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