Copyright updated
[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 - 2011 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          * Instance of the list
88          */
89         private $listInstance = null;
90
91         /**
92          * Instance of a menu
93          */
94         private $menuInstance = null;
95
96         /**
97          * Instance of the image
98          */
99         private $imageInstance = null;
100
101         /**
102          * Instance of the stacker
103          */
104         private $stackerInstance = null;
105
106         /**
107          * A Compressor instance
108          */
109         private $compressorInstance = null;
110
111         /**
112          * A Parseable instance
113          */
114         private $parserInstance = null;
115
116         /**
117          * A ProtocolHandler instance
118          */
119         private $protocolInstance = null;
120
121         /**
122          * A database wrapper instance
123          */
124         private $databaseInstance = null;
125
126         /**
127          * The real class name
128          */
129         private $realClass = 'BaseFrameworkSystem';
130
131         /**
132          * Thousands seperator
133          */
134         private $thousands = '.'; // German
135
136         /**
137          * Decimal seperator
138          */
139         private $decimals  = ','; // German
140
141         /**
142          * Socket resource
143          */
144         private $socketResource = false;
145
146         /**
147          * Package data
148          */
149         private $packageData = array();
150
151         /***********************
152          * Exception codes.... *
153          ***********************/
154         // @todo Try to clean these constants up
155         const EXCEPTION_IS_NULL_POINTER              = 0x001;
156         const EXCEPTION_IS_NO_OBJECT                 = 0x002;
157         const EXCEPTION_IS_NO_ARRAY                  = 0x003;
158         const EXCEPTION_MISSING_METHOD               = 0x004;
159         const EXCEPTION_CLASSES_NOT_MATCHING         = 0x005;
160         const EXCEPTION_INDEX_OUT_OF_BOUNDS          = 0x006;
161         const EXCEPTION_DIMENSION_ARRAY_INVALID      = 0x007;
162         const EXCEPTION_ITEM_NOT_TRADEABLE           = 0x008;
163         const EXCEPTION_ITEM_NOT_IN_PRICE_LIST       = 0x009;
164         const EXCEPTION_GENDER_IS_WRONG              = 0x00a;
165         const EXCEPTION_BIRTH_DATE_IS_INVALID        = 0x00b;
166         const EXCEPTION_EMPTY_STRUCTURES_ARRAY       = 0x00c;
167         const EXCEPTION_HAS_ALREADY_PERSONELL_LIST   = 0x00d;
168         const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES      = 0x00e;
169         const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED   = 0x00f;
170         const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS      = 0x010;
171         const EXCEPTION_CONTRACT_PARTNER_INVALID     = 0x011;
172         const EXCEPTION_CONTRACT_PARTNER_MISMATCH    = 0x012;
173         const EXCEPTION_CONTRACT_ALREADY_SIGNED      = 0x013;
174         const EXCEPTION_UNEXPECTED_EMPTY_STRING      = 0x014;
175         const EXCEPTION_PATH_NOT_FOUND               = 0x015;
176         const EXCEPTION_INVALID_PATH_NAME            = 0x016;
177         const EXCEPTION_READ_PROTECED_PATH           = 0x017;
178         const EXCEPTION_WRITE_PROTECED_PATH          = 0x018;
179         const EXCEPTION_DIR_POINTER_INVALID          = 0x019;
180         const EXCEPTION_FILE_POINTER_INVALID         = 0x01a;
181         const EXCEPTION_INVALID_RESOURCE             = 0x01b;
182         const EXCEPTION_UNEXPECTED_OBJECT            = 0x01c;
183         const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
184         const EXCEPTION_GETTER_IS_MISSING            = 0x01e;
185         const EXCEPTION_ARRAY_EXPECTED               = 0x01f;
186         const EXCEPTION_ARRAY_HAS_INVALID_COUNT      = 0x020;
187         const EXCEPTION_ID_IS_INVALID_FORMAT         = 0x021;
188         const EXCEPTION_MD5_CHECKSUMS_MISMATCH       = 0x022;
189         const EXCEPTION_UNEXPECTED_STRING_SIZE       = 0x023;
190         const EXCEPTION_SIMULATOR_ID_INVALID         = 0x024;
191         const EXCEPTION_MISMATCHING_COMPRESSORS      = 0x025;
192         const EXCEPTION_CONTAINER_ITEM_IS_NULL       = 0x026;
193         const EXCEPTION_ITEM_IS_NO_ARRAY             = 0x027;
194         const EXCEPTION_CONTAINER_MAYBE_DAMAGED      = 0x028;
195         const EXCEPTION_INVALID_STRING               = 0x029;
196         const EXCEPTION_VARIABLE_NOT_SET             = 0x02a;
197         const EXCEPTION_ATTRIBUTES_ARE_MISSING       = 0x02b;
198         const EXCEPTION_ARRAY_ELEMENTS_MISSING       = 0x02c;
199         const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED  = 0x02d;
200         const EXCEPTION_MISSING_LANGUAGE_HANDLER     = 0x02e;
201         const EXCEPTION_MISSING_FILE_IO_HANDLER      = 0x02f;
202         const EXCEPTION_MISSING_ELEMENT              = 0x030;
203         const EXCEPTION_HEADERS_ALREADY_SENT         = 0x031;
204         const EXCEPTION_DEFAULT_CONTROLLER_GONE      = 0x032;
205         const EXCEPTION_CLASS_NOT_FOUND              = 0x033;
206         const EXCEPTION_REQUIRED_INTERFACE_MISSING   = 0x034;
207         const EXCEPTION_FATAL_ERROR                  = 0x035;
208         const EXCEPTION_FILE_NOT_FOUND               = 0x036;
209         const EXCEPTION_ASSERTION_FAILED             = 0x037;
210         const EXCEPTION_FILE_CANNOT_BE_READ          = 0x038;
211         const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
212         const EXCEPTION_FILTER_CHAIN_INTERCEPTED     = 0x040;
213
214         /**
215          * Protected super constructor
216          *
217          * @param       $className      Name of the class
218          * @return      void
219          */
220         protected function __construct ($className) {
221                 // Set real class
222                 $this->setRealClass($className);
223
224                 // Set configuration instance if no registry
225                 if (!$this instanceof Register) {
226                         // Because registries doesn't need to be configured
227                         $this->setConfigInstance(FrameworkConfiguration::getInstance());
228                 } // END - if
229         }
230
231         /**
232          * Destructor reached...
233          *
234          * @return      void
235          * @todo        This is old code. Do we still need this old lost code?
236          */
237         public function __destruct() {
238                 // Flush any updated entries to the database
239                 $this->flushPendingUpdates();
240
241                 // Is this object already destroyed?
242                 if ($this->__toString() != 'DestructedObject') {
243                         // Destroy all informations about this class but keep some text about it alive
244                         $this->setRealClass('DestructedObject');
245                 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
246                         // Already destructed object
247                         $this->debugOutput(sprintf("[%s:] The object <span class=\"object_name\">%s</span> is already destroyed.",
248                                 __CLASS__,
249                                 $this->__toString()
250                         ));
251                 }
252         }
253
254         /**
255          * The call method where all non-implemented methods end up
256          *
257          * @return      void
258          */
259         public final function __call ($methodName, $args) {
260                 // Implode all given arguments
261                 $argsString = '';
262                 if (empty($args)) {
263                         // No arguments
264                         $argsString = 'NULL';
265                 } elseif (is_array($args)) {
266                         // Some arguments are there
267                         foreach ($args as $arg) {
268                                 // Add the type
269                                 $argsString .= $this->replaceControlCharacters($arg) . ' (' . gettype($arg);
270
271                                 // Add length if type is string
272                                 if (gettype($arg) == 'string') $argsString .= ', '.strlen($arg);
273
274                                 // Closing bracket
275                                 $argsString .= '), ';
276                         } // END - foreach
277
278                         // Remove last comma
279                         if (substr($argsString, -2, 1) == ',') {
280                                 $argsString = substr($argsString, 0, -2);
281                         } // END - if
282                 } else {
283                         // Invalid arguments!
284                         $argsString = '!INVALID:' . gettype($args) . '!';
285                 }
286
287                 // Output stub message
288                 $this->debugOutput(sprintf("[%s-&gt;%s] Stub! Args: %s",
289                         $this->__toString(),
290                         $methodName,
291                         $argsString
292                 ));
293
294                 // Return nothing
295                 return null;
296         }
297
298         /**
299          * Setter for database result instance
300          *
301          * @param       $resultInstance         An instance of a database result class
302          * @return      void
303          * @todo        SearchableResult and UpdateableResult shall have a super interface to use here
304          */
305         protected final function setResultInstance (SearchableResult $resultInstance) {
306                 $this->resultInstance =  $resultInstance;
307         }
308
309         /**
310          * Getter for database result instance
311          *
312          * @return      $resultInstance         An instance of a database result class
313          */
314         public final function getResultInstance () {
315                 return $this->resultInstance;
316         }
317
318         /**
319          * Setter for template engine instances
320          *
321          * @param       $templateInstance       An instance of a template engine class
322          * @return      void
323          */
324         protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
325                 $this->templateInstance = $templateInstance;
326         }
327
328         /**
329          * Getter for template engine instances
330          *
331          * @return      $templateInstance       An instance of a template engine class
332          */
333         protected final function getTemplateInstance () {
334                 return $this->templateInstance;
335         }
336
337         /**
338          * Setter for search instance
339          *
340          * @param       $searchInstance         Searchable criteria instance
341          * @return      void
342          */
343         public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
344                 $this->searchInstance = $searchInstance;
345         }
346
347         /**
348          * Getter for search instance
349          *
350          * @return      $searchInstance         Searchable criteria instance
351          */
352         public final function getSearchInstance () {
353                 return $this->searchInstance;
354         }
355
356         /**
357          * Setter for update instance
358          *
359          * @param       $updateInstance         Searchable criteria instance
360          * @return      void
361          */
362         public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
363                 $this->updateInstance = $updateInstance;
364         }
365
366         /**
367          * Getter for update instance
368          *
369          * @return      $updateInstance         Updateable criteria instance
370          */
371         public final function getUpdateInstance () {
372                 return $this->updateInstance;
373         }
374
375         /**
376          * Setter for resolver instance
377          *
378          * @param       $resolverInstance       Instance of a command resolver class
379          * @return      void
380          */
381         public final function setResolverInstance (Resolver $resolverInstance) {
382                 $this->resolverInstance = $resolverInstance;
383         }
384
385         /**
386          * Getter for resolver instance
387          *
388          * @return      $resolverInstance       Instance of a command resolver class
389          */
390         public final function getResolverInstance () {
391                 return $this->resolverInstance;
392         }
393
394         /**
395          * Setter for language instance
396          *
397          * @param       $configInstance         The configuration instance which shall
398          *                                                              be FrameworkConfiguration
399          * @return      void
400          */
401         public final function setConfigInstance (FrameworkConfiguration $configInstance) {
402                 Registry::getRegistry()->addInstance('config', $configInstance);
403         }
404
405         /**
406          * Getter for configuration instance
407          *
408          * @return      $configInstance         Configuration instance
409          */
410         public final function getConfigInstance () {
411                 $configInstance = Registry::getRegistry()->getInstance('config');
412                 return $configInstance;
413         }
414
415         /**
416          * Setter for debug instance
417          *
418          * @param       $debugInstance  The instance for debug output class
419          * @return      void
420          */
421         public final function setDebugInstance (DebugMiddleware $debugInstance) {
422                 Registry::getRegistry()->addInstance('debug', $debugInstance);
423         }
424
425         /**
426          * Getter for debug instance
427          *
428          * @return      $debugInstance  Instance to class DebugConsoleOutput or DebugWebOutput
429          */
430         public final function getDebugInstance () {
431                 // Get debug instance
432                 $debugInstance = Registry::getRegistry()->getInstance('debug');
433
434                 // Return it
435                 return $debugInstance;
436         }
437
438         /**
439          * Setter for web output instance
440          *
441          * @param               $webInstance    The instance for web output class
442          * @return      void
443          */
444         public final function setWebOutputInstance (OutputStreamer $webInstance) {
445                 Registry::getRegistry()->addInstance('web_output', $webInstance);
446         }
447
448         /**
449          * Getter for web output instance
450          *
451          * @return      $webOutputInstance - Instance to class WebOutput
452          */
453         public final function getWebOutputInstance () {
454                 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
455                 return $webOutputInstance;
456         }
457
458         /**
459          * Setter for database instance
460          *
461          * @param               $dbInstance     The instance for the database connection (forced DatabaseConnection)
462          * @return      void
463          */
464         public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
465                 Registry::getRegistry()->addInstance('db_instance', $dbInstance);
466         }
467
468         /**
469          * Getter for database layer
470          *
471          * @return      $dbInstance     The database layer instance
472          */
473         public final function getDatabaseInstance () {
474                 // Get instance
475                 $dbInstance = Registry::getRegistry()->getInstance('db_instance');
476
477                 // Return instance
478                 return $dbInstance;
479         }
480
481         /**
482          * Setter for compressor channel
483          *
484          * @param               $compressorInstance             An instance of CompressorChannel
485          * @return      void
486          */
487         public final function setCompressorChannel (CompressorChannel $compressorInstance) {
488                 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
489         }
490
491         /**
492          * Getter for compressor channel
493          *
494          * @return      $compressorInstance             The compressor channel
495          */
496         public final function getCompressorChannel () {
497                 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
498                 return $compressorInstance;
499         }
500
501         /**
502          * Protected getter for a manageable application helper class
503          *
504          * @return      $applicationInstance    An instance of a manageable application helper class
505          */
506         protected final function getApplicationInstance () {
507                 $applicationInstance = Registry::getRegistry()->getInstance('application');
508                 return $applicationInstance;
509         }
510
511         /**
512          * Setter for a manageable application helper class
513          *
514          * @param       $applicationInstance    An instance of a manageable application helper class
515          * @return      void
516          */
517         public final function setApplicationInstance (ManageableApplication $applicationInstance) {
518                 Registry::getRegistry()->addInstance('application', $applicationInstance);
519         }
520
521         /**
522          * Setter for request instance
523          *
524          * @param       $requestInstance        An instance of a Requestable class
525          * @return      void
526          */
527         public final function setRequestInstance (Requestable $requestInstance) {
528                 $this->requestInstance = $requestInstance;
529         }
530
531         /**
532          * Getter for request instance
533          *
534          * @return      $requestInstance        An instance of a Requestable class
535          */
536         public final function getRequestInstance () {
537                 return $this->requestInstance;
538         }
539
540         /**
541          * Setter for response instance
542          *
543          * @param       $responseInstance       An instance of a Responseable class
544          * @return      void
545          */
546         public final function setResponseInstance (Responseable $responseInstance) {
547                 $this->responseInstance = $responseInstance;
548         }
549
550         /**
551          * Getter for response instance
552          *
553          * @return      $responseInstance       An instance of a Responseable class
554          */
555         public final function getResponseInstance () {
556                 return $this->responseInstance;
557         }
558
559         /**
560          * Getter for $realClass
561          *
562          * @return      $realClass The name of the real class (not BaseFrameworkSystem)
563          */
564         public function __toString () {
565                 return $this->realClass;
566         }
567
568         /**
569          * Setter for the real class name
570          *
571          * @param               $realClass      Class name (string)
572          * @return      void
573          */
574         public final function setRealClass ($realClass) {
575                 // Cast to string
576                 $realClass = (string) $realClass;
577
578                 // Set real class
579                 $this->realClass = $realClass;
580         }
581
582         /**
583          * Checks wether an object equals this object. You should overwrite this
584          * method to implement own equality checks
585          *
586          * @param       $objectInstance         An instance of a FrameworkInterface object
587          * @return      $equals                         Wether both objects equals
588          */
589         public function equals (FrameworkInterface $objectInstance) {
590                 // Now test it
591                 $equals = ((
592                         $this->__toString() == $objectInstance->__toString()
593                 ) && (
594                         $this->hashCode() == $objectInstance->hashCode()
595                 ));
596
597                 // Return the result
598                 return $equals;
599         }
600
601         /**
602          * Generates a generic hash code of this class. You should really overwrite
603          * this method with your own hash code generator code. But keep KISS in mind.
604          *
605          * @return      $hashCode       A generic hash code respresenting this whole class
606          */
607         public function hashCode () {
608                 // Simple hash code
609                 return crc32($this->__toString());
610         }
611
612         /**
613          * Formats computer generated price values into human-understandable formats
614          * with thousand and decimal seperators.
615          *
616          * @param       $value          The in computer format value for a price
617          * @param       $currency       The currency symbol (use HTML-valid characters!)
618          * @param       $decNum         Number of decimals after commata
619          * @return      $price          The for the current language formated price string
620          * @throws      MissingDecimalsThousandsSeperatorException      If decimals or
621          *                                                                                              thousands seperator
622          *                                                                                              is missing
623          */
624         public function formatCurrency ($value, $currency = '&euro;', $decNum = 2) {
625                 // Are all required attriutes set?
626                 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
627                         // Throw an exception
628                         throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
629                 }
630
631                 // Cast the number
632                 $value = (float) $value;
633
634                 // Reformat the US number
635                 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
636
637                 // Return as string...
638                 return $price;
639         }
640
641         /**
642          * Private getter for language instance
643          *
644          * @return      $langInstance   An instance to the language sub-system
645          */
646         protected final function getLanguageInstance () {
647                 $langInstance = Registry::getRegistry()->getInstance('language');
648                 return $langInstance;
649         }
650
651         /**
652          * Setter for language instance
653          *
654          * @param       $langInstance   An instance to the language sub-system
655          * @return      void
656          * @see         LanguageSystem
657          */
658         public final function setLanguageInstance (ManageableLanguage $langInstance) {
659                 Registry::getRegistry()->addInstance('language', $langInstance);
660         }
661
662         /**
663          * Appends a trailing slash to a string
664          *
665          * @param       $str            A string (maybe) without trailing slash
666          * @return      $str            A string with an auto-appended trailing slash
667          */
668         public final function addMissingTrailingSlash ($str) {
669                 // Is there a trailing slash?
670                 if (substr($str, -1, 1) != '/') $str .= '/';
671                 return $str;
672         }
673
674         /**
675          * Private getter for file IO instance
676          *
677          * @return      $fileIoInstance An instance to the file I/O sub-system
678          */
679         protected final function getFileIoInstance () {
680                 return $this->fileIoInstance;
681         }
682
683         /**
684          * Setter for file I/O instance
685          *
686          * @param       $fileIoInstance An instance to the file I/O sub-system
687          * @return      void
688          */
689         public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
690                 $this->fileIoInstance = $fileIoInstance;
691         }
692
693         /**
694          * Prepare the template engine (WebTemplateEngine by default) for a given
695          * application helper instance (ApplicationHelper by default).
696          *
697          * @param               $appInstance                    An application helper instance or
698          *                                                                              null if we shall use the default
699          * @return              $templateInstance                               The template engine instance
700          * @throws              NullPointerException    If the template engine could not
701          *                                                                              be initialized
702          * @throws              UnsupportedTemplateEngineException      If $templateInstance is an
703          *                                                                              unsupported template engine
704          * @throws              MissingLanguageHandlerException If the language sub-system
705          *                                                                              is not yet initialized
706          * @throws              NullPointerException    If the discovered application
707          *                                                                              instance is still null
708          */
709         protected function prepareTemplateInstance (FrameworkInterface $appInstance=null) {
710                 // Is the application instance set?
711                 if (is_null($appInstance)) {
712                         // Get the current instance
713                         $appInstance = $this->getApplicationInstance();
714
715                         // Still null?
716                         if (is_null($appInstance)) {
717                                 // Thrown an exception
718                                 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
719                         } // END - if
720                 } // END - if
721
722                 // Are both instances set?
723                 if ($appInstance->getLanguageInstance() === null) {
724                         // Invalid language instance
725                         throw new MissingLanguageHandlerException($appInstance, self::EXCEPTION_MISSING_LANGUAGE_HANDLER);
726                 } elseif ($appInstance->getFileIoInstance() === null) {
727                         // Invalid language instance
728                         throw new MissingFileIoHandlerException($appInstance, self::EXCEPTION_MISSING_FILE_IO_HANDLER);
729                 }
730
731                 // Initialize the template engine
732                 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class', array($appInstance));
733
734                 // Return the prepared instance
735                 return $templateInstance;
736         }
737
738         /**
739          * Debugs this instance by putting out it's full content
740          *
741          * @param       $message        Optional message to show in debug output
742          * @return      void
743          */
744         public final function debugInstance ($message = '') {
745                 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
746                 restore_error_handler();
747
748                 // Init content
749                 $content = '';
750
751                 // Is a message set?
752                 if (!empty($message)) {
753                         // Construct message
754                         $content = sprintf("<div class=\"debug_message\">Message: %s</div>\n", $message);
755                 } // END - if
756
757                 // Generate the output
758                 $content .= sprintf("<pre>%s</pre>",
759                         trim(
760                                 htmlentities(
761                                         print_r($this, true)
762                                 )
763                         )
764                 );
765
766                 // Output it
767                 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>",
768                         $this->__toString(),
769                         $content,
770                         ClassLoader::getInstance()->getPrintableIncludeList()
771                 ));
772         }
773
774         /**
775          * Replaces control characters with printable output
776          *
777          * @param       $str    String with control characters
778          * @return      $str    Replaced string
779          */
780         protected function replaceControlCharacters ($str) {
781                 // Replace them
782                 $str = str_replace(
783                         "\r", '[r]', str_replace(
784                         "\n", '[n]', str_replace(
785                         "\t", '[t]',
786                         $str
787                 )));
788
789                 // Return it
790                 return $str;
791         }
792
793         /**
794          * Output a partial stub message for the caller method
795          *
796          * @param       $message        An optional message to display
797          * @return      void
798          */
799         protected function partialStub ($message = '') {
800                 // Get the backtrace
801                 $backtrace = debug_backtrace();
802
803                 // Generate the class::method string
804                 $methodName = 'UnknownClass-&gt;unknownMethod';
805                 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
806                         $methodName = $backtrace[1]['class']."-&gt;".$backtrace[1]['function'];
807                 } // END - if
808
809                 // Construct the full message
810                 $stubMessage = sprintf("[%s:] Partial stub!",
811                         $methodName
812                 );
813
814                 // Is the extra message given?
815                 if (!empty($message)) {
816                         // Then add it as well
817                         $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
818                 } // END - if
819
820                 // Debug instance is there?
821                 if (!is_null($this->getDebugInstance())) {
822                         // Output stub message
823                         $this->debugOutput($stubMessage);
824                 } else {
825                         // Trigger an error
826                         trigger_error($stubMessage."<br />\n");
827                 }
828         }
829
830         /**
831          * Outputs a debug backtrace and stops further script execution
832          *
833          * @return      void
834          */
835         public function debugBackTrace () {
836                 // Sorry, there is no other way getting this nice backtrace
837                 print("<pre>\n");
838                 debug_print_backtrace();
839                 print("</pre>");
840                 exit();
841         }
842
843         /**
844          * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
845          *
846          * @param       $message        Message we shall send out...
847          * @param       $doPrint        Wether we shall print or die here which first is the default
848          * @return      void
849          */
850         public function debugOutput ($message, $doPrint = true) {
851                 // Get debug instance
852                 $debugInstance = $this->getDebugInstance();
853
854                 // Is the debug instance there?
855                 if (is_object($debugInstance)) {
856                         // Use debug output handler
857                         $debugInstance->output($message);
858                         if ($doPrint === false) die(); // Die here if not printed
859                 } else {
860                         // Put directly out
861                         if ($doPrint === true) {
862                                 print($message);
863                         } else {
864                                 // DO NOT REWRITE THIS TO app_die() !!!
865                                 die($message);
866                         }
867                 }
868         }
869
870         /**
871          * Converts e.g. a command from URL to a valid class by keeping out bad characters
872          *
873          * @param       $str            The string, what ever it is needs to be converted
874          * @return      $className      Generated class name
875          */
876         public function convertToClassName ($str) {
877                 // Init class name
878                 $className = '';
879
880                 // Convert all dashes in underscores
881                 $str = $this->convertDashesToUnderscores($str);
882
883                 // Now use that underscores to get classname parts for hungarian style
884                 foreach (explode('_', $str) as $strPart) {
885                         // Make the class name part lower case and first upper case
886                         $className .= ucfirst(strtolower($strPart));
887                 } // END - foreach
888
889                 // Return class name
890                 return $className;
891         }
892
893         /**
894          * Converts dashes to underscores, e.g. useable for configuration entries
895          *
896          * @param       $str    The string with maybe dashes inside
897          * @return      $str    The converted string with no dashed, but underscores
898          */
899         public final function convertDashesToUnderscores ($str) {
900                 // Convert them all
901                 $str = str_replace('-', '_', $str);
902
903                 // Return converted string
904                 return $str;
905         }
906
907         /**
908          * Marks up the code by adding e.g. line numbers
909          *
910          * @param       $phpCode                Unmarked PHP code
911          * @return      $markedCode             Marked PHP code
912          */
913         public function markupCode ($phpCode) {
914                 // Init marked code
915                 $markedCode = '';
916
917                 // Get last error
918                 $errorArray = error_get_last();
919
920                 // Init the code with error message
921                 if (is_array($errorArray)) {
922                         // Get error infos
923                         $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>",
924                                 basename($errorArray['file']),
925                                 $errorArray['line'],
926                                 $errorArray['message'],
927                                 $errorArray['type']
928                         );
929                 } // END - if
930
931                 // Add line number to the code
932                 foreach (explode("\n", $phpCode) as $lineNo => $code) {
933                         // Add line numbers
934                         $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
935                                 ($lineNo + 1),
936                                 htmlentities($code, ENT_QUOTES)
937                         );
938                 } // END - foreach
939
940                 // Return the code
941                 return $markedCode;
942         }
943
944         /**
945          * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
946          * beatiful for web-based front-ends. If null is given a message id
947          * null_timestamp will be resolved and returned.
948          *
949          * @param       $timestamp      Timestamp to prepare (filter) for display
950          * @return      $readable       A readable timestamp
951          */
952         public function doFilterFormatTimestamp ($timestamp) {
953                 // Default value to return
954                 $readable = '???';
955
956                 // Is the timestamp null?
957                 if (is_null($timestamp)) {
958                         // Get a message string
959                         $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
960                 } else {
961                         switch ($this->getLanguageInstance()->getLanguageCode()) {
962                                 case 'de': // German format is a bit different to default
963                                         // Split the GMT stamp up
964                                         $dateTime  = explode(' ', $timestamp  );
965                                         $dateArray = explode('-', $dateTime[0]);
966                                         $timeArray = explode(':', $dateTime[1]);
967
968                                         // Construct the timestamp
969                                         $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
970                                                 $dateArray[0],
971                                                 $dateArray[1],
972                                                 $dateArray[2],
973                                                 $timeArray[0],
974                                                 $timeArray[1],
975                                                 $timeArray[2]
976                                         );
977                                         break;
978
979                                 default: // Default is pass-through
980                                         $readable = $timestamp;
981                                         break;
982                         } // END - switch
983                 }
984
985                 // Return the stamp
986                 return $readable;
987         }
988
989         /**
990          * Filter a given number into a localized number
991          *
992          * @param       $value          The raw value from e.g. database
993          * @return      $localized      Localized value
994          */
995         public function doFilterFormatNumber ($value) {
996                 // Generate it from config and localize dependencies
997                 switch ($this->getLanguageInstance()->getLanguageCode()) {
998                         case 'de': // German format is a bit different to default
999                                 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1000                                 break;
1001
1002                         default: // US, etc.
1003                                 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1004                                 break;
1005                 } // END - switch
1006
1007                 // Return it
1008                 return $localized;
1009         }
1010
1011         /**
1012          * "Getter" for databse entry
1013          *
1014          * @return      $entry  An array with database entries
1015          * @throws      NullPointerException    If the database result is not found
1016          * @throws      InvalidDatabaseResultException  If the database result is invalid
1017          */
1018         protected final function getDatabaseEntry () {
1019                 // Is there an instance?
1020                 if (is_null($this->getResultInstance())) {
1021                         // Throw an exception here
1022                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1023                 } // END - if
1024
1025                 // Rewind it
1026                 $this->getResultInstance()->rewind();
1027
1028                 // Do we have an entry?
1029                 if ($this->getResultInstance()->valid() === false) {
1030                         throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1031                 } // END - if
1032
1033                 // Get next entry
1034                 $this->getResultInstance()->next();
1035
1036                 // Fetch it
1037                 $entry = $this->getResultInstance()->current();
1038
1039                 // And return it
1040                 return $entry;
1041         }
1042
1043         /**
1044          * Getter for field name
1045          *
1046          * @param       $fieldName              Field name which we shall get
1047          * @return      $fieldValue             Field value from the user
1048          * @throws      NullPointerException    If the result instance is null
1049          */
1050         public final function getField ($fieldName) {
1051                 // Default field value
1052                 $fieldValue = null;
1053
1054                 // Get result instance
1055                 $resultInstance = $this->getResultInstance();
1056
1057                 // Is this instance null?
1058                 if (is_null($resultInstance)) {
1059                         // Then the user instance is no longer valid (expired cookies?)
1060                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1061                 } // END - if
1062
1063                 // Get current array
1064                 $fieldArray = $resultInstance->current();
1065                 //* DEBUG: */ $this->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1066
1067                 // Does the field exist?
1068                 if (isset($fieldArray[$fieldName])) {
1069                         // Get it
1070                         $fieldValue = $fieldArray[$fieldName];
1071                 } // END - if
1072
1073                 // Return it
1074                 return $fieldValue;
1075         }
1076
1077         /**
1078          * Protected setter for user instance
1079          *
1080          * @param       $userInstance   An instance of a user class
1081          * @return      void
1082          */
1083         protected final function setUserInstance (ManageableAccount $userInstance) {
1084                 $this->userInstance = $userInstance;
1085         }
1086
1087         /**
1088          * Getter for user instance
1089          *
1090          * @return      $userInstance   An instance of a user class
1091          */
1092         public final function getUserInstance () {
1093                 return $this->userInstance;
1094         }
1095
1096         /**
1097          * Setter for controller instance (this surely breaks a bit the MVC patterm)
1098          *
1099          * @param       $controllerInstance             An instance of the controller
1100          * @return      void
1101          */
1102         public final function setControllerInstance (Controller $controllerInstance) {
1103                 $this->controllerInstance = $controllerInstance;
1104         }
1105
1106         /**
1107          * Getter for controller instance (this surely breaks a bit the MVC patterm)
1108          *
1109          * @return      $controllerInstance             An instance of the controller
1110          */
1111         public final function getControllerInstance () {
1112                 return $this->controllerInstance;
1113         }
1114
1115         /**
1116          * Flushs all pending updates to the database layer
1117          *
1118          * @return      void
1119          */
1120         public function flushPendingUpdates () {
1121                 // Get result instance
1122                 $resultInstance = $this->getResultInstance();
1123
1124                 // Do we have data to update?
1125                 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1126                         // Get wrapper class name config entry
1127                         $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1128
1129                         // Create object instance
1130                         $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1131
1132                         // Yes, then send the whole result to the database layer
1133                         $wrapperInstance->doUpdateByResult($this->getResultInstance());
1134                 } // END - if
1135         }
1136
1137         /**
1138          * Outputs a deprecation warning to the developer.
1139          *
1140          * @param       $message        The message we shall output to the developer
1141          * @return      void
1142          * @todo        Write a logging mechanism for productive mode
1143          */
1144         public function deprecationWarning ($message) {
1145                 // Is developer mode active?
1146                 if (defined('DEVELOPER')) {
1147                         // Debug instance is there?
1148                         if (!is_null($this->getDebugInstance())) {
1149                                 // Output stub message
1150                                 $this->debugOutput($message);
1151                         } else {
1152                                 // Trigger an error
1153                                 trigger_error($message."<br />\n");
1154                         }
1155                 } else {
1156                         // @TODO Finish this part!
1157                         $this->partialStub('Developer mode inactive. Message:' . $message);
1158                 }
1159         }
1160
1161         /**
1162          * Checks wether the given PHP extension is loaded
1163          *
1164          * @param       $phpExtension   The PHP extension we shall check
1165          * @return      $isLoaded       Wether the PHP extension is loaded
1166          */
1167         public final function isPhpExtensionLoaded ($phpExtension) {
1168                 // Is it loaded?
1169                 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1170
1171                 // Return result
1172                 return $isLoaded;
1173         }
1174
1175         /**
1176          * Setter for RNG instance
1177          *
1178          * @param       $rngInstance    An instance of a random number generator (RNG)
1179          * @return      void
1180          */
1181         protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1182                 $this->rngInstance = $rngInstance;
1183         }
1184
1185         /**
1186          * Getter for RNG instance
1187          *
1188          * @return      $rngInstance    An instance of a random number generator (RNG)
1189          */
1190         public final function getRngInstance () {
1191                 return $this->rngInstance;
1192         }
1193
1194         /**
1195          * Setter for Iterator instance
1196          *
1197          * @param       $iteratorInstance       An instance of an Iterator
1198          * @return      void
1199          */
1200         protected final function setIteratorInstance (Iterator $iteratorInstance) {
1201                 $this->iteratorInstance = $iteratorInstance;
1202         }
1203
1204         /**
1205          * Getter for Iterator instance
1206          *
1207          * @return      $iteratorInstance       An instance of an Iterator
1208          */
1209         public final function getIteratorInstance () {
1210                 return $this->iteratorInstance;
1211         }
1212
1213         /**
1214          * "Getter" as a time() replacement but with milliseconds. You should use this
1215          * method instead of the encapsulated getimeofday() function.
1216          *
1217          * @return      $milliTime      Timestamp with milliseconds
1218          */
1219         public function getMilliTime () {
1220                 // Get the time of day as float
1221                 $milliTime = gettimeofday(true);
1222
1223                 // Return it
1224                 return $milliTime;
1225         }
1226
1227         /**
1228          * Idles (sleeps) for given milliseconds
1229          *
1230          * @return      $hasSlept       Wether it goes fine
1231          */
1232         public function idle ($milliSeconds) {
1233                 // Sleep is fine by default
1234                 $hasSlept = true;
1235
1236                 // Idle so long with found function
1237                 if (function_exists('time_sleep_until')) {
1238                         // Get current time and add idle time
1239                         $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1240
1241                         // New PHP 5.1.0 function found
1242                         $hasSlept = time_sleep_until($sleepUntil);
1243                 } else {
1244                         // My Sun Station doesn't have that function even with latest PHP
1245                         // package. :(
1246                         usleep($milliSeconds * 1000);
1247                 }
1248
1249                 // Return result
1250                 return $hasSlept;
1251         }
1252
1253         /**
1254          * Setter for the list instance
1255          *
1256          * @param       $listInstance   A list of Listable
1257          * @return      void
1258          */
1259         protected final function setListInstance (Listable $listInstance) {
1260                 $this->listInstance = $listInstance;
1261         }
1262
1263         /**
1264          * Getter for the list instance
1265          *
1266          * @return      $listInstance   A list of Listable
1267          */
1268         protected final function getListInstance () {
1269                 return $this->listInstance;
1270         }
1271
1272         /**
1273          * Setter for the menu instance
1274          *
1275          * @param       $menuInstance   A RenderableMenu instance
1276          * @return      void
1277          */
1278         protected final function setMenuInstance (RenderableMenu $menuInstance) {
1279                 $this->menuInstance = $menuInstance;
1280         }
1281
1282         /**
1283          * Getter for the menu instance
1284          *
1285          * @return      $menuInstance   A RenderableMenu instance
1286          */
1287         protected final function getMenuInstance () {
1288                 return $this->menuInstance;
1289         }
1290
1291         /**
1292          * Setter for image instance
1293          *
1294          * @param       $imageInstance  An instance of an image
1295          * @return      void
1296          */
1297         public final function setImageInstance (BaseImage $imageInstance) {
1298                 $this->imageInstance = $imageInstance;
1299         }
1300
1301         /**
1302          * Getter for image instance
1303          *
1304          * @return      $imageInstance  An instance of an image
1305          */
1306         public final function getImageInstance () {
1307                 return $this->imageInstance;
1308         }
1309
1310         /**
1311          * Setter for stacker instance
1312          *
1313          * @param       $stackerInstance        An instance of an stacker
1314          * @return      void
1315          */
1316         public final function setStackerInstance (Stackable $stackerInstance) {
1317                 $this->stackerInstance = $stackerInstance;
1318         }
1319
1320         /**
1321          * Getter for stacker instance
1322          *
1323          * @return      $stackerInstance        An instance of an stacker
1324          */
1325         public final function getStackerInstance () {
1326                 return $this->stackerInstance;
1327         }
1328
1329         /**
1330          * Setter for compressor instance
1331          *
1332          * @param       $compressorInstance     An instance of an compressor
1333          * @return      void
1334          */
1335         public final function setCompressorInstance (Compressor $compressorInstance) {
1336                 $this->compressorInstance = $compressorInstance;
1337         }
1338
1339         /**
1340          * Getter for compressor instance
1341          *
1342          * @return      $compressorInstance     An instance of an compressor
1343          */
1344         public final function getCompressorInstance () {
1345                 return $this->compressorInstance;
1346         }
1347
1348         /**
1349          * Setter for Parseable instance
1350          *
1351          * @param       $parserInstance An instance of an Parseable
1352          * @return      void
1353          */
1354         public final function setParserInstance (Parseable $parserInstance) {
1355                 $this->parserInstance = $parserInstance;
1356         }
1357
1358         /**
1359          * Getter for Parseable instance
1360          *
1361          * @return      $parserInstance An instance of an Parseable
1362          */
1363         public final function getParserInstance () {
1364                 return $this->parserInstance;
1365         }
1366
1367         /**
1368          * Setter for ProtocolHandler instance
1369          *
1370          * @param       $protocolInstance       An instance of an ProtocolHandler
1371          * @return      void
1372          */
1373         public final function setProtocolInstance (ProtocolHandler $protocolInstance) {
1374                 $this->protocolInstance = $protocolInstance;
1375         }
1376
1377         /**
1378          * Getter for ProtocolHandler instance
1379          *
1380          * @return      $protocolInstance       An instance of an ProtocolHandler
1381          */
1382         public final function getProtocolInstance () {
1383                 return $this->protocolInstance;
1384         }
1385
1386         /**
1387          * Setter for BaseDatabaseWrapper instance
1388          *
1389          * @param       $wrapperInstance        An instance of an BaseDatabaseWrapper
1390          * @return      void
1391          */
1392         public final function setWrapperInstance (BaseDatabaseWrapper $wrapperInstance) {
1393                 $this->wrapperInstance = $wrapperInstance;
1394         }
1395
1396         /**
1397          * Getter for BaseDatabaseWrapper instance
1398          *
1399          * @return      $wrapperInstance        An instance of an BaseDatabaseWrapper
1400          */
1401         public final function getWrapperInstance () {
1402                 return $this->wrapperInstance;
1403         }
1404
1405         /**
1406          * Setter for socket resource
1407          *
1408          * @param       $socketResource         A valid socket resource
1409          * @return      void
1410          */
1411         public final function setSocketResource ($socketResource) {
1412                 $this->socketResource = $socketResource;
1413         }
1414
1415         /**
1416          * Getter for socket resource
1417          *
1418          * @return      $socketResource         A valid socket resource
1419          */
1420         public function getSocketResource () {
1421                 return $this->socketResource;
1422         }
1423
1424         /**
1425          * Setter for raw package Data
1426          *
1427          * @param       $packageData    Raw package Data
1428          * @return      void
1429          */
1430         public final function setPackageData (array $packageData) {
1431                 $this->packageData = $packageData;
1432         }
1433
1434         /**
1435          * Getter for raw package Data
1436          *
1437          * @return      $packageData    Raw package Data
1438          */
1439         public function getPackageData () {
1440                 return $this->packageData;
1441         }
1442 }
1443
1444 // [EOF]
1445 ?>