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