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