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