Moved back to 'hub' project
[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 - 2012 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          * The real class name
28          */
29         private $realClass = 'BaseFrameworkSystem';
30
31         /**
32          * Instance of a request class
33          */
34         private $requestInstance = NULL;
35
36         /**
37          * Instance of a response class
38          */
39         private $responseInstance = NULL;
40
41         /**
42          * Search criteria instance
43          */
44         private $searchInstance = NULL;
45
46         /**
47          * Update criteria instance
48          */
49         private $updateInstance = NULL;
50
51         /**
52          * The file I/O instance for the template loader
53          */
54         private $fileIoInstance = NULL;
55
56         /**
57          * Resolver instance
58          */
59         private $resolverInstance = NULL;
60
61         /**
62          * Template engine instance
63          */
64         private $templateInstance = NULL;
65
66         /**
67          * Database result instance
68          */
69         private $resultInstance = NULL;
70
71         /**
72          * Instance for user class
73          */
74         private $userInstance = NULL;
75
76         /**
77          * A controller instance
78          */
79         private $controllerInstance = NULL;
80
81         /**
82          * Instance of a RNG
83          */
84         private $rngInstance = NULL;
85
86         /**
87          * Instance of a crypto helper
88          */
89         private $cryptoInstance = NULL;
90
91         /**
92          * Instance of an Iterator class
93          */
94         private $iteratorInstance = NULL;
95
96         /**
97          * Instance of the list
98          */
99         private $listInstance = NULL;
100
101         /**
102          * Instance of a menu
103          */
104         private $menuInstance = NULL;
105
106         /**
107          * Instance of the image
108          */
109         private $imageInstance = NULL;
110
111         /**
112          * Instance of the stacker
113          */
114         private $stackerInstance = NULL;
115
116         /**
117          * A Compressor instance
118          */
119         private $compressorInstance = NULL;
120
121         /**
122          * A Parseable instance
123          */
124         private $parserInstance = NULL;
125
126         /**
127          * A ProtocolHandler instance
128          */
129         private $protocolInstance = NULL;
130
131         /**
132          * A database wrapper instance
133          */
134         private $databaseInstance = NULL;
135
136         /**
137          * A helper instance for the form
138          */
139         private $helperInstance = NULL;
140
141         /**
142          * An instance of a Sourceable class
143          */
144         private $sourceInstance = NULL;
145
146         /**
147          * An instance of a InputStreamable class
148          */
149         private $inputStreamInstance = NULL;
150
151         /**
152          * An instance of a OutputStreamable class
153          */
154         private $outputStreamInstance = NULL;
155
156         /**
157          * Networkable handler instance
158          */
159         private $handlerInstance = NULL;
160
161         /**
162          * Visitor handler instance
163          */
164         private $visitorInstance = NULL;
165
166         /**
167          * An instance of a database wrapper class
168          */
169         private $wrapperInstance = NULL;
170
171         /**
172          * Thousands separator
173          */
174         private $thousands = '.'; // German
175
176         /**
177          * Decimal separator
178          */
179         private $decimals  = ','; // German
180
181         /**
182          * Socket resource
183          */
184         private $socketResource = false;
185
186         /**
187          * Package data
188          */
189         private $packageData = array();
190
191         /***********************
192          * Exception codes.... *
193          ***********************/
194
195         // @todo Try to clean these constants up
196         const EXCEPTION_IS_NULL_POINTER              = 0x001;
197         const EXCEPTION_IS_NO_OBJECT                 = 0x002;
198         const EXCEPTION_IS_NO_ARRAY                  = 0x003;
199         const EXCEPTION_MISSING_METHOD               = 0x004;
200         const EXCEPTION_CLASSES_NOT_MATCHING         = 0x005;
201         const EXCEPTION_INDEX_OUT_OF_BOUNDS          = 0x006;
202         const EXCEPTION_DIMENSION_ARRAY_INVALID      = 0x007;
203         const EXCEPTION_ITEM_NOT_TRADEABLE           = 0x008;
204         const EXCEPTION_ITEM_NOT_IN_PRICE_LIST       = 0x009;
205         const EXCEPTION_GENDER_IS_WRONG              = 0x00a;
206         const EXCEPTION_BIRTH_DATE_IS_INVALID        = 0x00b;
207         const EXCEPTION_EMPTY_STRUCTURES_ARRAY       = 0x00c;
208         const EXCEPTION_HAS_ALREADY_PERSONELL_LIST   = 0x00d;
209         const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES      = 0x00e;
210         const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED   = 0x00f;
211         const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS      = 0x010;
212         const EXCEPTION_CONTRACT_PARTNER_INVALID     = 0x011;
213         const EXCEPTION_CONTRACT_PARTNER_MISMATCH    = 0x012;
214         const EXCEPTION_CONTRACT_ALREADY_SIGNED      = 0x013;
215         const EXCEPTION_UNEXPECTED_EMPTY_STRING      = 0x014;
216         const EXCEPTION_PATH_NOT_FOUND               = 0x015;
217         const EXCEPTION_INVALID_PATH_NAME            = 0x016;
218         const EXCEPTION_READ_PROTECED_PATH           = 0x017;
219         const EXCEPTION_WRITE_PROTECED_PATH          = 0x018;
220         const EXCEPTION_DIR_POINTER_INVALID          = 0x019;
221         const EXCEPTION_FILE_POINTER_INVALID         = 0x01a;
222         const EXCEPTION_INVALID_RESOURCE             = 0x01b;
223         const EXCEPTION_UNEXPECTED_OBJECT            = 0x01c;
224         const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
225         const EXCEPTION_GETTER_IS_MISSING            = 0x01e;
226         const EXCEPTION_ARRAY_EXPECTED               = 0x01f;
227         const EXCEPTION_ARRAY_HAS_INVALID_COUNT      = 0x020;
228         const EXCEPTION_ID_IS_INVALID_FORMAT         = 0x021;
229         const EXCEPTION_MD5_CHECKSUMS_MISMATCH       = 0x022;
230         const EXCEPTION_UNEXPECTED_STRING_SIZE       = 0x023;
231         const EXCEPTION_SIMULATOR_ID_INVALID         = 0x024;
232         const EXCEPTION_MISMATCHING_COMPRESSORS      = 0x025;
233         const EXCEPTION_CONTAINER_ITEM_IS_NULL       = 0x026;
234         const EXCEPTION_ITEM_IS_NO_ARRAY             = 0x027;
235         const EXCEPTION_CONTAINER_MAYBE_DAMAGED      = 0x028;
236         const EXCEPTION_INVALID_STRING               = 0x029;
237         const EXCEPTION_VARIABLE_NOT_SET             = 0x02a;
238         const EXCEPTION_ATTRIBUTES_ARE_MISSING       = 0x02b;
239         const EXCEPTION_ARRAY_ELEMENTS_MISSING       = 0x02c;
240         const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED  = 0x02d;
241         const EXCEPTION_UNSPPORTED_OPERATION         = 0x02e;
242         const EXCEPTION_MISSING_ELEMENT              = 0x030;
243         const EXCEPTION_HEADERS_ALREADY_SENT         = 0x031;
244         const EXCEPTION_DEFAULT_CONTROLLER_GONE      = 0x032;
245         const EXCEPTION_CLASS_NOT_FOUND              = 0x033;
246         const EXCEPTION_REQUIRED_INTERFACE_MISSING   = 0x034;
247         const EXCEPTION_FATAL_ERROR                  = 0x035;
248         const EXCEPTION_FILE_NOT_FOUND               = 0x036;
249         const EXCEPTION_ASSERTION_FAILED             = 0x037;
250         const EXCEPTION_FILE_CANNOT_BE_READ          = 0x038;
251         const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
252         const EXCEPTION_FILTER_CHAIN_INTERCEPTED     = 0x040;
253
254         /**
255          * Hexadecimal->Decimal translation array
256          */
257         private static $hexdec = array(
258                 '0' => 0,
259                 '1' => 1,
260                 '2' => 2,
261                 '3' => 3,
262                 '4' => 4,
263                 '5' => 5,
264                 '6' => 6,
265                 '7' => 7,
266                 '8' => 8,
267                 '9' => 9,
268                 'a' => 10,
269                 'b' => 11,
270                 'c' => 12,
271                 'd' => 13,
272                 'e' => 14,
273                 'f' => 15
274         );
275
276         /**
277          * Decimal->hexadecimal translation array
278          */
279         private static $dechex = array(
280                  0 => '0',
281                  1 => '1',
282                  2 => '2',
283                  3 => '3',
284                  4 => '4',
285                  5 => '5',
286                  6 => '6',
287                  7 => '7',
288                  8 => '8',
289                  9 => '9',
290                 10 => 'a',
291                 11 => 'b',
292                 12 => 'c',
293                 13 => 'd',
294                 14 => 'e',
295                 15 => 'f'
296         );
297
298         /**
299          * Startup time in miliseconds
300          */
301         private static $startupTime = 0;
302
303         /**
304          * Protected super constructor
305          *
306          * @param       $className      Name of the class
307          * @return      void
308          */
309         protected function __construct ($className) {
310                 // Set real class
311                 $this->setRealClass($className);
312
313                 // Set configuration instance if no registry ...
314                 if (!$this instanceof Register) {
315                         // ... because registries doesn't need to be configured
316                         $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
317                 } // END - if
318
319                 // Is the startup time set? (0 cannot be true anymore)
320                 if (self::$startupTime == 0) {
321                         // Then set it
322                         self::$startupTime = microtime(true);
323                 } // END - if
324         }
325
326         /**
327          * Destructor for all classes
328          *
329          * @return      void
330          */
331         public function __destruct () {
332                 // Flush any updated entries to the database
333                 $this->flushPendingUpdates();
334
335                 // Is this object already destroyed?
336                 if ($this->__toString() != 'DestructedObject') {
337                         // Destroy all informations about this class but keep some text about it alive
338                         $this->setRealClass('DestructedObject');
339                 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
340                         // Already destructed object
341                         self::createDebugInstance(__CLASS__)->debugOutput(sprintf("[%s:] The object <span class=\"object_name\">%s</span> is already destroyed.",
342                                 __CLASS__,
343                                 $this->__toString()
344                         ));
345                 }
346         }
347
348         /**
349          * The __call() method where all non-implemented methods end up
350          *
351          * @param       $methodName             Name of the missing method
352          * @args        $args                   Arguments passed to the method
353          * @return      void
354          */
355         public final function __call ($methodName, $args) {
356                 return self::__callStatic($methodName, $args);
357         }
358
359         /**
360          * The __callStatic() method where all non-implemented static methods end up
361          *
362          * @param       $methodName             Name of the missing method
363          * @args        $args                   Arguments passed to the method
364          * @return      void
365          */
366         public static final function __callStatic ($methodName, $args) {
367                 // Implode all given arguments
368                 $argsString = '';
369                 if (empty($args)) {
370                         // No arguments
371                         $argsString = 'NULL';
372                 } elseif (is_array($args)) {
373                         // Some arguments are there
374                         foreach ($args as $arg) {
375                                 // Add the value itself if not array. This prevents 'array to string conversion' message
376                                 if (is_array($arg)) {
377                                         $argsString .= 'Array';
378                                 } else {
379                                         $argsString .= $arg;
380                                 }
381
382                                 // Add data about the argument
383                                 $argsString .= ' (' . gettype($arg);
384
385                                 if (is_string($arg)) {
386                                         // Add length for strings
387                                         $argsString .= ', ' . strlen($arg);
388                                 } elseif (is_array($arg)) {
389                                         // .. or size if array
390                                         $argsString .= ', ' . count($arg);
391                                 } elseif ($arg === true) {
392                                         // ... is boolean 'true'
393                                         $argsString .= ', true';
394                                 } elseif ($arg === false) {
395                                         // ... is boolean 'true'
396                                         $argsString .= ', false';
397                                 }
398
399                                 // Closing bracket
400                                 $argsString .= '), ';
401                         } // END - foreach
402
403                         // Remove last comma
404                         if (substr($argsString, -2, 1) == ',') {
405                                 $argsString = substr($argsString, 0, -2);
406                         } // END - if
407                 } else {
408                         // Invalid arguments!
409                         $argsString = '!INVALID:' . gettype($args) . '!';
410                 }
411
412                 // Output stub message
413                 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
414                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf("[unknown::%s:] Stub! Args: %s",
415                         $methodName,
416                         $argsString
417                 ));
418
419                 // Return nothing
420                 return NULL;
421         }
422
423         /**
424          * Getter for $realClass
425          *
426          * @return      $realClass The name of the real class (not BaseFrameworkSystem)
427          */
428         public function __toString () {
429                 return $this->realClass;
430         }
431
432         /**
433          * Magic function to catch setting of missing but set class fields/attributes
434          *
435          * @param       $name   Name of the field/attribute
436          * @param       $value  Value to store
437          * @return      void
438          */
439         public final function __set ($name, $value) {
440                 $this->debugBackTrace(sprintf("Tried to set a missing field. name=%s, value[%s]=%s",
441                         $name,
442                         gettype($value),
443                         $value
444                 ));
445         }
446
447         /**
448          * Magic function to catch getting of missing fields/attributes
449          *
450          * @param       $name   Name of the field/attribute
451          * @return      void
452          */
453         public final function __get ($name) {
454                 $this->debugBackTrace(sprintf("Tried to get a missing field. name=%s",
455                         $name
456                 ));
457         }
458
459         /**
460          * Magic function to catch unsetting of missing fields/attributes
461          *
462          * @param       $name   Name of the field/attribute
463          * @return      void
464          */
465         public final function __unset ($name) {
466                 $this->debugBackTrace(sprintf("Tried to unset a missing field. name=%s",
467                         $name
468                 ));
469         }
470
471         /**
472          * Setter for the real class name
473          *
474          * @param       $realClass      Class name (string)
475          * @return      void
476          */
477         public final function setRealClass ($realClass) {
478                 // Set real class
479                 $this->realClass = (string) $realClass;
480         }
481
482         /**
483          * Setter for database result instance
484          *
485          * @param       $resultInstance         An instance of a database result class
486          * @return      void
487          * @todo        SearchableResult and UpdateableResult shall have a super interface to use here
488          */
489         protected final function setResultInstance (SearchableResult $resultInstance) {
490                 $this->resultInstance =  $resultInstance;
491         }
492
493         /**
494          * Getter for database result instance
495          *
496          * @return      $resultInstance         An instance of a database result class
497          */
498         public final function getResultInstance () {
499                 return $this->resultInstance;
500         }
501
502         /**
503          * Setter for template engine instances
504          *
505          * @param       $templateInstance       An instance of a template engine class
506          * @return      void
507          */
508         protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
509                 $this->templateInstance = $templateInstance;
510         }
511
512         /**
513          * Getter for template engine instances
514          *
515          * @return      $templateInstance       An instance of a template engine class
516          */
517         protected final function getTemplateInstance () {
518                 return $this->templateInstance;
519         }
520
521         /**
522          * Setter for search instance
523          *
524          * @param       $searchInstance         Searchable criteria instance
525          * @return      void
526          */
527         public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
528                 $this->searchInstance = $searchInstance;
529         }
530
531         /**
532          * Getter for search instance
533          *
534          * @return      $searchInstance         Searchable criteria instance
535          */
536         public final function getSearchInstance () {
537                 return $this->searchInstance;
538         }
539
540         /**
541          * Setter for update instance
542          *
543          * @param       $updateInstance         Searchable criteria instance
544          * @return      void
545          */
546         public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
547                 $this->updateInstance = $updateInstance;
548         }
549
550         /**
551          * Getter for update instance
552          *
553          * @return      $updateInstance         Updateable criteria instance
554          */
555         public final function getUpdateInstance () {
556                 return $this->updateInstance;
557         }
558
559         /**
560          * Setter for resolver instance
561          *
562          * @param       $resolverInstance       Instance of a command resolver class
563          * @return      void
564          */
565         public final function setResolverInstance (Resolver $resolverInstance) {
566                 $this->resolverInstance = $resolverInstance;
567         }
568
569         /**
570          * Getter for resolver instance
571          *
572          * @return      $resolverInstance       Instance of a command resolver class
573          */
574         public final function getResolverInstance () {
575                 return $this->resolverInstance;
576         }
577
578         /**
579          * Setter for language instance
580          *
581          * @param       $configInstance         The configuration instance which shall
582          *                                                              be FrameworkConfiguration
583          * @return      void
584          */
585         public final function setConfigInstance (FrameworkConfiguration $configInstance) {
586                 Registry::getRegistry()->addInstance('config', $configInstance);
587         }
588
589         /**
590          * Getter for configuration instance
591          *
592          * @return      $configInstance         Configuration instance
593          */
594         public final function getConfigInstance () {
595                 $configInstance = Registry::getRegistry()->getInstance('config');
596                 return $configInstance;
597         }
598
599         /**
600          * Setter for debug instance
601          *
602          * @param       $debugInstance  The instance for debug output class
603          * @return      void
604          */
605         public final function setDebugInstance (DebugMiddleware $debugInstance) {
606                 Registry::getRegistry()->addInstance('debug', $debugInstance);
607         }
608
609         /**
610          * Getter for debug instance
611          *
612          * @return      $debugInstance  Instance to class DebugConsoleOutput or DebugWebOutput
613          */
614         public final function getDebugInstance () {
615                 // Get debug instance
616                 $debugInstance = Registry::getRegistry()->getInstance('debug');
617
618                 // Return it
619                 return $debugInstance;
620         }
621
622         /**
623          * Setter for web output instance
624          *
625          * @param       $webInstance    The instance for web output class
626          * @return      void
627          */
628         public final function setWebOutputInstance (OutputStreamer $webInstance) {
629                 Registry::getRegistry()->addInstance('web_output', $webInstance);
630         }
631
632         /**
633          * Getter for web output instance
634          *
635          * @return      $webOutputInstance - Instance to class WebOutput
636          */
637         public final function getWebOutputInstance () {
638                 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
639                 return $webOutputInstance;
640         }
641
642         /**
643          * Setter for database instance
644          *
645          * @param       $databaseInstance       The instance for the database connection (forced DatabaseConnection)
646          * @return      void
647          */
648         public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
649                 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
650         }
651
652         /**
653          * Getter for database layer
654          *
655          * @return      $databaseInstance       The database layer instance
656          */
657         public final function getDatabaseInstance () {
658                 // Get instance
659                 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
660
661                 // Return instance
662                 return $databaseInstance;
663         }
664
665         /**
666          * Setter for compressor channel
667          *
668          * @param       $compressorInstance             An instance of CompressorChannel
669          * @return      void
670          */
671         public final function setCompressorChannel (CompressorChannel $compressorInstance) {
672                 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
673         }
674
675         /**
676          * Getter for compressor channel
677          *
678          * @return      $compressorInstance             The compressor channel
679          */
680         public final function getCompressorChannel () {
681                 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
682                 return $compressorInstance;
683         }
684
685         /**
686          * Protected getter for a manageable application helper class
687          *
688          * @return      $applicationInstance    An instance of a manageable application helper class
689          */
690         protected final function getApplicationInstance () {
691                 $applicationInstance = Registry::getRegistry()->getInstance('application');
692                 return $applicationInstance;
693         }
694
695         /**
696          * Setter for a manageable application helper class
697          *
698          * @param       $applicationInstance    An instance of a manageable application helper class
699          * @return      void
700          */
701         public final function setApplicationInstance (ManageableApplication $applicationInstance) {
702                 Registry::getRegistry()->addInstance('application', $applicationInstance);
703         }
704
705         /**
706          * Setter for request instance
707          *
708          * @param       $requestInstance        An instance of a Requestable class
709          * @return      void
710          */
711         public final function setRequestInstance (Requestable $requestInstance) {
712                 $this->requestInstance = $requestInstance;
713         }
714
715         /**
716          * Getter for request instance
717          *
718          * @return      $requestInstance        An instance of a Requestable class
719          */
720         public final function getRequestInstance () {
721                 return $this->requestInstance;
722         }
723
724         /**
725          * Setter for response instance
726          *
727          * @param       $responseInstance       An instance of a Responseable class
728          * @return      void
729          */
730         public final function setResponseInstance (Responseable $responseInstance) {
731                 $this->responseInstance = $responseInstance;
732         }
733
734         /**
735          * Getter for response instance
736          *
737          * @return      $responseInstance       An instance of a Responseable class
738          */
739         public final function getResponseInstance () {
740                 return $this->responseInstance;
741         }
742
743         /**
744          * Private getter for language instance
745          *
746          * @return      $langInstance   An instance to the language sub-system
747          */
748         protected final function getLanguageInstance () {
749                 $langInstance = Registry::getRegistry()->getInstance('language');
750                 return $langInstance;
751         }
752
753         /**
754          * Setter for language instance
755          *
756          * @param       $langInstance   An instance to the language sub-system
757          * @return      void
758          * @see         LanguageSystem
759          */
760         public final function setLanguageInstance (ManageableLanguage $langInstance) {
761                 Registry::getRegistry()->addInstance('language', $langInstance);
762         }
763
764         /**
765          * Private getter for file IO instance
766          *
767          * @return      $fileIoInstance         An instance to the file I/O sub-system
768          */
769         protected final function getFileIoInstance () {
770                 return $this->fileIoInstance;
771         }
772
773         /**
774          * Setter for file I/O instance
775          *
776          * @param       $fileIoInstance         An instance to the file I/O sub-system
777          * @return      void
778          */
779         public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
780                 $this->fileIoInstance = $fileIoInstance;
781         }
782
783         /**
784          * Protected setter for user instance
785          *
786          * @param       $userInstance   An instance of a user class
787          * @return      void
788          */
789         protected final function setUserInstance (ManageableAccount $userInstance) {
790                 $this->userInstance = $userInstance;
791         }
792
793         /**
794          * Getter for user instance
795          *
796          * @return      $userInstance   An instance of a user class
797          */
798         public final function getUserInstance () {
799                 return $this->userInstance;
800         }
801
802         /**
803          * Setter for controller instance (this surely breaks a bit the MVC patterm)
804          *
805          * @param       $controllerInstance             An instance of the controller
806          * @return      void
807          */
808         public final function setControllerInstance (Controller $controllerInstance) {
809                 $this->controllerInstance = $controllerInstance;
810         }
811
812         /**
813          * Getter for controller instance (this surely breaks a bit the MVC patterm)
814          *
815          * @return      $controllerInstance             An instance of the controller
816          */
817         public final function getControllerInstance () {
818                 return $this->controllerInstance;
819         }
820
821         /**
822          * Setter for RNG instance
823          *
824          * @param       $rngInstance    An instance of a random number generator (RNG)
825          * @return      void
826          */
827         protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
828                 $this->rngInstance = $rngInstance;
829         }
830
831         /**
832          * Getter for RNG instance
833          *
834          * @return      $rngInstance    An instance of a random number generator (RNG)
835          */
836         public final function getRngInstance () {
837                 return $this->rngInstance;
838         }
839
840         /**
841          * Setter for Cryptable instance
842          *
843          * @param       $cryptoInstance An instance of a Cryptable class
844          * @return      void
845          */
846         protected final function setCryptoInstance (Cryptable $cryptoInstance) {
847                 $this->cryptoInstance = $cryptoInstance;
848         }
849
850         /**
851          * Getter for Cryptable instance
852          *
853          * @return      $cryptoInstance An instance of a Cryptable class
854          */
855         public final function getCryptoInstance () {
856                 return $this->cryptoInstance;
857         }
858
859         /**
860          * Setter for the list instance
861          *
862          * @param       $listInstance   A list of Listable
863          * @return      void
864          */
865         protected final function setListInstance (Listable $listInstance) {
866                 $this->listInstance = $listInstance;
867         }
868
869         /**
870          * Getter for the list instance
871          *
872          * @return      $listInstance   A list of Listable
873          */
874         protected final function getListInstance () {
875                 return $this->listInstance;
876         }
877
878         /**
879          * Setter for the menu instance
880          *
881          * @param       $menuInstance   A RenderableMenu instance
882          * @return      void
883          */
884         protected final function setMenuInstance (RenderableMenu $menuInstance) {
885                 $this->menuInstance = $menuInstance;
886         }
887
888         /**
889          * Getter for the menu instance
890          *
891          * @return      $menuInstance   A RenderableMenu instance
892          */
893         protected final function getMenuInstance () {
894                 return $this->menuInstance;
895         }
896
897         /**
898          * Setter for image instance
899          *
900          * @param       $imageInstance  An instance of an image
901          * @return      void
902          */
903         public final function setImageInstance (BaseImage $imageInstance) {
904                 $this->imageInstance = $imageInstance;
905         }
906
907         /**
908          * Getter for image instance
909          *
910          * @return      $imageInstance  An instance of an image
911          */
912         public final function getImageInstance () {
913                 return $this->imageInstance;
914         }
915
916         /**
917          * Setter for stacker instance
918          *
919          * @param       $stackerInstance        An instance of an stacker
920          * @return      void
921          */
922         public final function setStackerInstance (Stackable $stackerInstance) {
923                 $this->stackerInstance = $stackerInstance;
924         }
925
926         /**
927          * Getter for stacker instance
928          *
929          * @return      $stackerInstance        An instance of an stacker
930          */
931         public final function getStackerInstance () {
932                 return $this->stackerInstance;
933         }
934
935         /**
936          * Setter for compressor instance
937          *
938          * @param       $compressorInstance     An instance of an compressor
939          * @return      void
940          */
941         public final function setCompressorInstance (Compressor $compressorInstance) {
942                 $this->compressorInstance = $compressorInstance;
943         }
944
945         /**
946          * Getter for compressor instance
947          *
948          * @return      $compressorInstance     An instance of an compressor
949          */
950         public final function getCompressorInstance () {
951                 return $this->compressorInstance;
952         }
953
954         /**
955          * Setter for Parseable instance
956          *
957          * @param       $parserInstance An instance of an Parseable
958          * @return      void
959          */
960         public final function setParserInstance (Parseable $parserInstance) {
961                 $this->parserInstance = $parserInstance;
962         }
963
964         /**
965          * Getter for Parseable instance
966          *
967          * @return      $parserInstance An instance of an Parseable
968          */
969         public final function getParserInstance () {
970                 return $this->parserInstance;
971         }
972
973         /**
974          * Setter for ProtocolHandler instance
975          *
976          * @param       $protocolInstance       An instance of an ProtocolHandler
977          * @return      void
978          */
979         public final function setProtocolInstance (ProtocolHandler $protocolInstance = NULL) {
980                 $this->protocolInstance = $protocolInstance;
981         }
982
983         /**
984          * Getter for ProtocolHandler instance
985          *
986          * @return      $protocolInstance       An instance of an ProtocolHandler
987          */
988         public final function getProtocolInstance () {
989                 return $this->protocolInstance;
990         }
991
992         /**
993          * Setter for BaseDatabaseWrapper instance
994          *
995          * @param       $wrapperInstance        An instance of an BaseDatabaseWrapper
996          * @return      void
997          */
998         public final function setWrapperInstance (BaseDatabaseWrapper $wrapperInstance) {
999                 $this->wrapperInstance = $wrapperInstance;
1000         }
1001
1002         /**
1003          * Getter for BaseDatabaseWrapper instance
1004          *
1005          * @return      $wrapperInstance        An instance of an BaseDatabaseWrapper
1006          */
1007         public final function getWrapperInstance () {
1008                 return $this->wrapperInstance;
1009         }
1010
1011         /**
1012          * Setter for socket resource
1013          *
1014          * @param       $socketResource         A valid socket resource
1015          * @return      void
1016          */
1017         public final function setSocketResource ($socketResource) {
1018                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1019                 $this->socketResource = $socketResource;
1020         }
1021
1022         /**
1023          * Getter for socket resource
1024          *
1025          * @return      $socketResource         A valid socket resource
1026          */
1027         public final function getSocketResource () {
1028                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1029                 return $this->socketResource;
1030         }
1031
1032         /**
1033          * Setter for helper instance
1034          *
1035          * @param       $helperInstance         An instance of a helper class
1036          * @return      void
1037          */
1038         protected final function setHelperInstance (Helper $helperInstance) {
1039                 $this->helperInstance = $helperInstance;
1040         }
1041
1042         /**
1043          * Getter for helper instance
1044          *
1045          * @return      $helperInstance         An instance of a helper class
1046          */
1047         public final function getHelperInstance () {
1048                 return $this->helperInstance;
1049         }
1050
1051         /**
1052          * Setter for a Sourceable instance
1053          *
1054          * @param       $sourceInstance The Sourceable instance
1055          * @return      void
1056          */
1057         protected final function setSourceInstance (Sourceable $sourceInstance) {
1058                 $this->sourceInstance = $sourceInstance;
1059         }
1060
1061         /**
1062          * Getter for a Sourceable instance
1063          *
1064          * @return      $sourceInstance The Sourceable instance
1065          */
1066         protected final function getSourceInstance () {
1067                 return $this->sourceInstance;
1068         }
1069
1070         /**
1071          * Getter for a InputStreamable instance
1072          *
1073          * @param       $inputStreamInstance    The InputStreamable instance
1074          */
1075         protected final function getInputStreamInstance () {
1076                 return $this->inputStreamInstance;
1077         }
1078
1079         /**
1080          * Setter for a InputStreamable instance
1081          *
1082          * @param       $inputStreamInstance    The InputStreamable instance
1083          * @return      void
1084          */
1085         protected final function setInputStreamInstance (InputStreamable $inputStreamInstance) {
1086                 $this->inputStreamInstance = $inputStreamInstance;
1087         }
1088
1089         /**
1090          * Getter for a OutputStreamable instance
1091          *
1092          * @param       $outputStreamInstance   The OutputStreamable instance
1093          */
1094         protected final function getOutputStreamInstance () {
1095                 return $this->outputStreamInstance;
1096         }
1097
1098         /**
1099          * Setter for a OutputStreamable instance
1100          *
1101          * @param       $outputStreamInstance   The OutputStreamable instance
1102          * @return      void
1103          */
1104         protected final function setOutputStreamInstance (OutputStreamable $outputStreamInstance) {
1105                 $this->outputStreamInstance = $outputStreamInstance;
1106         }
1107
1108         /**
1109          * Setter for handler instance
1110          *
1111          * @param       $handlerInstance        An instance of a Handleable class
1112          * @return      void
1113          */
1114         protected final function setHandlerInstance (Handleable $handlerInstance) {
1115                 $this->handlerInstance = $handlerInstance;
1116         }
1117
1118         /**
1119          * Getter for handler instance
1120          *
1121          * @return      $handlerInstance        A Networkable instance
1122          */
1123         protected final function getHandlerInstance () {
1124                 return $this->handlerInstance;
1125         }
1126
1127         /**
1128          * Setter for visitor instance
1129          *
1130          * @param       $visitorInstance        A Visitor instance
1131          * @return      void
1132          */
1133         protected final function setVisitorInstance (Visitor $visitorInstance) {
1134                 $this->visitorInstance = $visitorInstance;
1135         }
1136
1137         /**
1138          * Getter for visitor instance
1139          *
1140          * @return      $visitorInstance        A Visitor instance
1141          */
1142         protected final function getVisitorInstance () {
1143                 return $this->visitorInstance;
1144         }
1145
1146         /**
1147          * Setter for raw package Data
1148          *
1149          * @param       $packageData    Raw package Data
1150          * @return      void
1151          */
1152         public final function setPackageData (array $packageData) {
1153                 $this->packageData = $packageData;
1154         }
1155
1156         /**
1157          * Getter for raw package Data
1158          *
1159          * @return      $packageData    Raw package Data
1160          */
1161         public function getPackageData () {
1162                 return $this->packageData;
1163         }
1164
1165
1166         /**
1167          * Setter for Iterator instance
1168          *
1169          * @param       $iteratorInstance       An instance of an Iterator
1170          * @return      void
1171          */
1172         protected final function setIteratorInstance (Iterator $iteratorInstance) {
1173                 $this->iteratorInstance = $iteratorInstance;
1174         }
1175
1176         /**
1177          * Getter for Iterator instance
1178          *
1179          * @return      $iteratorInstance       An instance of an Iterator
1180          */
1181         public final function getIteratorInstance () {
1182                 return $this->iteratorInstance;
1183         }
1184
1185         /**
1186          * Checks whether an object equals this object. You should overwrite this
1187          * method to implement own equality checks
1188          *
1189          * @param       $objectInstance         An instance of a FrameworkInterface object
1190          * @return      $equals                         Whether both objects equals
1191          */
1192         public function equals (FrameworkInterface $objectInstance) {
1193                 // Now test it
1194                 $equals = ((
1195                         $this->__toString() == $objectInstance->__toString()
1196                 ) && (
1197                         $this->hashCode() == $objectInstance->hashCode()
1198                 ));
1199
1200                 // Return the result
1201                 return $equals;
1202         }
1203
1204         /**
1205          * Generates a generic hash code of this class. You should really overwrite
1206          * this method with your own hash code generator code. But keep KISS in mind.
1207          *
1208          * @return      $hashCode       A generic hash code respresenting this whole class
1209          */
1210         public function hashCode () {
1211                 // Simple hash code
1212                 return crc32($this->__toString());
1213         }
1214
1215         /**
1216          * Formats computer generated price values into human-understandable formats
1217          * with thousand and decimal separators.
1218          *
1219          * @param       $value          The in computer format value for a price
1220          * @param       $currency       The currency symbol (use HTML-valid characters!)
1221          * @param       $decNum         Number of decimals after commata
1222          * @return      $price          The for the current language formated price string
1223          * @throws      MissingDecimalsThousandsSeparatorException      If decimals or
1224          *                                                                                              thousands separator
1225          *                                                                                              is missing
1226          */
1227         public function formatCurrency ($value, $currency = '&euro;', $decNum = 2) {
1228                 // Are all required attriutes set?
1229                 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1230                         // Throw an exception
1231                         throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1232                 } // END - if
1233
1234                 // Cast the number
1235                 $value = (float) $value;
1236
1237                 // Reformat the US number
1238                 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1239
1240                 // Return as string...
1241                 return $price;
1242         }
1243
1244         /**
1245          * Appends a trailing slash to a string
1246          *
1247          * @param       $str    A string (maybe) without trailing slash
1248          * @return      $str    A string with an auto-appended trailing slash
1249          */
1250         public final function addMissingTrailingSlash ($str) {
1251                 // Is there a trailing slash?
1252                 if (substr($str, -1, 1) != '/') {
1253                         $str .= '/';
1254                 } // END - if
1255
1256                 // Return string with trailing slash
1257                 return $str;
1258         }
1259
1260         /**
1261          * Prepare the template engine (WebTemplateEngine by default) for a given
1262          * application helper instance (ApplicationHelper by default).
1263          *
1264          * @param               $applicationInstance    An application helper instance or
1265          *                                                                              null if we shall use the default
1266          * @return              $templateInstance               The template engine instance
1267          * @throws              NullPointerException    If the discovered application
1268          *                                                                              instance is still null
1269          */
1270         protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1271                 // Is the application instance set?
1272                 if (is_null($applicationInstance)) {
1273                         // Get the current instance
1274                         $applicationInstance = $this->getApplicationInstance();
1275
1276                         // Still null?
1277                         if (is_null($applicationInstance)) {
1278                                 // Thrown an exception
1279                                 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1280                         } // END - if
1281                 } // END - if
1282
1283                 // Initialize the template engine
1284                 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
1285
1286                 // Return the prepared instance
1287                 return $templateInstance;
1288         }
1289
1290         /**
1291          * Debugs this instance by putting out it's full content
1292          *
1293          * @param       $message        Optional message to show in debug output
1294          * @return      void
1295          */
1296         public final function debugInstance ($message = '') {
1297                 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1298                 restore_error_handler();
1299
1300                 // Init content
1301                 $content = '';
1302
1303                 // Is a message set?
1304                 if (!empty($message)) {
1305                         // Construct message
1306                         $content = sprintf("<div class=\"debug_message\">Message: %s</div>\n", $message);
1307                 } // END - if
1308
1309                 // Generate the output
1310                 $content .= sprintf("<pre>%s</pre>",
1311                         trim(
1312                                 htmlentities(
1313                                         print_r($this, true)
1314                                 )
1315                         )
1316                 );
1317
1318                 // Output it
1319                 ApplicationEntryPoint::app_exit(sprintf("<div class=\"debug_header\">%s debug output:</div><div class=\"debug_content\">%s</div>\nLoaded includes: <div class=\"debug_include_list\">%s</div>",
1320                         $this->__toString(),
1321                         $content,
1322                         ClassLoader::getSelfInstance()->getPrintableIncludeList()
1323                 ));
1324         }
1325
1326         /**
1327          * Replaces control characters with printable output
1328          *
1329          * @param       $str    String with control characters
1330          * @return      $str    Replaced string
1331          */
1332         protected function replaceControlCharacters ($str) {
1333                 // Replace them
1334                 $str = str_replace(
1335                         chr(13), '[r]', str_replace(
1336                         chr(10), '[n]', str_replace(
1337                         chr(9) , '[t]',
1338                         $str
1339                 )));
1340
1341                 // Return it
1342                 return $str;
1343         }
1344
1345         /**
1346          * Output a partial stub message for the caller method
1347          *
1348          * @param       $message        An optional message to display
1349          * @return      void
1350          */
1351         protected function partialStub ($message = '') {
1352                 // Get the backtrace
1353                 $backtrace = debug_backtrace();
1354
1355                 // Generate the class::method string
1356                 $methodName = 'UnknownClass-&gt;unknownMethod';
1357                 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1358                         $methodName = $backtrace[1]['class'] . '-&gt;' . $backtrace[1]['function'];
1359                 } // END - if
1360
1361                 // Construct the full message
1362                 $stubMessage = sprintf('[%s:] Partial stub!',
1363                         $methodName
1364                 );
1365
1366                 // Is the extra message given?
1367                 if (!empty($message)) {
1368                         // Then add it as well
1369                         $stubMessage .= ' Message: ' . $message;
1370                 } // END - if
1371
1372                 // Debug instance is there?
1373                 if (!is_null($this->getDebugInstance())) {
1374                         // Output stub message
1375                         self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1376                 } else {
1377                         // Trigger an error
1378                         trigger_error($stubMessage);
1379                 }
1380         }
1381
1382         /**
1383          * Outputs a debug backtrace and stops further script execution
1384          *
1385          * @param       $message        An optional message to output
1386          * @param       $doExit         Whether exit the program (true is default)
1387          * @return      void
1388          */
1389         public function debugBackTrace ($message = '', $doExit = true) {
1390                 // Sorry, there is no other way getting this nice backtrace
1391                 if (!empty($message)) {
1392                         // Output message
1393                         printf('Message: %s<br />' . chr(10), $message);
1394                 } // END - if
1395
1396                 print('<pre>');
1397                 debug_print_backtrace();
1398                 print('</pre>');
1399
1400                 // Exit program?
1401                 if ($doExit === true) {
1402                         exit();
1403                 } // END - if
1404         }
1405
1406         /**
1407          * Creates an instance of a debugger instance
1408          *
1409          * @param       $className              Name of the class (currently unsupported)
1410          * @return      $debugInstance  An instance of a debugger class
1411          */
1412         public final static function createDebugInstance ($className) {
1413                 // Init debug instance
1414                 $debugInstance = NULL;
1415
1416                 // Try it
1417                 try {
1418                         // Get a debugger instance
1419                         $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_class'));
1420                 } catch (NullPointerException $e) {
1421                         // Didn't work, no instance there
1422                         exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1423                 }
1424
1425                 // Empty string should be ignored and used for testing the middleware
1426                 DebugMiddleware::getSelfInstance()->output('');
1427
1428                 // Return it
1429                 return $debugInstance;
1430         }
1431
1432         /**
1433          * Outputs a debug message whether to debug instance (should be set!) or
1434          * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1435          * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1436          *
1437          * @param       $message        Message we shall send out...
1438          * @param       $doPrint        Whether print or die here (default: print)
1439          * @paran       $stripTags      Whether to strip tags (default: false)
1440          * @return      void
1441          */
1442         public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1443                 // Set debug instance to NULL
1444                 $debugInstance = NULL;
1445
1446                 // Try it:
1447                 try {
1448                         // Get debug instance
1449                         $debugInstance = $this->getDebugInstance();
1450                 } catch (NullPointerException $e) {
1451                         // The debug instance is not set (yet)
1452                 }
1453
1454                 // Is the debug instance there?
1455                 if (is_object($debugInstance)) {
1456                         // Use debug output handler
1457                         $debugInstance->output($message, $stripTags);
1458
1459                         if ($doPrint === false) {
1460                                 // Die here if not printed
1461                                 exit();
1462                         } // END - if
1463                 } else {
1464                         // Are debug times enabled?
1465                         if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1466                                 // Prepent it
1467                                 $message = $this->getPrintableExecutionTime() . $message;
1468                         } // END - if
1469
1470                         // Put directly out
1471                         if ($doPrint === true) {
1472                                 // Print message
1473                                 print($message . chr(10));
1474                         } else {
1475                                 // Die here
1476                                 exit($message);
1477                         }
1478                 }
1479         }
1480
1481         /**
1482          * Converts e.g. a command from URL to a valid class by keeping out bad characters
1483          *
1484          * @param       $str            The string, what ever it is needs to be converted
1485          * @return      $className      Generated class name
1486          */
1487         public function convertToClassName ($str) {
1488                 // Init class name
1489                 $className = '';
1490
1491                 // Convert all dashes in underscores
1492                 $str = $this->convertDashesToUnderscores($str);
1493
1494                 // Now use that underscores to get classname parts for hungarian style
1495                 foreach (explode('_', $str) as $strPart) {
1496                         // Make the class name part lower case and first upper case
1497                         $className .= ucfirst(strtolower($strPart));
1498                 } // END - foreach
1499
1500                 // Return class name
1501                 return $className;
1502         }
1503
1504         /**
1505          * Converts dashes to underscores, e.g. useable for configuration entries
1506          *
1507          * @param       $str    The string with maybe dashes inside
1508          * @return      $str    The converted string with no dashed, but underscores
1509          */
1510         public final function convertDashesToUnderscores ($str) {
1511                 // Convert them all
1512                 $str = str_replace('-', '_', $str);
1513
1514                 // Return converted string
1515                 return $str;
1516         }
1517
1518         /**
1519          * Marks up the code by adding e.g. line numbers
1520          *
1521          * @param       $phpCode                Unmarked PHP code
1522          * @return      $markedCode             Marked PHP code
1523          */
1524         public function markupCode ($phpCode) {
1525                 // Init marked code
1526                 $markedCode = '';
1527
1528                 // Get last error
1529                 $errorArray = error_get_last();
1530
1531                 // Init the code with error message
1532                 if (is_array($errorArray)) {
1533                         // Get error infos
1534                         $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>',
1535                                 basename($errorArray['file']),
1536                                 $errorArray['line'],
1537                                 $errorArray['message'],
1538                                 $errorArray['type']
1539                         );
1540                 } // END - if
1541
1542                 // Add line number to the code
1543                 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1544                         // Add line numbers
1545                         $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1546                                 ($lineNo + 1),
1547                                 htmlentities($code, ENT_QUOTES)
1548                         );
1549                 } // END - foreach
1550
1551                 // Return the code
1552                 return $markedCode;
1553         }
1554
1555         /**
1556          * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1557          * beatiful for web-based front-ends. If null is given a message id
1558          * null_timestamp will be resolved and returned.
1559          *
1560          * @param       $timestamp      Timestamp to prepare (filter) for display
1561          * @return      $readable       A readable timestamp
1562          */
1563         public function doFilterFormatTimestamp ($timestamp) {
1564                 // Default value to return
1565                 $readable = '???';
1566
1567                 // Is the timestamp null?
1568                 if (is_null($timestamp)) {
1569                         // Get a message string
1570                         $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1571                 } else {
1572                         switch ($this->getLanguageInstance()->getLanguageCode()) {
1573                                 case 'de': // German format is a bit different to default
1574                                         // Split the GMT stamp up
1575                                         $dateTime  = explode(' ', $timestamp  );
1576                                         $dateArray = explode('-', $dateTime[0]);
1577                                         $timeArray = explode(':', $dateTime[1]);
1578
1579                                         // Construct the timestamp
1580                                         $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1581                                                 $dateArray[0],
1582                                                 $dateArray[1],
1583                                                 $dateArray[2],
1584                                                 $timeArray[0],
1585                                                 $timeArray[1],
1586                                                 $timeArray[2]
1587                                         );
1588                                         break;
1589
1590                                 default: // Default is pass-through
1591                                         $readable = $timestamp;
1592                                         break;
1593                         } // END - switch
1594                 }
1595
1596                 // Return the stamp
1597                 return $readable;
1598         }
1599
1600         /**
1601          * Filter a given number into a localized number
1602          *
1603          * @param       $value          The raw value from e.g. database
1604          * @return      $localized      Localized value
1605          */
1606         public function doFilterFormatNumber ($value) {
1607                 // Generate it from config and localize dependencies
1608                 switch ($this->getLanguageInstance()->getLanguageCode()) {
1609                         case 'de': // German format is a bit different to default
1610                                 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1611                                 break;
1612
1613                         default: // US, etc.
1614                                 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1615                                 break;
1616                 } // END - switch
1617
1618                 // Return it
1619                 return $localized;
1620         }
1621
1622         /**
1623          * "Getter" for databse entry
1624          *
1625          * @return      $entry  An array with database entries
1626          * @throws      NullPointerException    If the database result is not found
1627          * @throws      InvalidDatabaseResultException  If the database result is invalid
1628          */
1629         protected final function getDatabaseEntry () {
1630                 // Is there an instance?
1631                 if (is_null($this->getResultInstance())) {
1632                         // Throw an exception here
1633                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1634                 } // END - if
1635
1636                 // Rewind it
1637                 $this->getResultInstance()->rewind();
1638
1639                 // Do we have an entry?
1640                 if ($this->getResultInstance()->valid() === false) {
1641                         throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1642                 } // END - if
1643
1644                 // Get next entry
1645                 $this->getResultInstance()->next();
1646
1647                 // Fetch it
1648                 $entry = $this->getResultInstance()->current();
1649
1650                 // And return it
1651                 return $entry;
1652         }
1653
1654         /**
1655          * Getter for field name
1656          *
1657          * @param       $fieldName              Field name which we shall get
1658          * @return      $fieldValue             Field value from the user
1659          * @throws      NullPointerException    If the result instance is null
1660          */
1661         public final function getField ($fieldName) {
1662                 // Default field value
1663                 $fieldValue = NULL;
1664
1665                 // Get result instance
1666                 $resultInstance = $this->getResultInstance();
1667
1668                 // Is this instance null?
1669                 if (is_null($resultInstance)) {
1670                         // Then the user instance is no longer valid (expired cookies?)
1671                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1672                 } // END - if
1673
1674                 // Get current array
1675                 $fieldArray = $resultInstance->current();
1676                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1677
1678                 // Convert dashes to underscore
1679                 $fieldName = $this->convertDashesToUnderscores($fieldName);
1680
1681                 // Does the field exist?
1682                 if (isset($fieldArray[$fieldName])) {
1683                         // Get it
1684                         $fieldValue = $fieldArray[$fieldName];
1685                 } else {
1686                         // Missing field entry, may require debugging
1687                         self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ':fieldname=' . $fieldName . ' not found!');
1688                 }
1689
1690                 // Return it
1691                 return $fieldValue;
1692         }
1693
1694         /**
1695          * Flushs all pending updates to the database layer
1696          *
1697          * @return      void
1698          */
1699         public function flushPendingUpdates () {
1700                 // Get result instance
1701                 $resultInstance = $this->getResultInstance();
1702
1703                 // Do we have data to update?
1704                 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1705                         // Get wrapper class name config entry
1706                         $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1707
1708                         // Create object instance
1709                         $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1710
1711                         // Yes, then send the whole result to the database layer
1712                         $wrapperInstance->doUpdateByResult($this->getResultInstance());
1713                 } // END - if
1714         }
1715
1716         /**
1717          * Outputs a deprecation warning to the developer.
1718          *
1719          * @param       $message        The message we shall output to the developer
1720          * @return      void
1721          * @todo        Write a logging mechanism for productive mode
1722          */
1723         public function deprecationWarning ($message) {
1724                 // Is developer mode active?
1725                 if (defined('DEVELOPER')) {
1726                         // Debug instance is there?
1727                         if (!is_null($this->getDebugInstance())) {
1728                                 // Output stub message
1729                                 self::createDebugInstance(__CLASS__)->debugOutput($message);
1730                         } else {
1731                                 // Trigger an error
1732                                 trigger_error($message . "<br />\n");
1733                         }
1734                 } else {
1735                         // @TODO Finish this part!
1736                         $this->partialStub('Developer mode inactive. Message:' . $message);
1737                 }
1738         }
1739
1740         /**
1741          * Checks whether the given PHP extension is loaded
1742          *
1743          * @param       $phpExtension   The PHP extension we shall check
1744          * @return      $isLoaded       Whether the PHP extension is loaded
1745          */
1746         public final function isPhpExtensionLoaded ($phpExtension) {
1747                 // Is it loaded?
1748                 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1749
1750                 // Return result
1751                 return $isLoaded;
1752         }
1753
1754         /**
1755          * "Getter" as a time() replacement but with milliseconds. You should use this
1756          * method instead of the encapsulated getimeofday() function.
1757          *
1758          * @return      $milliTime      Timestamp with milliseconds
1759          */
1760         public function getMilliTime () {
1761                 // Get the time of day as float
1762                 $milliTime = gettimeofday(true);
1763
1764                 // Return it
1765                 return $milliTime;
1766         }
1767
1768         /**
1769          * Idles (sleeps) for given milliseconds
1770          *
1771          * @return      $hasSlept       Whether it goes fine
1772          */
1773         public function idle ($milliSeconds) {
1774                 // Sleep is fine by default
1775                 $hasSlept = true;
1776
1777                 // Idle so long with found function
1778                 if (function_exists('time_sleep_until')) {
1779                         // Get current time and add idle time
1780                         $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1781
1782                         // New PHP 5.1.0 function found, ignore errors
1783                         $hasSlept = @time_sleep_until($sleepUntil);
1784                 } else {
1785                         /*
1786                          * My Sun station doesn't have that function even with latest PHP
1787                          * package. :(
1788                          */
1789                         usleep($milliSeconds * 1000);
1790                 }
1791
1792                 // Return result
1793                 return $hasSlept;
1794         }
1795         /**
1796          * Converts a hexadecimal string, even with negative sign as first string to
1797          * a decimal number using BC functions.
1798          *
1799          * This work is based on comment #86673 on php.net documentation page at:
1800          * <http://de.php.net/manual/en/function.dechex.php#86673>
1801          *
1802          * @param       $hex    Hexadecimal string
1803          * @return      $dec    Decimal number
1804          */
1805         protected function hex2dec ($hex) {
1806                 // Convert to all lower-case
1807                 $hex = strtolower($hex);
1808
1809                 // Detect sign (negative/positive numbers)
1810                 $sign = '';
1811                 if (substr($hex, 0, 1) == '-') {
1812                         $sign = '-';
1813                         $hex = substr($hex, 1);
1814                 } // END - if
1815
1816                 // Decode the hexadecimal string into a decimal number
1817                 $dec = 0;
1818                 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1819                         $factor = self::$hexdec[substr($hex, $i, 1)];
1820                         $dec = bcadd($dec, bcmul($factor, $e));
1821                 } // END - for
1822
1823                 // Return the decimal number
1824                 return $sign . $dec;
1825         }
1826
1827         /**
1828          * Converts even very large decimal numbers, also with negative sign, to a
1829          * hexadecimal string.
1830          *
1831          * This work is based on comment #97756 on php.net documentation page at:
1832          * <http://de.php.net/manual/en/function.hexdec.php#97756>
1833          *
1834          * @param       $dec            Decimal number, even with negative sign
1835          * @param       $maxLength      Optional maximum length of the string
1836          * @return      $hex    Hexadecimal string
1837          */
1838         protected function dec2hex ($dec, $maxLength = 0) {
1839                 // maxLength can be zero or devideable by 2
1840                 assert(($maxLength == 0) || (($maxLength % 2) == 0));
1841
1842                 // Detect sign (negative/positive numbers)
1843                 $sign = '';
1844                 if ($dec < 0) {
1845                         $sign = '-';
1846                         $dec = abs($dec);
1847                 } // END - if
1848
1849                 // Encode the decimal number into a hexadecimal string
1850                 $hex = '';
1851                 do {
1852                         $hex = self::$dechex[($dec % 16)] . $hex;
1853                         $dec /= 16;
1854                 } while ($dec >= 1);
1855
1856                 /*
1857                  * We need hexadecimal strings with leading zeros if the length cannot
1858                  * be divided by 2
1859                  */
1860                 if ($maxLength > 0) {
1861                         // Prepend more zeros
1862                         $hex = $this->prependStringToString($hex, '0', $maxLength);
1863                 } elseif ((strlen($hex) % 2) != 0) {
1864                         $hex = '0' . $hex;
1865                 }
1866
1867                 // Return the hexadecimal string
1868                 return $sign . $hex;
1869         }
1870
1871         /**
1872          * Converts a ASCII string (0 to 255) into a decimal number.
1873          *
1874          * @param       $asc    The ASCII string to be converted
1875          * @return      $dec    Decimal number
1876          */
1877         protected function asc2dec ($asc) {
1878                 // Convert it into a hexadecimal number
1879                 $hex = bin2hex($asc);
1880
1881                 // And back into a decimal number
1882                 $dec = $this->hex2dec($hex);
1883
1884                 // Return it
1885                 return $dec;
1886         }
1887
1888         /**
1889          * Converts a decimal number into an ASCII string.
1890          *
1891          * @param       $dec            Decimal number
1892          * @return      $asc    An ASCII string
1893          */
1894         protected function dec2asc ($dec) {
1895                 // First convert the number into a hexadecimal string
1896                 $hex = $this->dec2hex($dec);
1897
1898                 // Then convert it into the ASCII string
1899                 $asc = $this->hex2asc($hex);
1900
1901                 // Return it
1902                 return $asc;
1903         }
1904
1905         /**
1906          * Converts a hexadecimal number into an ASCII string. Negative numbers
1907          * are not allowed.
1908          *
1909          * @param       $hex    Hexadecimal string
1910          * @return      $asc    An ASCII string
1911          */
1912         protected function hex2asc ($hex) {
1913                 // Check for length, it must be devideable by 2
1914                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
1915                 assert((strlen($hex) % 2) == 0);
1916
1917                 // Walk the string
1918                 $asc = '';
1919                 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
1920                         // Get the decimal number of the chunk
1921                         $part = hexdec(substr($hex, $idx, 2));
1922
1923                         // Add it to the final string
1924                         $asc .= chr($part);
1925                 } // END - for
1926
1927                 // Return the final string
1928                 return $asc;
1929         }
1930
1931         /**
1932          * Prepends a given string $prepend to $str with a given total length
1933          *
1934          * @param       $str            Given original string which should be prepended
1935          * @param       $prepend        The string to prepend
1936          * @param       $length         Total length of the final string
1937          * @return      $strFinal       Final prepended string
1938          */
1939         protected function prependStringToString ($str, $prepend, $length) {
1940                 // Set final string to original string by default
1941                 $strFinal = $str;
1942
1943                 // Can it devided
1944                 if (strlen($str) < $length) {
1945                         // Difference between total length and length of original string
1946                         $diff = $length - strlen($str);
1947
1948                         // Prepend the string
1949                         $prepend = str_repeat($prepend, ($diff / strlen($prepend) + 1));
1950
1951                         // Make sure it will definedly fit
1952                         assert(strlen($prepend) >= $diff);
1953
1954                         // Cut it a little down
1955                         $prepend = substr($prepend, 0, $diff);
1956                         //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('prepend('.strlen($prepend).')='.$prepend.',diff='.$diff.',length='.$length);
1957
1958                         // Construct the final prepended string
1959                         $strFinal = $prepend . $str;
1960                 } // END - if
1961
1962                 // Return it
1963                 return $strFinal;
1964         }
1965
1966         /**
1967          * Checks whether the given encoded data was encoded with Base64
1968          *
1969          * @param       $encodedData    Encoded data we shall check
1970          * @return      $isBase64               Whether the encoded data is Base64
1971          */
1972         protected function isBase64Encoded ($encodedData) {
1973                 // Determine it
1974                 $isBase64 = (@base64_decode($encodedData, true) !== false);
1975
1976                 // Return it
1977                 return $isBase64;
1978         }
1979
1980         /**
1981          * "Getter" to get response/request type from analysis of the system.
1982          *
1983          * @return      $responseType   Analyzed response type
1984          */
1985         protected function getResponseTypeFromSystem () {
1986                 // Default is console
1987                 $responseType = 'console';
1988
1989                 // Is 'HTTP_HOST' set?
1990                 if (isset($_SERVER['HTTP_HOST'])) {
1991                         // Then it is a HTTP response/request
1992                         $responseType = 'http';
1993                 } // END - if
1994
1995                 // Return it
1996                 return $responseType;
1997         }
1998
1999         /**
2000          * Gets a cache key from Criteria instance
2001          *
2002          * @param       $criteriaInstance       An instance of a Criteria class
2003          * @param       $onlyKeys                       Only use these keys for a cache key
2004          * @return      $cacheKey                       A cache key suitable for lookup/storage purposes
2005          */
2006         protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2007                 // Generate it
2008                 $cacheKey = sprintf("%s@%s",
2009                         $this->__toString(),
2010                         $criteriaInstance->getCacheKey($onlyKeys)
2011                 );
2012
2013                 // And return it
2014                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2015                 return $cacheKey;
2016         }
2017
2018         /**
2019          * Getter for startup time in miliseconds
2020          *
2021          * @return      $startupTime    Startup time in miliseconds
2022          */
2023         protected function getStartupTime () {
2024                 return self::$startupTime;
2025         }
2026
2027         /**
2028          * "Getter" for a printable currently execution time in nice braces
2029          *
2030          * @return      $executionTime  Current execution time in nice braces
2031          */
2032         protected function getPrintableExecutionTime () {
2033                 // Caculate the execution time
2034                 $executionTime = microtime(true) - $this->getStartupTime();
2035
2036                 // Pack it in nice braces
2037                 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2038
2039                 // And return it
2040                 return $executionTime;
2041         }
2042
2043         /**
2044          * Hashes a given string with a simple but stronger hash function (no salts)
2045          *
2046          * @param       $str    The string to be hashed
2047          * @return      $hash   The hash from string $str
2048          */
2049         public function hashString ($str) {
2050                 // Hash given string with (better secure) hasher
2051                 $hash = mhash(MHASH_SHA256, $str);
2052
2053                 // Return it
2054                 return $hash;
2055         }
2056
2057         /**
2058          * Checks whether the given number is really a number (only chars 0-9).
2059          *
2060          * @param       $num            A string consisting only chars between 0 and 9
2061          * @param       $castValue      Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2062          * @param       $assertMismatch         Whether to assert mismatches
2063          * @return      $ret            The (hopefully) secured numbered value
2064          */
2065         public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2066                 // Filter all numbers out
2067                 $ret = preg_replace('/[^0123456789]/', '', $num);
2068
2069                 // Shall we cast?
2070                 if ($castValue === true) {
2071                         // Cast to biggest numeric type
2072                         $ret = (double) $ret;
2073                 } // END - if
2074
2075                 // Assert only if requested
2076                 if ($assertMismatch === true) {
2077                         // Has the whole value changed?
2078                         assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2079                 } // END - if
2080
2081                 // Return result
2082                 return $ret;
2083         }
2084
2085         /**
2086          * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2087          *
2088          * @param       $num    A string consisting only chars between 0 and 9
2089          * @param       $assertMismatch         Whether to assert mismatches
2090          * @return      $ret    The (hopefully) secured hext-numbered value
2091          */
2092         public function hexval ($num, $assertMismatch = false) {
2093                 // Filter all numbers out
2094                 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2095
2096                 // Assert only if requested
2097                 if ($assertMismatch === true) {
2098                         // Has the whole value changed?
2099                         assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2100                 } // END - if
2101
2102                 // Return result
2103                 return $ret;
2104         }
2105
2106         /**
2107          * Checks whether start/end marker are set
2108          *
2109          * @param       $data   Data to be checked
2110          * @return      $isset  Whether start/end marker are set
2111          */
2112         public final function ifStartEndMarkersSet ($data) {
2113                 // Determine it
2114                 $isset = ((substr($data, 0, strlen(BaseRawDataHandler::STREAM_START_MARKER)) == BaseRawDataHandler::STREAM_START_MARKER) && (substr($data, -1 * strlen(BaseRawDataHandler::STREAM_END_MARKER), strlen(BaseRawDataHandler::STREAM_END_MARKER)) == BaseRawDataHandler::STREAM_END_MARKER));
2115
2116                 // ... and return it
2117                 return $isset;
2118         }
2119 }
2120
2121 // [EOF]
2122 ?>