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