Missed this ... :-(
[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@shipsimu.org>
7  * @version             0.0.0
8  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Core Developer Team
9  * @license             GNU GPL 3.0 or any newer version
10  * @link                http://www.shipsimu.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          * Length of output from hash()
28          */
29         private static $hashLength = NULL;
30
31         /**
32          * The real class name
33          */
34         private $realClass = 'BaseFrameworkSystem';
35
36         /**
37          * Instance of a request class
38          */
39         private $requestInstance = NULL;
40
41         /**
42          * Instance of a response class
43          */
44         private $responseInstance = NULL;
45
46         /**
47          * Search criteria instance
48          */
49         private $searchInstance = NULL;
50
51         /**
52          * Update criteria instance
53          */
54         private $updateInstance = NULL;
55
56         /**
57          * The file I/O instance for the template loader
58          */
59         private $fileIoInstance = NULL;
60
61         /**
62          * Resolver instance
63          */
64         private $resolverInstance = NULL;
65
66         /**
67          * Template engine instance
68          */
69         private $templateInstance = NULL;
70
71         /**
72          * Database result instance
73          */
74         private $resultInstance = NULL;
75
76         /**
77          * Instance for user class
78          */
79         private $userInstance = NULL;
80
81         /**
82          * A controller instance
83          */
84         private $controllerInstance = NULL;
85
86         /**
87          * Instance of a RNG
88          */
89         private $rngInstance = NULL;
90
91         /**
92          * Instance of a crypto helper
93          */
94         private $cryptoInstance = NULL;
95
96         /**
97          * Instance of an Iterator class
98          */
99         private $iteratorInstance = NULL;
100
101         /**
102          * Instance of the list
103          */
104         private $listInstance = NULL;
105
106         /**
107          * Instance of a menu
108          */
109         private $menuInstance = NULL;
110
111         /**
112          * Instance of the image
113          */
114         private $imageInstance = NULL;
115
116         /**
117          * Instance of the stacker
118          */
119         private $stackInstance = NULL;
120
121         /**
122          * A Compressor instance
123          */
124         private $compressorInstance = NULL;
125
126         /**
127          * A Parseable instance
128          */
129         private $parserInstance = NULL;
130
131         /**
132          * A HandleableProtocol instance
133          */
134         private $protocolInstance = NULL;
135
136         /**
137          * A database wrapper instance
138          */
139         private $databaseInstance = NULL;
140
141         /**
142          * A helper instance for the form
143          */
144         private $helperInstance = NULL;
145
146         /**
147          * An instance of a Source class
148          */
149         private $sourceInstance = NULL;
150
151         /**
152          * An instance of a UrlSource class
153          */
154         private $urlSourceInstance = NULL;
155
156         /**
157          * An instance of a InputStream class
158          */
159         private $inputStreamInstance = NULL;
160
161         /**
162          * An instance of a OutputStream class
163          */
164         private $outputStreamInstance = NULL;
165
166         /**
167          * Networkable handler instance
168          */
169         private $handlerInstance = NULL;
170
171         /**
172          * Visitor handler instance
173          */
174         private $visitorInstance = NULL;
175
176         /**
177          * DHT instance
178          */
179         private $dhtInstance = NULL;
180
181         /**
182          * An instance of a database wrapper class
183          */
184         private $wrapperInstance = NULL;
185
186         /**
187          * An instance of a file I/O pointer class (not handler)
188          */
189         private $pointerInstance = NULL;
190
191         /**
192          * An instance of an Indexable class
193          */
194         private $indexInstance = NULL;
195
196         /**
197          * An instance of a Block class
198          */
199         private $blockInstance = NULL;
200
201         /**
202          * A Minable instance
203          */
204         private $minableInstance = NULL;
205
206         /**
207          * A FrameworkDirectory instance
208          */
209         private $directoryInstance = NULL;
210
211         /**
212          * Listener instance
213          */
214         private $listenerInstance = NULL;
215
216         /**
217          * An instance of a communicator
218          */
219         private $communicatorInstance = NULL;
220
221         /**
222          * State instance
223          */
224         private $stateInstance = NULL;
225
226         /**
227          * Thousands separator
228          */
229         private $thousands = '.'; // German
230
231         /**
232          * Decimal separator
233          */
234         private $decimals  = ','; // German
235
236         /**
237          * Socket resource
238          */
239         private $socketResource = FALSE;
240
241         /**
242          * Regular expression to use for validation
243          */
244         private $regularExpression = '';
245
246         /**
247          * Package data
248          */
249         private $packageData = array();
250
251         /**
252          * Generic array
253          */
254         private $genericArray = array();
255
256         /**
257          * Command name
258          */
259         private $commandName = '';
260
261         /**
262          * Controller name
263          */
264         private $controllerName = '';
265
266         /**
267          * Name of used protocol
268          */
269         private $protocolName = 'invalid';
270
271         /**
272          * Array with bitmasks and such for pack/unpack methods to support both
273          * 32-bit and 64-bit systems
274          */
275         private $packingData = array(
276                 32 => array(
277                         'step'   => 3,
278                         'left'   => 0xffff0000,
279                         'right'  => 0x0000ffff,
280                         'factor' => 16,
281                         'format' => 'II',
282                 ),
283                 64 => array(
284                         'step'   => 7,
285                         'left'   => 0xffffffff00000000,
286                         'right'  => 0x00000000ffffffff,
287                         'factor' => 32,
288                         'format' => 'NN'
289                 )
290         );
291
292         /**
293          * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
294          *
295          * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
296          */
297         private $archArrayElement = FALSE;
298
299         /***********************
300          * Exception codes.... *
301          ***********************/
302
303         // @todo Try to clean these constants up
304         const EXCEPTION_IS_NULL_POINTER              = 0x001;
305         const EXCEPTION_IS_NO_OBJECT                 = 0x002;
306         const EXCEPTION_IS_NO_ARRAY                  = 0x003;
307         const EXCEPTION_MISSING_METHOD               = 0x004;
308         const EXCEPTION_CLASSES_NOT_MATCHING         = 0x005;
309         const EXCEPTION_INDEX_OUT_OF_BOUNDS          = 0x006;
310         const EXCEPTION_DIMENSION_ARRAY_INVALID      = 0x007;
311         const EXCEPTION_ITEM_NOT_TRADEABLE           = 0x008;
312         const EXCEPTION_ITEM_NOT_IN_PRICE_LIST       = 0x009;
313         const EXCEPTION_GENDER_IS_WRONG              = 0x00a;
314         const EXCEPTION_BIRTH_DATE_IS_INVALID        = 0x00b;
315         const EXCEPTION_EMPTY_STRUCTURES_ARRAY       = 0x00c;
316         const EXCEPTION_HAS_ALREADY_PERSONELL_LIST   = 0x00d;
317         const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES      = 0x00e;
318         const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED   = 0x00f;
319         const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS      = 0x010;
320         const EXCEPTION_CONTRACT_PARTNER_INVALID     = 0x011;
321         const EXCEPTION_CONTRACT_PARTNER_MISMATCH    = 0x012;
322         const EXCEPTION_CONTRACT_ALREADY_SIGNED      = 0x013;
323         const EXCEPTION_UNEXPECTED_EMPTY_STRING      = 0x014;
324         const EXCEPTION_PATH_NOT_FOUND               = 0x015;
325         const EXCEPTION_INVALID_PATH_NAME            = 0x016;
326         const EXCEPTION_READ_PROTECED_PATH           = 0x017;
327         const EXCEPTION_WRITE_PROTECED_PATH          = 0x018;
328         const EXCEPTION_DIR_POINTER_INVALID          = 0x019;
329         const EXCEPTION_FILE_POINTER_INVALID         = 0x01a;
330         const EXCEPTION_INVALID_RESOURCE             = 0x01b;
331         const EXCEPTION_UNEXPECTED_OBJECT            = 0x01c;
332         const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
333         const EXCEPTION_GETTER_IS_MISSING            = 0x01e;
334         const EXCEPTION_ARRAY_EXPECTED               = 0x01f;
335         const EXCEPTION_ARRAY_HAS_INVALID_COUNT      = 0x020;
336         const EXCEPTION_ID_IS_INVALID_FORMAT         = 0x021;
337         const EXCEPTION_MD5_CHECKSUMS_MISMATCH       = 0x022;
338         const EXCEPTION_UNEXPECTED_STRING_SIZE       = 0x023;
339         const EXCEPTION_SIMULATOR_ID_INVALID         = 0x024;
340         const EXCEPTION_MISMATCHING_COMPRESSORS      = 0x025;
341         const EXCEPTION_CONTAINER_ITEM_IS_NULL       = 0x026;
342         const EXCEPTION_ITEM_IS_NO_ARRAY             = 0x027;
343         const EXCEPTION_CONTAINER_MAYBE_DAMAGED      = 0x028;
344         const EXCEPTION_INVALID_STRING               = 0x029;
345         const EXCEPTION_VARIABLE_NOT_SET             = 0x02a;
346         const EXCEPTION_ATTRIBUTES_ARE_MISSING       = 0x02b;
347         const EXCEPTION_ARRAY_ELEMENTS_MISSING       = 0x02c;
348         const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED  = 0x02d;
349         const EXCEPTION_UNSPPORTED_OPERATION         = 0x02e;
350         const EXCEPTION_FACTORY_REQUIRE_PARAMETER    = 0x02f;
351         const EXCEPTION_MISSING_ELEMENT              = 0x030;
352         const EXCEPTION_HEADERS_ALREADY_SENT         = 0x031;
353         const EXCEPTION_DEFAULT_CONTROLLER_GONE      = 0x032;
354         const EXCEPTION_CLASS_NOT_FOUND              = 0x033;
355         const EXCEPTION_REQUIRED_INTERFACE_MISSING   = 0x034;
356         const EXCEPTION_FATAL_ERROR                  = 0x035;
357         const EXCEPTION_FILE_NOT_FOUND               = 0x036;
358         const EXCEPTION_ASSERTION_FAILED             = 0x037;
359         const EXCEPTION_FILE_NOT_REACHABLE           = 0x038;
360         const EXCEPTION_FILE_CANNOT_BE_READ          = 0x039;
361         const EXCEPTION_FILE_CANNOT_BE_WRITTEN       = 0x03a;
362         const EXCEPTION_PATH_CANNOT_BE_WRITTEN       = 0x03b;
363         const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
364         const EXCEPTION_FILTER_CHAIN_INTERCEPTED     = 0x03d;
365
366         /**
367          * Hexadecimal->Decimal translation array
368          */
369         private static $hexdec = array(
370                 '0' => 0,
371                 '1' => 1,
372                 '2' => 2,
373                 '3' => 3,
374                 '4' => 4,
375                 '5' => 5,
376                 '6' => 6,
377                 '7' => 7,
378                 '8' => 8,
379                 '9' => 9,
380                 'a' => 10,
381                 'b' => 11,
382                 'c' => 12,
383                 'd' => 13,
384                 'e' => 14,
385                 'f' => 15
386         );
387
388         /**
389          * Decimal->hexadecimal translation array
390          */
391         private static $dechex = array(
392                  0 => '0',
393                  1 => '1',
394                  2 => '2',
395                  3 => '3',
396                  4 => '4',
397                  5 => '5',
398                  6 => '6',
399                  7 => '7',
400                  8 => '8',
401                  9 => '9',
402                 10 => 'a',
403                 11 => 'b',
404                 12 => 'c',
405                 13 => 'd',
406                 14 => 'e',
407                 15 => 'f'
408         );
409
410         /**
411          * Startup time in miliseconds
412          */
413         private static $startupTime = 0;
414
415         /**
416          * Protected super constructor
417          *
418          * @param       $className      Name of the class
419          * @return      void
420          */
421         protected function __construct ($className) {
422                 // Set real class
423                 $this->setRealClass($className);
424
425                 // Set configuration instance if no registry ...
426                 if (!$this instanceof Register) {
427                         // ... because registries doesn't need to be configured
428                         $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
429                 } // END - if
430
431                 // Is the startup time set? (0 cannot be TRUE anymore)
432                 if (self::$startupTime == 0) {
433                         // Then set it
434                         self::$startupTime = microtime(TRUE);
435                 } // END - if
436
437                 // Set array element
438                 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
439         }
440
441         /**
442          * Destructor for all classes
443          *
444          * @return      void
445          */
446         public function __destruct () {
447                 // Flush any updated entries to the database
448                 $this->flushPendingUpdates();
449
450                 // Is this object already destroyed?
451                 if ($this->__toString() != 'DestructedObject') {
452                         // Destroy all informations about this class but keep some text about it alive
453                         $this->setRealClass('DestructedObject');
454                 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
455                         // Already destructed object
456                         self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
457                                 __CLASS__,
458                                 $this->__toString()
459                         ));
460                 } else {
461                         // Do not call this twice
462                         trigger_error(__METHOD__ . ': Called twice.');
463                         exit;
464                 }
465         }
466
467         /**
468          * The __call() method where all non-implemented methods end up
469          *
470          * @param       $methodName             Name of the missing method
471          * @args        $args                   Arguments passed to the method
472          * @return      void
473          */
474         public final function __call ($methodName, $args) {
475                 return self::__callStatic($methodName, $args);
476         }
477
478         /**
479          * The __callStatic() method where all non-implemented static methods end up
480          *
481          * @param       $methodName             Name of the missing method
482          * @args        $args                   Arguments passed to the method
483          * @return      void
484          */
485         public static final function __callStatic ($methodName, $args) {
486                 // Init argument string
487                 $argsString = '';
488
489                 // Is it NULL, empty or an array?
490                 if (is_null($args)) {
491                         // No arguments
492                         $argsString = 'NULL';
493                 } elseif (empty($args)) {
494                         // Empty arguments
495                         $argsString = '(empty)';
496                 } elseif (is_array($args)) {
497                         // Some arguments are there
498                         foreach ($args as $arg) {
499                                 // Add the value itself if not array. This prevents 'array to string conversion' message
500                                 if (is_array($arg)) {
501                                         $argsString .= 'Array';
502                                 } else {
503                                         $argsString .= $arg;
504                                 }
505
506                                 // Add data about the argument
507                                 $argsString .= ' (' . gettype($arg);
508
509                                 if (is_string($arg)) {
510                                         // Add length for strings
511                                         $argsString .= ', ' . strlen($arg);
512                                 } elseif (is_array($arg)) {
513                                         // .. or size if array
514                                         $argsString .= ', ' . count($arg);
515                                 } elseif ($arg === TRUE) {
516                                         // ... is boolean 'TRUE'
517                                         $argsString .= ', TRUE';
518                                 } elseif ($arg === FALSE) {
519                                         // ... is boolean 'FALSE'
520                                         $argsString .= ', FALSE';
521                                 }
522
523                                 // Closing bracket
524                                 $argsString .= '), ';
525                         } // END - foreach
526
527                         // Remove last comma
528                         if (substr($argsString, -2, 1) == ',') {
529                                 $argsString = substr($argsString, 0, -2);
530                         } // END - if
531                 } else {
532                         // Invalid arguments!
533                         $argsString = '!INVALID:' . gettype($args) . '!';
534                 }
535
536                 // Output stub message
537                 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
538                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
539                         $methodName,
540                         $argsString
541                 ));
542
543                 // Return nothing
544                 return NULL;
545         }
546
547         /**
548          * Getter for $realClass
549          *
550          * @return      $realClass The name of the real class (not BaseFrameworkSystem)
551          */
552         public function __toString () {
553                 return $this->realClass;
554         }
555
556         /**
557          * Magic method to catch setting of missing but set class fields/attributes
558          *
559          * @param       $name   Name of the field/attribute
560          * @param       $value  Value to store
561          * @return      void
562          */
563         public final function __set ($name, $value) {
564                 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
565                         $name,
566                         gettype($value),
567                         print_r($value, TRUE)
568                 ));
569         }
570
571         /**
572          * Magic method to catch getting of missing fields/attributes
573          *
574          * @param       $name   Name of the field/attribute
575          * @return      void
576          */
577         public final function __get ($name) {
578                 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
579                         $name
580                 ));
581         }
582
583         /**
584          * Magic method to catch unsetting of missing fields/attributes
585          *
586          * @param       $name   Name of the field/attribute
587          * @return      void
588          */
589         public final function __unset ($name) {
590                 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
591                         $name
592                 ));
593         }
594
595         /**
596          * Magic method to catch object serialization
597          *
598          * @return      $unsupported    Unsupported method
599          * @throws      UnsupportedOperationException   Objects of this framework cannot be serialized
600          */
601         public final function __sleep () {
602                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
603         }
604
605         /**
606          * Magic method to catch object deserialization
607          *
608          * @return      $unsupported    Unsupported method
609          * @throws      UnsupportedOperationException   Objects of this framework cannot be serialized
610          */
611         public final function __wakeup () {
612                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
613         }
614
615         /**
616          * Magic method to catch calls when an object instance is called
617          *
618          * @return      $unsupported    Unsupported method
619          * @throws      UnsupportedOperationException   Objects of this framework cannot be serialized
620          */
621         public final function __invoke () {
622                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
623         }
624
625         /**
626          * Setter for the real class name
627          *
628          * @param       $realClass      Class name (string)
629          * @return      void
630          */
631         public final function setRealClass ($realClass) {
632                 // Set real class
633                 $this->realClass = (string) $realClass;
634         }
635
636         /**
637          * Setter for database result instance
638          *
639          * @param       $resultInstance         An instance of a database result class
640          * @return      void
641          * @todo        SearchableResult and UpdateableResult shall have a super interface to use here
642          */
643         protected final function setResultInstance (SearchableResult $resultInstance) {
644                 $this->resultInstance =  $resultInstance;
645         }
646
647         /**
648          * Getter for database result instance
649          *
650          * @return      $resultInstance         An instance of a database result class
651          */
652         public final function getResultInstance () {
653                 return $this->resultInstance;
654         }
655
656         /**
657          * Setter for template engine instances
658          *
659          * @param       $templateInstance       An instance of a template engine class
660          * @return      void
661          */
662         protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
663                 $this->templateInstance = $templateInstance;
664         }
665
666         /**
667          * Getter for template engine instances
668          *
669          * @return      $templateInstance       An instance of a template engine class
670          */
671         protected final function getTemplateInstance () {
672                 return $this->templateInstance;
673         }
674
675         /**
676          * Setter for search instance
677          *
678          * @param       $searchInstance         Searchable criteria instance
679          * @return      void
680          */
681         public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
682                 $this->searchInstance = $searchInstance;
683         }
684
685         /**
686          * Getter for search instance
687          *
688          * @return      $searchInstance         Searchable criteria instance
689          */
690         public final function getSearchInstance () {
691                 return $this->searchInstance;
692         }
693
694         /**
695          * Setter for update instance
696          *
697          * @param       $updateInstance         Searchable criteria instance
698          * @return      void
699          */
700         public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
701                 $this->updateInstance = $updateInstance;
702         }
703
704         /**
705          * Getter for update instance
706          *
707          * @return      $updateInstance         Updateable criteria instance
708          */
709         public final function getUpdateInstance () {
710                 return $this->updateInstance;
711         }
712
713         /**
714          * Setter for resolver instance
715          *
716          * @param       $resolverInstance       Instance of a command resolver class
717          * @return      void
718          */
719         public final function setResolverInstance (Resolver $resolverInstance) {
720                 $this->resolverInstance = $resolverInstance;
721         }
722
723         /**
724          * Getter for resolver instance
725          *
726          * @return      $resolverInstance       Instance of a command resolver class
727          */
728         public final function getResolverInstance () {
729                 return $this->resolverInstance;
730         }
731
732         /**
733          * Setter for language instance
734          *
735          * @param       $configInstance         The configuration instance which shall
736          *                                                              be FrameworkConfiguration
737          * @return      void
738          */
739         public final function setConfigInstance (FrameworkConfiguration $configInstance) {
740                 Registry::getRegistry()->addInstance('config', $configInstance);
741         }
742
743         /**
744          * Getter for configuration instance
745          *
746          * @return      $configInstance         Configuration instance
747          */
748         public final function getConfigInstance () {
749                 $configInstance = Registry::getRegistry()->getInstance('config');
750                 return $configInstance;
751         }
752
753         /**
754          * Setter for debug instance
755          *
756          * @param       $debugInstance  The instance for debug output class
757          * @return      void
758          */
759         public final function setDebugInstance (DebugMiddleware $debugInstance) {
760                 Registry::getRegistry()->addInstance('debug', $debugInstance);
761         }
762
763         /**
764          * Getter for debug instance
765          *
766          * @return      $debugInstance  Instance to class DebugConsoleOutput or DebugWebOutput
767          */
768         public final function getDebugInstance () {
769                 // Get debug instance
770                 $debugInstance = Registry::getRegistry()->getInstance('debug');
771
772                 // Return it
773                 return $debugInstance;
774         }
775
776         /**
777          * Setter for web output instance
778          *
779          * @param       $webInstance    The instance for web output class
780          * @return      void
781          */
782         public final function setWebOutputInstance (OutputStreamer $webInstance) {
783                 Registry::getRegistry()->addInstance('web_output', $webInstance);
784         }
785
786         /**
787          * Getter for web output instance
788          *
789          * @return      $webOutputInstance - Instance to class WebOutput
790          */
791         public final function getWebOutputInstance () {
792                 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
793                 return $webOutputInstance;
794         }
795
796         /**
797          * Setter for database instance
798          *
799          * @param       $databaseInstance       The instance for the database connection (forced DatabaseConnection)
800          * @return      void
801          */
802         public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
803                 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
804         }
805
806         /**
807          * Getter for database layer
808          *
809          * @return      $databaseInstance       The database layer instance
810          */
811         public final function getDatabaseInstance () {
812                 // Get instance
813                 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
814
815                 // Return instance
816                 return $databaseInstance;
817         }
818
819         /**
820          * Setter for compressor channel
821          *
822          * @param       $compressorInstance             An instance of CompressorChannel
823          * @return      void
824          */
825         public final function setCompressorChannel (CompressorChannel $compressorInstance) {
826                 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
827         }
828
829         /**
830          * Getter for compressor channel
831          *
832          * @return      $compressorInstance             The compressor channel
833          */
834         public final function getCompressorChannel () {
835                 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
836                 return $compressorInstance;
837         }
838
839         /**
840          * Protected getter for a manageable application helper class
841          *
842          * @return      $applicationInstance    An instance of a manageable application helper class
843          */
844         protected final function getApplicationInstance () {
845                 $applicationInstance = Registry::getRegistry()->getInstance('application');
846                 return $applicationInstance;
847         }
848
849         /**
850          * Setter for a manageable application helper class
851          *
852          * @param       $applicationInstance    An instance of a manageable application helper class
853          * @return      void
854          */
855         public final function setApplicationInstance (ManageableApplication $applicationInstance) {
856                 Registry::getRegistry()->addInstance('application', $applicationInstance);
857         }
858
859         /**
860          * Setter for request instance
861          *
862          * @param       $requestInstance        An instance of a Requestable class
863          * @return      void
864          */
865         public final function setRequestInstance (Requestable $requestInstance) {
866                 $this->requestInstance = $requestInstance;
867         }
868
869         /**
870          * Getter for request instance
871          *
872          * @return      $requestInstance        An instance of a Requestable class
873          */
874         public final function getRequestInstance () {
875                 return $this->requestInstance;
876         }
877
878         /**
879          * Setter for response instance
880          *
881          * @param       $responseInstance       An instance of a Responseable class
882          * @return      void
883          */
884         public final function setResponseInstance (Responseable $responseInstance) {
885                 $this->responseInstance = $responseInstance;
886         }
887
888         /**
889          * Getter for response instance
890          *
891          * @return      $responseInstance       An instance of a Responseable class
892          */
893         public final function getResponseInstance () {
894                 return $this->responseInstance;
895         }
896
897         /**
898          * Private getter for language instance
899          *
900          * @return      $langInstance   An instance to the language sub-system
901          */
902         protected final function getLanguageInstance () {
903                 $langInstance = Registry::getRegistry()->getInstance('language');
904                 return $langInstance;
905         }
906
907         /**
908          * Setter for language instance
909          *
910          * @param       $langInstance   An instance to the language sub-system
911          * @return      void
912          * @see         LanguageSystem
913          */
914         public final function setLanguageInstance (ManageableLanguage $langInstance) {
915                 Registry::getRegistry()->addInstance('language', $langInstance);
916         }
917
918         /**
919          * Private getter for file IO instance
920          *
921          * @return      $fileIoInstance         An instance to the file I/O sub-system
922          */
923         protected final function getFileIoInstance () {
924                 return $this->fileIoInstance;
925         }
926
927         /**
928          * Setter for file I/O instance
929          *
930          * @param       $fileIoInstance         An instance to the file I/O sub-system
931          * @return      void
932          */
933         public final function setFileIoInstance (IoHandler $fileIoInstance) {
934                 $this->fileIoInstance = $fileIoInstance;
935         }
936
937         /**
938          * Protected setter for user instance
939          *
940          * @param       $userInstance   An instance of a user class
941          * @return      void
942          */
943         protected final function setUserInstance (ManageableAccount $userInstance) {
944                 $this->userInstance = $userInstance;
945         }
946
947         /**
948          * Getter for user instance
949          *
950          * @return      $userInstance   An instance of a user class
951          */
952         public final function getUserInstance () {
953                 return $this->userInstance;
954         }
955
956         /**
957          * Setter for controller instance (this surely breaks a bit the MVC patterm)
958          *
959          * @param       $controllerInstance             An instance of the controller
960          * @return      void
961          */
962         public final function setControllerInstance (Controller $controllerInstance) {
963                 $this->controllerInstance = $controllerInstance;
964         }
965
966         /**
967          * Getter for controller instance (this surely breaks a bit the MVC patterm)
968          *
969          * @return      $controllerInstance             An instance of the controller
970          */
971         public final function getControllerInstance () {
972                 return $this->controllerInstance;
973         }
974
975         /**
976          * Setter for RNG instance
977          *
978          * @param       $rngInstance    An instance of a random number generator (RNG)
979          * @return      void
980          */
981         protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
982                 $this->rngInstance = $rngInstance;
983         }
984
985         /**
986          * Getter for RNG instance
987          *
988          * @return      $rngInstance    An instance of a random number generator (RNG)
989          */
990         public final function getRngInstance () {
991                 return $this->rngInstance;
992         }
993
994         /**
995          * Setter for Cryptable instance
996          *
997          * @param       $cryptoInstance An instance of a Cryptable class
998          * @return      void
999          */
1000         protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1001                 $this->cryptoInstance = $cryptoInstance;
1002         }
1003
1004         /**
1005          * Getter for Cryptable instance
1006          *
1007          * @return      $cryptoInstance An instance of a Cryptable class
1008          */
1009         public final function getCryptoInstance () {
1010                 return $this->cryptoInstance;
1011         }
1012
1013         /**
1014          * Setter for the list instance
1015          *
1016          * @param       $listInstance   A list of Listable
1017          * @return      void
1018          */
1019         protected final function setListInstance (Listable $listInstance) {
1020                 $this->listInstance = $listInstance;
1021         }
1022
1023         /**
1024          * Getter for the list instance
1025          *
1026          * @return      $listInstance   A list of Listable
1027          */
1028         protected final function getListInstance () {
1029                 return $this->listInstance;
1030         }
1031
1032         /**
1033          * Setter for the menu instance
1034          *
1035          * @param       $menuInstance   A RenderableMenu instance
1036          * @return      void
1037          */
1038         protected final function setMenuInstance (RenderableMenu $menuInstance) {
1039                 $this->menuInstance = $menuInstance;
1040         }
1041
1042         /**
1043          * Getter for the menu instance
1044          *
1045          * @return      $menuInstance   A RenderableMenu instance
1046          */
1047         protected final function getMenuInstance () {
1048                 return $this->menuInstance;
1049         }
1050
1051         /**
1052          * Setter for image instance
1053          *
1054          * @param       $imageInstance  An instance of an image
1055          * @return      void
1056          */
1057         public final function setImageInstance (BaseImage $imageInstance) {
1058                 $this->imageInstance = $imageInstance;
1059         }
1060
1061         /**
1062          * Getter for image instance
1063          *
1064          * @return      $imageInstance  An instance of an image
1065          */
1066         public final function getImageInstance () {
1067                 return $this->imageInstance;
1068         }
1069
1070         /**
1071          * Setter for stacker instance
1072          *
1073          * @param       $stackInstance  An instance of an stacker
1074          * @return      void
1075          */
1076         public final function setStackInstance (Stackable $stackInstance) {
1077                 $this->stackInstance = $stackInstance;
1078         }
1079
1080         /**
1081          * Getter for stacker instance
1082          *
1083          * @return      $stackInstance  An instance of an stacker
1084          */
1085         public final function getStackInstance () {
1086                 return $this->stackInstance;
1087         }
1088
1089         /**
1090          * Setter for compressor instance
1091          *
1092          * @param       $compressorInstance     An instance of an compressor
1093          * @return      void
1094          */
1095         public final function setCompressorInstance (Compressor $compressorInstance) {
1096                 $this->compressorInstance = $compressorInstance;
1097         }
1098
1099         /**
1100          * Getter for compressor instance
1101          *
1102          * @return      $compressorInstance     An instance of an compressor
1103          */
1104         public final function getCompressorInstance () {
1105                 return $this->compressorInstance;
1106         }
1107
1108         /**
1109          * Setter for Parseable instance
1110          *
1111          * @param       $parserInstance An instance of an Parseable
1112          * @return      void
1113          */
1114         public final function setParserInstance (Parseable $parserInstance) {
1115                 $this->parserInstance = $parserInstance;
1116         }
1117
1118         /**
1119          * Getter for Parseable instance
1120          *
1121          * @return      $parserInstance An instance of an Parseable
1122          */
1123         public final function getParserInstance () {
1124                 return $this->parserInstance;
1125         }
1126
1127         /**
1128          * Setter for HandleableProtocol instance
1129          *
1130          * @param       $protocolInstance       An instance of an HandleableProtocol
1131          * @return      void
1132          */
1133         public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1134                 $this->protocolInstance = $protocolInstance;
1135         }
1136
1137         /**
1138          * Getter for HandleableProtocol instance
1139          *
1140          * @return      $protocolInstance       An instance of an HandleableProtocol
1141          */
1142         public final function getProtocolInstance () {
1143                 return $this->protocolInstance;
1144         }
1145
1146         /**
1147          * Setter for DatabaseWrapper instance
1148          *
1149          * @param       $wrapperInstance        An instance of an DatabaseWrapper
1150          * @return      void
1151          */
1152         public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1153                 $this->wrapperInstance = $wrapperInstance;
1154         }
1155
1156         /**
1157          * Getter for DatabaseWrapper instance
1158          *
1159          * @return      $wrapperInstance        An instance of an DatabaseWrapper
1160          */
1161         public final function getWrapperInstance () {
1162                 return $this->wrapperInstance;
1163         }
1164
1165         /**
1166          * Setter for socket resource
1167          *
1168          * @param       $socketResource         A valid socket resource
1169          * @return      void
1170          */
1171         public final function setSocketResource ($socketResource) {
1172                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1173                 $this->socketResource = $socketResource;
1174         }
1175
1176         /**
1177          * Getter for socket resource
1178          *
1179          * @return      $socketResource         A valid socket resource
1180          */
1181         public final function getSocketResource () {
1182                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1183                 return $this->socketResource;
1184         }
1185
1186         /**
1187          * Setter for regular expression
1188          *
1189          * @param       $regularExpression      A valid regular expression
1190          * @return      void
1191          */
1192         public final function setRegularExpression ($regularExpression) {
1193                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1194                 $this->regularExpression = $regularExpression;
1195         }
1196
1197         /**
1198          * Getter for regular expression
1199          *
1200          * @return      $regularExpression      A valid regular expression
1201          */
1202         public final function getRegularExpression () {
1203                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1204                 return $this->regularExpression;
1205         }
1206
1207         /**
1208          * Setter for helper instance
1209          *
1210          * @param       $helperInstance         An instance of a helper class
1211          * @return      void
1212          */
1213         protected final function setHelperInstance (Helper $helperInstance) {
1214                 $this->helperInstance = $helperInstance;
1215         }
1216
1217         /**
1218          * Getter for helper instance
1219          *
1220          * @return      $helperInstance         An instance of a helper class
1221          */
1222         public final function getHelperInstance () {
1223                 return $this->helperInstance;
1224         }
1225
1226         /**
1227          * Setter for a Source instance
1228          *
1229          * @param       $sourceInstance         An instance of a Source class
1230          * @return      void
1231          */
1232         protected final function setSourceInstance (Source $sourceInstance) {
1233                 $this->sourceInstance = $sourceInstance;
1234         }
1235
1236         /**
1237          * Getter for a Source instance
1238          *
1239          * @return      $sourceInstance         An instance of a Source class
1240          */
1241         protected final function getSourceInstance () {
1242                 return $this->sourceInstance;
1243         }
1244
1245         /**
1246          * Setter for a UrlSource instance
1247          *
1248          * @param       $sourceInstance         An instance of a UrlSource class
1249          * @return      void
1250          */
1251         protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1252                 $this->urlSourceInstance = $urlSourceInstance;
1253         }
1254
1255         /**
1256          * Getter for a UrlSource instance
1257          *
1258          * @return      $urlSourceInstance              An instance of a UrlSource class
1259          */
1260         protected final function getUrlSourceInstance () {
1261                 return $this->urlSourceInstance;
1262         }
1263
1264         /**
1265          * Getter for a InputStream instance
1266          *
1267          * @param       $inputStreamInstance    The InputStream instance
1268          */
1269         protected final function getInputStreamInstance () {
1270                 return $this->inputStreamInstance;
1271         }
1272
1273         /**
1274          * Setter for a InputStream instance
1275          *
1276          * @param       $inputStreamInstance    The InputStream instance
1277          * @return      void
1278          */
1279         protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1280                 $this->inputStreamInstance = $inputStreamInstance;
1281         }
1282
1283         /**
1284          * Getter for a OutputStream instance
1285          *
1286          * @param       $outputStreamInstance   The OutputStream instance
1287          */
1288         protected final function getOutputStreamInstance () {
1289                 return $this->outputStreamInstance;
1290         }
1291
1292         /**
1293          * Setter for a OutputStream instance
1294          *
1295          * @param       $outputStreamInstance   The OutputStream instance
1296          * @return      void
1297          */
1298         protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1299                 $this->outputStreamInstance = $outputStreamInstance;
1300         }
1301
1302         /**
1303          * Setter for handler instance
1304          *
1305          * @param       $handlerInstance        An instance of a Handleable class
1306          * @return      void
1307          */
1308         protected final function setHandlerInstance (Handleable $handlerInstance) {
1309                 $this->handlerInstance = $handlerInstance;
1310         }
1311
1312         /**
1313          * Getter for handler instance
1314          *
1315          * @return      $handlerInstance        A Networkable instance
1316          */
1317         protected final function getHandlerInstance () {
1318                 return $this->handlerInstance;
1319         }
1320
1321         /**
1322          * Setter for visitor instance
1323          *
1324          * @param       $visitorInstance        A Visitor instance
1325          * @return      void
1326          */
1327         protected final function setVisitorInstance (Visitor $visitorInstance) {
1328                 $this->visitorInstance = $visitorInstance;
1329         }
1330
1331         /**
1332          * Getter for visitor instance
1333          *
1334          * @return      $visitorInstance        A Visitor instance
1335          */
1336         protected final function getVisitorInstance () {
1337                 return $this->visitorInstance;
1338         }
1339
1340         /**
1341          * Setter for DHT instance
1342          *
1343          * @param       $dhtInstance    A Distributable instance
1344          * @return      void
1345          */
1346         protected final function setDhtInstance (Distributable $dhtInstance) {
1347                 $this->dhtInstance = $dhtInstance;
1348         }
1349
1350         /**
1351          * Getter for DHT instance
1352          *
1353          * @return      $dhtInstance    A Distributable instance
1354          */
1355         protected final function getDhtInstance () {
1356                 return $this->dhtInstance;
1357         }
1358
1359         /**
1360          * Setter for raw package Data
1361          *
1362          * @param       $packageData    Raw package Data
1363          * @return      void
1364          */
1365         public final function setPackageData (array $packageData) {
1366                 $this->packageData = $packageData;
1367         }
1368
1369         /**
1370          * Getter for raw package Data
1371          *
1372          * @return      $packageData    Raw package Data
1373          */
1374         public function getPackageData () {
1375                 return $this->packageData;
1376         }
1377
1378
1379         /**
1380          * Setter for Iterator instance
1381          *
1382          * @param       $iteratorInstance       An instance of an Iterator
1383          * @return      void
1384          */
1385         protected final function setIteratorInstance (Iterator $iteratorInstance) {
1386                 $this->iteratorInstance = $iteratorInstance;
1387         }
1388
1389         /**
1390          * Getter for Iterator instance
1391          *
1392          * @return      $iteratorInstance       An instance of an Iterator
1393          */
1394         public final function getIteratorInstance () {
1395                 return $this->iteratorInstance;
1396         }
1397
1398         /**
1399          * Setter for FilePointer instance
1400          *
1401          * @param       $pointerInstance        An instance of an FilePointer class
1402          * @return      void
1403          */
1404         protected final function setPointerInstance (FilePointer $pointerInstance) {
1405                 $this->pointerInstance = $pointerInstance;
1406         }
1407
1408         /**
1409          * Getter for FilePointer instance
1410          *
1411          * @return      $pointerInstance        An instance of an FilePointer class
1412          */
1413         public final function getPointerInstance () {
1414                 return $this->pointerInstance;
1415         }
1416
1417         /**
1418          * Unsets pointer instance which triggers a call of __destruct() if the
1419          * instance is still there. This is surely not fatal on already "closed"
1420          * file pointer instances.
1421          *
1422          * I don't want to mess around with above setter by giving it a default
1423          * value NULL as setter should always explicitly only set (existing) object
1424          * instances and NULL is NULL.
1425          *
1426          * @return      void
1427          */
1428         protected final function unsetPointerInstance () {
1429                 // Simply it to NULL
1430                 $this->pointerInstance = NULL;
1431         }
1432
1433         /**
1434          * Setter for Indexable instance
1435          *
1436          * @param       $indexInstance  An instance of an Indexable class
1437          * @return      void
1438          */
1439         protected final function setIndexInstance (Indexable $indexInstance) {
1440                 $this->indexInstance = $indexInstance;
1441         }
1442
1443         /**
1444          * Getter for Indexable instance
1445          *
1446          * @return      $indexInstance  An instance of an Indexable class
1447          */
1448         public final function getIndexInstance () {
1449                 return $this->indexInstance;
1450         }
1451
1452         /**
1453          * Setter for Block instance
1454          *
1455          * @param       $blockInstance  An instance of an Block class
1456          * @return      void
1457          */
1458         protected final function setBlockInstance (Block $blockInstance) {
1459                 $this->blockInstance = $blockInstance;
1460         }
1461
1462         /**
1463          * Getter for Block instance
1464          *
1465          * @return      $blockInstance  An instance of an Block class
1466          */
1467         public final function getBlockInstance () {
1468                 return $this->blockInstance;
1469         }
1470
1471         /**
1472          * Setter for Minable instance
1473          *
1474          * @param       $minableInstance        A Minable instance
1475          * @return      void
1476          */
1477         protected final function setMinableInstance (Minable $minableInstance) {
1478                 $this->minableInstance = $minableInstance;
1479         }
1480
1481         /**
1482          * Getter for minable instance
1483          *
1484          * @return      $minableInstance        A Minable instance
1485          */
1486         protected final function getMinableInstance () {
1487                 return $this->minableInstance;
1488         }
1489
1490         /**
1491          * Setter for FrameworkDirectory instance
1492          *
1493          * @param       $directoryInstance      A FrameworkDirectoryPointer instance
1494          * @return      void
1495          */
1496         protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1497                 $this->directoryInstance = $directoryInstance;
1498         }
1499
1500         /**
1501          * Getter for FrameworkDirectory instance
1502          *
1503          * @return      $directoryInstance      A FrameworkDirectory instance
1504          */
1505         protected final function getDirectoryInstance () {
1506                 return $this->directoryInstance;
1507         }
1508
1509         /**
1510          * Setter for listener instance
1511          *
1512          * @param       $listenerInstance       A Listenable instance
1513          * @return      void
1514          */
1515         protected final function setListenerInstance (Listenable $listenerInstance) {
1516                 $this->listenerInstance = $listenerInstance;
1517         }
1518
1519         /**
1520          * Getter for listener instance
1521          *
1522          * @return      $listenerInstance       A Listenable instance
1523          */
1524         protected final function getListenerInstance () {
1525                 return $this->listenerInstance;
1526         }
1527
1528         /**
1529          * Getter for communicator instance
1530          *
1531          * @return      $communicatorInstance   An instance of a Communicator class
1532          */
1533         public final function getCommunicatorInstance () {
1534                 return $this->communicatorInstance;
1535         }
1536
1537         /**
1538          * Setter for communicator instance
1539          *
1540          * @param       $communicatorInstance   An instance of a Communicator class
1541          * @return      void
1542          */
1543         protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1544                 $this->communicatorInstance = $communicatorInstance;
1545         }
1546
1547         /**
1548          * Setter for state instance
1549          *
1550          * @param       $stateInstance  A Stateable instance
1551          * @return      void
1552          */
1553         public final function setStateInstance (Stateable $stateInstance) {
1554                 $this->stateInstance = $stateInstance;
1555         }
1556
1557         /**
1558          * Getter for state instance
1559          *
1560          * @return      $stateInstance  A Stateable instance
1561          */
1562         public final function getStateInstance () {
1563                 return $this->stateInstance;
1564         }
1565
1566         /**
1567          * Setter for command name
1568          *
1569          * @param       $commandName    Last validated command name
1570          * @return      void
1571          */
1572         protected final function setCommandName ($commandName) {
1573                 $this->commandName = $commandName;
1574         }
1575
1576         /**
1577          * Getter for command name
1578          *
1579          * @return      $commandName    Last validated command name
1580          */
1581         protected final function getCommandName () {
1582                 return $this->commandName;
1583         }
1584
1585         /**
1586          * Setter for controller name
1587          *
1588          * @param       $controllerName Last validated controller name
1589          * @return      void
1590          */
1591         protected final function setControllerName ($controllerName) {
1592                 $this->controllerName = $controllerName;
1593         }
1594
1595         /**
1596          * Getter for controller name
1597          *
1598          * @return      $controllerName Last validated controller name
1599          */
1600         protected final function getControllerName () {
1601                 return $this->controllerName;
1602         }
1603
1604         /**
1605          * Getter for protocol name
1606          *
1607          * @return      $protocolName   Name of used protocol
1608          */
1609         public final function getProtocolName () {
1610                 return $this->protocolName;
1611         }
1612
1613         /**
1614          * Setter for protocol name
1615          *
1616          * @param       $protocolName   Name of used protocol
1617          * @return      void
1618          */
1619         protected final function setProtocolName ($protocolName) {
1620                 $this->protocolName = $protocolName;
1621         }
1622
1623         /**
1624          * Checks whether an object equals this object. You should overwrite this
1625          * method to implement own equality checks
1626          *
1627          * @param       $objectInstance         An instance of a FrameworkInterface object
1628          * @return      $equals                         Whether both objects equals
1629          */
1630         public function equals (FrameworkInterface $objectInstance) {
1631                 // Now test it
1632                 $equals = ((
1633                         $this->__toString() == $objectInstance->__toString()
1634                 ) && (
1635                         $this->hashCode() == $objectInstance->hashCode()
1636                 ));
1637
1638                 // Return the result
1639                 return $equals;
1640         }
1641
1642         /**
1643          * Generates a generic hash code of this class. You should really overwrite
1644          * this method with your own hash code generator code. But keep KISS in mind.
1645          *
1646          * @return      $hashCode       A generic hash code respresenting this whole class
1647          */
1648         public function hashCode () {
1649                 // Simple hash code
1650                 return crc32($this->__toString());
1651         }
1652
1653         /**
1654          * Formats computer generated price values into human-understandable formats
1655          * with thousand and decimal separators.
1656          *
1657          * @param       $value          The in computer format value for a price
1658          * @param       $currency       The currency symbol (use HTML-valid characters!)
1659          * @param       $decNum         Number of decimals after commata
1660          * @return      $price          The for the current language formated price string
1661          * @throws      MissingDecimalsThousandsSeparatorException      If decimals or
1662          *                                                                                              thousands separator
1663          *                                                                                              is missing
1664          */
1665         public function formatCurrency ($value, $currency = '&euro;', $decNum = 2) {
1666                 // Are all required attriutes set?
1667                 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1668                         // Throw an exception
1669                         throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1670                 } // END - if
1671
1672                 // Cast the number
1673                 $value = (float) $value;
1674
1675                 // Reformat the US number
1676                 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1677
1678                 // Return as string...
1679                 return $price;
1680         }
1681
1682         /**
1683          * Appends a trailing slash to a string
1684          *
1685          * @param       $str    A string (maybe) without trailing slash
1686          * @return      $str    A string with an auto-appended trailing slash
1687          */
1688         public final function addMissingTrailingSlash ($str) {
1689                 // Is there a trailing slash?
1690                 if (substr($str, -1, 1) != '/') {
1691                         $str .= '/';
1692                 } // END - if
1693
1694                 // Return string with trailing slash
1695                 return $str;
1696         }
1697
1698         /**
1699          * Prepare the template engine (HtmlTemplateEngine by default) for a given
1700          * application helper instance (ApplicationHelper by default).
1701          *
1702          * @param               $applicationInstance    An application helper instance or
1703          *                                                                              null if we shall use the default
1704          * @return              $templateInstance               The template engine instance
1705          * @throws              NullPointerException    If the discovered application
1706          *                                                                              instance is still null
1707          */
1708         protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1709                 // Is the application instance set?
1710                 if (is_null($applicationInstance)) {
1711                         // Get the current instance
1712                         $applicationInstance = $this->getApplicationInstance();
1713
1714                         // Still null?
1715                         if (is_null($applicationInstance)) {
1716                                 // Thrown an exception
1717                                 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1718                         } // END - if
1719                 } // END - if
1720
1721                 // Initialize the template engine
1722                 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1723
1724                 // Return the prepared instance
1725                 return $templateInstance;
1726         }
1727
1728         /**
1729          * Debugs this instance by putting out it's full content
1730          *
1731          * @param       $message        Optional message to show in debug output
1732          * @return      void
1733          */
1734         public final function debugInstance ($message = '') {
1735                 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1736                 restore_error_handler();
1737
1738                 // Init content
1739                 $content = '';
1740
1741                 // Is a message set?
1742                 if (!empty($message)) {
1743                         // Construct message
1744                         $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1745                 } // END - if
1746
1747                 // Generate the output
1748                 $content .= sprintf('<pre>%s</pre>',
1749                         trim(
1750                                 htmlentities(
1751                                         print_r($this, TRUE)
1752                                 )
1753                         )
1754                 );
1755
1756                 // Output it
1757                 ApplicationEntryPoint::app_exit(sprintf('<div class="debug_header">%s debug output:</div><div class="debug_content">%s</div>Loaded includes: <div class="debug_include_list">%s</div>',
1758                         $this->__toString(),
1759                         $content,
1760                         ClassLoader::getSelfInstance()->getPrintableIncludeList()
1761                 ));
1762         }
1763
1764         /**
1765          * Replaces control characters with printable output
1766          *
1767          * @param       $str    String with control characters
1768          * @return      $str    Replaced string
1769          */
1770         protected function replaceControlCharacters ($str) {
1771                 // Replace them
1772                 $str = str_replace(
1773                         chr(13), '[r]', str_replace(
1774                         chr(10), '[n]', str_replace(
1775                         chr(9) , '[t]',
1776                         $str
1777                 )));
1778
1779                 // Return it
1780                 return $str;
1781         }
1782
1783         /**
1784          * Output a partial stub message for the caller method
1785          *
1786          * @param       $message        An optional message to display
1787          * @return      void
1788          */
1789         protected function partialStub ($message = '') {
1790                 // Get the backtrace
1791                 $backtrace = debug_backtrace();
1792
1793                 // Generate the class::method string
1794                 $methodName = 'UnknownClass-&gt;unknownMethod';
1795                 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1796                         $methodName = $backtrace[1]['class'] . '-&gt;' . $backtrace[1]['function'];
1797                 } // END - if
1798
1799                 // Construct the full message
1800                 $stubMessage = sprintf('[%s:] Partial stub!',
1801                         $methodName
1802                 );
1803
1804                 // Is the extra message given?
1805                 if (!empty($message)) {
1806                         // Then add it as well
1807                         $stubMessage .= ' Message: ' . $message;
1808                 } // END - if
1809
1810                 // Debug instance is there?
1811                 if (!is_null($this->getDebugInstance())) {
1812                         // Output stub message
1813                         self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1814                 } else {
1815                         // Trigger an error
1816                         trigger_error($stubMessage);
1817                         exit;
1818                 }
1819         }
1820
1821         /**
1822          * Outputs a debug backtrace and stops further script execution
1823          *
1824          * @param       $message        An optional message to output
1825          * @param       $doExit         Whether exit the program (TRUE is default)
1826          * @return      void
1827          */
1828         public function debugBackTrace ($message = '', $doExit = TRUE) {
1829                 // Sorry, there is no other way getting this nice backtrace
1830                 if (!empty($message)) {
1831                         // Output message
1832                         printf('Message: %s<br />' . chr(10), $message);
1833                 } // END - if
1834
1835                 print('<pre>');
1836                 debug_print_backtrace();
1837                 print('</pre>');
1838
1839                 // Exit program?
1840                 if ($doExit === TRUE) {
1841                         exit();
1842                 } // END - if
1843         }
1844
1845         /**
1846          * Creates an instance of a debugger instance
1847          *
1848          * @param       $className              Name of the class (currently unsupported)
1849          * @return      $debugInstance  An instance of a debugger class
1850          */
1851         public final static function createDebugInstance ($className) {
1852                 // Is the instance set?
1853                 if (!Registry::getRegistry()->instanceExists('debug')) {
1854                         // Init debug instance
1855                         $debugInstance = NULL;
1856
1857                         // Try it
1858                         try {
1859                                 // Get a debugger instance
1860                                 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'));
1861                         } catch (NullPointerException $e) {
1862                                 // Didn't work, no instance there
1863                                 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1864                         }
1865
1866                         // Empty string should be ignored and used for testing the middleware
1867                         DebugMiddleware::getSelfInstance()->output('');
1868
1869                         // Set it in its own class. This will set it in the registry
1870                         $debugInstance->setDebugInstance($debugInstance);
1871                 } else {
1872                         // Get instance from registry
1873                         $debugInstance = Registry::getRegistry()->getDebugInstance();
1874                 }
1875
1876                 // Return it
1877                 return $debugInstance;
1878         }
1879
1880         /**
1881          * Simple output of a message with line-break
1882          *
1883          * @param       $message        Message to output
1884          * @return      void
1885          */
1886         public function outputLine ($message) {
1887                 // Simply output it
1888                 print($message . PHP_EOL);
1889         }
1890
1891         /**
1892          * Outputs a debug message whether to debug instance (should be set!) or
1893          * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1894          * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1895          *
1896          * @param       $message        Message we shall send out...
1897          * @param       $doPrint        Whether print or die here (default: print)
1898          * @paran       $stripTags      Whether to strip tags (default: FALSE)
1899          * @return      void
1900          */
1901         public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1902                 // Set debug instance to NULL
1903                 $debugInstance = NULL;
1904
1905                 // Try it:
1906                 try {
1907                         // Get debug instance
1908                         $debugInstance = $this->getDebugInstance();
1909                 } catch (NullPointerException $e) {
1910                         // The debug instance is not set (yet)
1911                 }
1912
1913                 // Is the debug instance there?
1914                 if (is_object($debugInstance)) {
1915                         // Use debug output handler
1916                         $debugInstance->output($message, $stripTags);
1917
1918                         if ($doPrint === FALSE) {
1919                                 // Die here if not printed
1920                                 exit();
1921                         } // END - if
1922                 } else {
1923                         // Are debug times enabled?
1924                         if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1925                                 // Prepent it
1926                                 $message = $this->getPrintableExecutionTime() . $message;
1927                         } // END - if
1928
1929                         // Put directly out
1930                         if ($doPrint === TRUE) {
1931                                 // Print message
1932                                 $this->outputLine($message);
1933                         } else {
1934                                 // Die here
1935                                 exit($message);
1936                         }
1937                 }
1938         }
1939
1940         /**
1941          * Converts e.g. a command from URL to a valid class by keeping out bad characters
1942          *
1943          * @param       $str            The string, what ever it is needs to be converted
1944          * @return      $className      Generated class name
1945          */
1946         public static final function convertToClassName ($str) {
1947                 // Init class name
1948                 $className = '';
1949
1950                 // Convert all dashes in underscores
1951                 $str = self::convertDashesToUnderscores($str);
1952
1953                 // Now use that underscores to get classname parts for hungarian style
1954                 foreach (explode('_', $str) as $strPart) {
1955                         // Make the class name part lower case and first upper case
1956                         $className .= ucfirst(strtolower($strPart));
1957                 } // END - foreach
1958
1959                 // Return class name
1960                 return $className;
1961         }
1962
1963         /**
1964          * Converts dashes to underscores, e.g. useable for configuration entries
1965          *
1966          * @param       $str    The string with maybe dashes inside
1967          * @return      $str    The converted string with no dashed, but underscores
1968          */
1969         public static final function convertDashesToUnderscores ($str) {
1970                 // Convert them all
1971                 $str = str_replace('-', '_', $str);
1972
1973                 // Return converted string
1974                 return $str;
1975         }
1976
1977         /**
1978          * Marks up the code by adding e.g. line numbers
1979          *
1980          * @param       $phpCode                Unmarked PHP code
1981          * @return      $markedCode             Marked PHP code
1982          */
1983         public function markupCode ($phpCode) {
1984                 // Init marked code
1985                 $markedCode = '';
1986
1987                 // Get last error
1988                 $errorArray = error_get_last();
1989
1990                 // Init the code with error message
1991                 if (is_array($errorArray)) {
1992                         // Get error infos
1993                         $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>',
1994                                 basename($errorArray['file']),
1995                                 $errorArray['line'],
1996                                 $errorArray['message'],
1997                                 $errorArray['type']
1998                         );
1999                 } // END - if
2000
2001                 // Add line number to the code
2002                 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2003                         // Add line numbers
2004                         $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
2005                                 ($lineNo + 1),
2006                                 htmlentities($code, ENT_QUOTES)
2007                         );
2008                 } // END - foreach
2009
2010                 // Return the code
2011                 return $markedCode;
2012         }
2013
2014         /**
2015          * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2016          * beatiful for web-based front-ends. If null is given a message id
2017          * null_timestamp will be resolved and returned.
2018          *
2019          * @param       $timestamp      Timestamp to prepare (filter) for display
2020          * @return      $readable       A readable timestamp
2021          */
2022         public function doFilterFormatTimestamp ($timestamp) {
2023                 // Default value to return
2024                 $readable = '???';
2025
2026                 // Is the timestamp null?
2027                 if (is_null($timestamp)) {
2028                         // Get a message string
2029                         $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2030                 } else {
2031                         switch ($this->getLanguageInstance()->getLanguageCode()) {
2032                                 case 'de': // German format is a bit different to default
2033                                         // Split the GMT stamp up
2034                                         $dateTime  = explode(' ', $timestamp  );
2035                                         $dateArray = explode('-', $dateTime[0]);
2036                                         $timeArray = explode(':', $dateTime[1]);
2037
2038                                         // Construct the timestamp
2039                                         $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2040                                                 $dateArray[0],
2041                                                 $dateArray[1],
2042                                                 $dateArray[2],
2043                                                 $timeArray[0],
2044                                                 $timeArray[1],
2045                                                 $timeArray[2]
2046                                         );
2047                                         break;
2048
2049                                 default: // Default is pass-through
2050                                         $readable = $timestamp;
2051                                         break;
2052                         } // END - switch
2053                 }
2054
2055                 // Return the stamp
2056                 return $readable;
2057         }
2058
2059         /**
2060          * Filter a given number into a localized number
2061          *
2062          * @param       $value          The raw value from e.g. database
2063          * @return      $localized      Localized value
2064          */
2065         public function doFilterFormatNumber ($value) {
2066                 // Generate it from config and localize dependencies
2067                 switch ($this->getLanguageInstance()->getLanguageCode()) {
2068                         case 'de': // German format is a bit different to default
2069                                 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2070                                 break;
2071
2072                         default: // US, etc.
2073                                 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2074                                 break;
2075                 } // END - switch
2076
2077                 // Return it
2078                 return $localized;
2079         }
2080
2081         /**
2082          * "Getter" for databse entry
2083          *
2084          * @return      $entry  An array with database entries
2085          * @throws      NullPointerException    If the database result is not found
2086          * @throws      InvalidDatabaseResultException  If the database result is invalid
2087          */
2088         protected final function getDatabaseEntry () {
2089                 // Is there an instance?
2090                 if (!$this->getResultInstance() instanceof SearchableResult) {
2091                         // Throw an exception here
2092                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2093                 } // END - if
2094
2095                 // Rewind it
2096                 $this->getResultInstance()->rewind();
2097
2098                 // Do we have an entry?
2099                 if ($this->getResultInstance()->valid() === FALSE) {
2100                         // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2101                         throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2102                 } // END - if
2103
2104                 // Get next entry
2105                 $this->getResultInstance()->next();
2106
2107                 // Fetch it
2108                 $entry = $this->getResultInstance()->current();
2109
2110                 // And return it
2111                 return $entry;
2112         }
2113
2114         /**
2115          * Getter for field name
2116          *
2117          * @param       $fieldName              Field name which we shall get
2118          * @return      $fieldValue             Field value from the user
2119          * @throws      NullPointerException    If the result instance is null
2120          */
2121         public final function getField ($fieldName) {
2122                 // Default field value
2123                 $fieldValue = NULL;
2124
2125                 // Get result instance
2126                 $resultInstance = $this->getResultInstance();
2127
2128                 // Is this instance null?
2129                 if (is_null($resultInstance)) {
2130                         // Then the user instance is no longer valid (expired cookies?)
2131                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2132                 } // END - if
2133
2134                 // Get current array
2135                 $fieldArray = $resultInstance->current();
2136                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2137
2138                 // Convert dashes to underscore
2139                 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2140
2141                 // Does the field exist?
2142                 if ($this->isFieldSet($fieldName)) {
2143                         // Get it
2144                         $fieldValue = $fieldArray[$fieldName2];
2145                 } elseif (defined('DEVELOPER')) {
2146                         // Missing field entry, may require debugging
2147                         self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2148                 } else {
2149                         // Missing field entry, may require debugging
2150                         self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2151                 }
2152
2153                 // Return it
2154                 return $fieldValue;
2155         }
2156
2157         /**
2158          * Checks if given field is set
2159          *
2160          * @param       $fieldName      Field name to check
2161          * @return      $isSet          Whether the given field name is set
2162          * @throws      NullPointerException    If the result instance is null
2163          */
2164         public function isFieldSet ($fieldName) {
2165                 // Get result instance
2166                 $resultInstance = $this->getResultInstance();
2167
2168                 // Is this instance null?
2169                 if (is_null($resultInstance)) {
2170                         // Then the user instance is no longer valid (expired cookies?)
2171                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2172                 } // END - if
2173
2174                 // Get current array
2175                 $fieldArray = $resultInstance->current();
2176                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2177
2178                 // Convert dashes to underscore
2179                 $fieldName = self::convertDashesToUnderscores($fieldName);
2180
2181                 // Determine it
2182                 $isSet = isset($fieldArray[$fieldName]);
2183
2184                 // Return result
2185                 return $isSet;
2186         }
2187
2188         /**
2189          * Flushs all pending updates to the database layer
2190          *
2191          * @return      void
2192          */
2193         public function flushPendingUpdates () {
2194                 // Get result instance
2195                 $resultInstance = $this->getResultInstance();
2196
2197                 // Do we have data to update?
2198                 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2199                         // Get wrapper class name config entry
2200                         $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2201
2202                         // Create object instance
2203                         $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2204
2205                         // Yes, then send the whole result to the database layer
2206                         $wrapperInstance->doUpdateByResult($this->getResultInstance());
2207                 } // END - if
2208         }
2209
2210         /**
2211          * Outputs a deprecation warning to the developer.
2212          *
2213          * @param       $message        The message we shall output to the developer
2214          * @return      void
2215          * @todo        Write a logging mechanism for productive mode
2216          */
2217         public function deprecationWarning ($message) {
2218                 // Is developer mode active?
2219                 if (defined('DEVELOPER')) {
2220                         // Debug instance is there?
2221                         if (!is_null($this->getDebugInstance())) {
2222                                 // Output stub message
2223                                 self::createDebugInstance(__CLASS__)->debugOutput($message);
2224                         } else {
2225                                 // Trigger an error
2226                                 trigger_error($message . "<br />\n");
2227                                 exit;
2228                         }
2229                 } else {
2230                         // @TODO Finish this part!
2231                         $this->partialStub('Developer mode inactive. Message:' . $message);
2232                 }
2233         }
2234
2235         /**
2236          * Checks whether the given PHP extension is loaded
2237          *
2238          * @param       $phpExtension   The PHP extension we shall check
2239          * @return      $isLoaded       Whether the PHP extension is loaded
2240          */
2241         public final function isPhpExtensionLoaded ($phpExtension) {
2242                 // Is it loaded?
2243                 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2244
2245                 // Return result
2246                 return $isLoaded;
2247         }
2248
2249         /**
2250          * "Getter" as a time() replacement but with milliseconds. You should use this
2251          * method instead of the encapsulated getimeofday() function.
2252          *
2253          * @return      $milliTime      Timestamp with milliseconds
2254          */
2255         public function getMilliTime () {
2256                 // Get the time of day as float
2257                 $milliTime = gettimeofday(TRUE);
2258
2259                 // Return it
2260                 return $milliTime;
2261         }
2262
2263         /**
2264          * Idles (sleeps) for given milliseconds
2265          *
2266          * @return      $hasSlept       Whether it goes fine
2267          */
2268         public function idle ($milliSeconds) {
2269                 // Sleep is fine by default
2270                 $hasSlept = TRUE;
2271
2272                 // Idle so long with found function
2273                 if (function_exists('time_sleep_until')) {
2274                         // Get current time and add idle time
2275                         $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2276
2277                         // New PHP 5.1.0 function found, ignore errors
2278                         $hasSlept = @time_sleep_until($sleepUntil);
2279                 } else {
2280                         /*
2281                          * My Sun station doesn't have that function even with latest PHP
2282                          * package. :(
2283                          */
2284                         usleep($milliSeconds * 1000);
2285                 }
2286
2287                 // Return result
2288                 return $hasSlept;
2289         }
2290         /**
2291          * Converts a hexadecimal string, even with negative sign as first string to
2292          * a decimal number using BC functions.
2293          *
2294          * This work is based on comment #86673 on php.net documentation page at:
2295          * <http://de.php.net/manual/en/function.dechex.php#86673>
2296          *
2297          * @param       $hex    Hexadecimal string
2298          * @return      $dec    Decimal number
2299          */
2300         protected function hex2dec ($hex) {
2301                 // Convert to all lower-case
2302                 $hex = strtolower($hex);
2303
2304                 // Detect sign (negative/positive numbers)
2305                 $sign = '';
2306                 if (substr($hex, 0, 1) == '-') {
2307                         $sign = '-';
2308                         $hex = substr($hex, 1);
2309                 } // END - if
2310
2311                 // Decode the hexadecimal string into a decimal number
2312                 $dec = 0;
2313                 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2314                         $factor = self::$hexdec[substr($hex, $i, 1)];
2315                         $dec = bcadd($dec, bcmul($factor, $e));
2316                 } // END - for
2317
2318                 // Return the decimal number
2319                 return $sign . $dec;
2320         }
2321
2322         /**
2323          * Converts even very large decimal numbers, also signed, to a hexadecimal
2324          * string.
2325          *
2326          * This work is based on comment #97756 on php.net documentation page at:
2327          * <http://de.php.net/manual/en/function.hexdec.php#97756>
2328          *
2329          * @param       $dec            Decimal number, even with negative sign
2330          * @param       $maxLength      Optional maximum length of the string
2331          * @return      $hex    Hexadecimal string
2332          */
2333         protected function dec2hex ($dec, $maxLength = 0) {
2334                 // maxLength can be zero or devideable by 2
2335                 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2336
2337                 // Detect sign (negative/positive numbers)
2338                 $sign = '';
2339                 if ($dec < 0) {
2340                         $sign = '-';
2341                         $dec = abs($dec);
2342                 } // END - if
2343
2344                 // Encode the decimal number into a hexadecimal string
2345                 $hex = '';
2346                 do {
2347                         $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2348                         $dec /= (2 ^ 4);
2349                 } while ($dec >= 1);
2350
2351                 /*
2352                  * Leading zeros are required for hex-decimal "numbers". In some
2353                  * situations more leading zeros are wanted, so check for both
2354                  * conditions.
2355                  */
2356                 if ($maxLength > 0) {
2357                         // Prepend more zeros
2358                         $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2359                 } elseif ((strlen($hex) % 2) != 0) {
2360                         // Only make string's length dividable by 2
2361                         $hex = '0' . $hex;
2362                 }
2363
2364                 // Return the hexadecimal string
2365                 return $sign . $hex;
2366         }
2367
2368         /**
2369          * Converts a ASCII string (0 to 255) into a decimal number.
2370          *
2371          * @param       $asc    The ASCII string to be converted
2372          * @return      $dec    Decimal number
2373          */
2374         protected function asc2dec ($asc) {
2375                 // Convert it into a hexadecimal number
2376                 $hex = bin2hex($asc);
2377
2378                 // And back into a decimal number
2379                 $dec = $this->hex2dec($hex);
2380
2381                 // Return it
2382                 return $dec;
2383         }
2384
2385         /**
2386          * Converts a decimal number into an ASCII string.
2387          *
2388          * @param       $dec            Decimal number
2389          * @return      $asc    An ASCII string
2390          */
2391         protected function dec2asc ($dec) {
2392                 // First convert the number into a hexadecimal string
2393                 $hex = $this->dec2hex($dec);
2394
2395                 // Then convert it into the ASCII string
2396                 $asc = $this->hex2asc($hex);
2397
2398                 // Return it
2399                 return $asc;
2400         }
2401
2402         /**
2403          * Converts a hexadecimal number into an ASCII string. Negative numbers
2404          * are not allowed.
2405          *
2406          * @param       $hex    Hexadecimal string
2407          * @return      $asc    An ASCII string
2408          */
2409         protected function hex2asc ($hex) {
2410                 // Check for length, it must be devideable by 2
2411                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2412                 assert((strlen($hex) % 2) == 0);
2413
2414                 // Walk the string
2415                 $asc = '';
2416                 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2417                         // Get the decimal number of the chunk
2418                         $part = hexdec(substr($hex, $idx, 2));
2419
2420                         // Add it to the final string
2421                         $asc .= chr($part);
2422                 } // END - for
2423
2424                 // Return the final string
2425                 return $asc;
2426         }
2427
2428         /**
2429          * Checks whether the given encoded data was encoded with Base64
2430          *
2431          * @param       $encodedData    Encoded data we shall check
2432          * @return      $isBase64               Whether the encoded data is Base64
2433          */
2434         protected function isBase64Encoded ($encodedData) {
2435                 // Determine it
2436                 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2437
2438                 // Return it
2439                 return $isBase64;
2440         }
2441
2442         /**
2443          * "Getter" to get response/request type from analysis of the system.
2444          *
2445          * @return      $responseType   Analyzed response type
2446          */
2447         protected static function getResponseTypeFromSystem () {
2448                 // Default is console
2449                 $responseType = 'console';
2450
2451                 // Is 'HTTP_HOST' set?
2452                 if (isset($_SERVER['HTTP_HOST'])) {
2453                         /*
2454                          * Then it is a HTML response/request as RSS and so on may be
2455                          * transfered over HTTP as well.
2456                          */
2457                         $responseType = 'html';
2458                 } // END - if
2459
2460                 // Return it
2461                 return $responseType;
2462         }
2463
2464         /**
2465          * Gets a cache key from Criteria instance
2466          *
2467          * @param       $criteriaInstance       An instance of a Criteria class
2468          * @param       $onlyKeys                       Only use these keys for a cache key
2469          * @return      $cacheKey                       A cache key suitable for lookup/storage purposes
2470          */
2471         protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2472                 // Generate it
2473                 $cacheKey = sprintf('%s@%s',
2474                         $this->__toString(),
2475                         $criteriaInstance->getCacheKey($onlyKeys)
2476                 );
2477
2478                 // And return it
2479                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2480                 return $cacheKey;
2481         }
2482
2483         /**
2484          * Getter for startup time in miliseconds
2485          *
2486          * @return      $startupTime    Startup time in miliseconds
2487          */
2488         protected function getStartupTime () {
2489                 return self::$startupTime;
2490         }
2491
2492         /**
2493          * "Getter" for a printable currently execution time in nice braces
2494          *
2495          * @return      $executionTime  Current execution time in nice braces
2496          */
2497         protected function getPrintableExecutionTime () {
2498                 // Caculate the execution time
2499                 $executionTime = microtime(TRUE) - $this->getStartupTime();
2500
2501                 // Pack it in nice braces
2502                 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2503
2504                 // And return it
2505                 return $executionTime;
2506         }
2507
2508         /**
2509          * Hashes a given string with a simple but stronger hash function (no salt)
2510          * and hex-encode it.
2511          *
2512          * @param       $str    The string to be hashed
2513          * @return      $hash   The hash from string $str
2514          */
2515         public static final function hash ($str) {
2516                 // Hash given string with (better secure) hasher
2517                 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2518
2519                 // Return it
2520                 return $hash;
2521         }
2522
2523         /**
2524          * "Getter" for length of hash() output. This will be "cached" to speed up
2525          * things.
2526          *
2527          * @return      $length         Length of hash() output
2528          */
2529         public static final function getHashLength () {
2530                 // Is it cashed?
2531                 if (is_null(self::$hashLength)) {
2532                         // No, then hash a string and save its length.
2533                         self::$hashLength = strlen(self::hash('abc123'));
2534                 } // END - if
2535
2536                 // Return it
2537                 return self::$hashLength;
2538         }
2539
2540         /**
2541          * Checks whether the given number is really a number (only chars 0-9).
2542          *
2543          * @param       $num            A string consisting only chars between 0 and 9
2544          * @param       $castValue      Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2545          * @param       $assertMismatch         Whether to assert mismatches
2546          * @return      $ret            The (hopefully) secured numbered value
2547          */
2548         public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2549                 // Filter all numbers out
2550                 $ret = preg_replace('/[^0123456789]/', '', $num);
2551
2552                 // Shall we cast?
2553                 if ($castValue === TRUE) {
2554                         // Cast to biggest numeric type
2555                         $ret = (double) $ret;
2556                 } // END - if
2557
2558                 // Assert only if requested
2559                 if ($assertMismatch === TRUE) {
2560                         // Has the whole value changed?
2561                         assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2562                 } // END - if
2563
2564                 // Return result
2565                 return $ret;
2566         }
2567
2568         /**
2569          * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2570          *
2571          * @param       $num    A string consisting only chars between 0 and 9
2572          * @param       $assertMismatch         Whether to assert mismatches
2573          * @return      $ret    The (hopefully) secured hext-numbered value
2574          */
2575         public function hexval ($num, $assertMismatch = FALSE) {
2576                 // Filter all numbers out
2577                 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2578
2579                 // Assert only if requested
2580                 if ($assertMismatch === TRUE) {
2581                         // Has the whole value changed?
2582                         assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2583                 } // END - if
2584
2585                 // Return result
2586                 return $ret;
2587         }
2588
2589         /**
2590          * Checks whether start/end marker are set
2591          *
2592          * @param       $data   Data to be checked
2593          * @return      $isset  Whether start/end marker are set
2594          */
2595         public final function ifStartEndMarkersSet ($data) {
2596                 // Determine it
2597                 $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));
2598
2599                 // ... and return it
2600                 return $isset;
2601         }
2602
2603         /**
2604          * Determines if an element is set in the generic array
2605          *
2606          * @param       $keyGroup       Main group for the key
2607          * @param       $subGroup       Sub group for the key
2608          * @param       $key            Key to check
2609          * @param       $element        Element to check
2610          * @return      $isset          Whether the given key is set
2611          */
2612         protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2613                 // Debug message
2614                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2615
2616                 // Is it there?
2617                 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2618
2619                 // Return it
2620                 return $isset;
2621         }
2622         /**
2623          * Determines if a key is set in the generic array
2624          *
2625          * @param       $keyGroup       Main group for the key
2626          * @param       $subGroup       Sub group for the key
2627          * @param       $key            Key to check
2628          * @return      $isset          Whether the given key is set
2629          */
2630         protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2631                 // Debug message
2632                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2633
2634                 // Is it there?
2635                 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2636
2637                 // Return it
2638                 return $isset;
2639         }
2640
2641
2642         /**
2643          * Determines if a group is set in the generic array
2644          *
2645          * @param       $keyGroup       Main group
2646          * @param       $subGroup       Sub group
2647          * @return      $isset          Whether the given group is set
2648          */
2649         protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2650                 // Debug message
2651                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2652
2653                 // Is it there?
2654                 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2655
2656                 // Return it
2657                 return $isset;
2658         }
2659
2660         /**
2661          * Getter for sub key group
2662          *
2663          * @param       $keyGroup       Main key group
2664          * @param       $subGroup       Sub key group
2665          * @return      $array          An array with all array elements
2666          */
2667         protected final function getGenericSubArray ($keyGroup, $subGroup) {
2668                 // Is it there?
2669                 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2670                         // No, then abort here
2671                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2672                         exit;
2673                 } // END - if
2674
2675                 // Debug message
2676                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2677
2678                 // Return it
2679                 return $this->genericArray[$keyGroup][$subGroup];
2680         }
2681
2682         /**
2683          * Unsets a given key in generic array
2684          *
2685          * @param       $keyGroup       Main group for the key
2686          * @param       $subGroup       Sub group for the key
2687          * @param       $key            Key to unset
2688          * @return      void
2689          */
2690         protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2691                 // Debug message
2692                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2693
2694                 // Remove it
2695                 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2696         }
2697
2698         /**
2699          * Unsets a given element in generic array
2700          *
2701          * @param       $keyGroup       Main group for the key
2702          * @param       $subGroup       Sub group for the key
2703          * @param       $key            Key to unset
2704          * @param       $element        Element to unset
2705          * @return      void
2706          */
2707         protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2708                 // Debug message
2709                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2710
2711                 // Remove it
2712                 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2713         }
2714
2715         /**
2716          * Append a string to a given generic array key
2717          *
2718          * @param       $keyGroup       Main group for the key
2719          * @param       $subGroup       Sub group for the key
2720          * @param       $key            Key to unset
2721          * @param       $value          Value to add/append
2722          * @return      void
2723          */
2724         protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2725                 // Debug message
2726                 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE) . ',appendGlue=' . $appendGlue);
2727
2728                 // Is it already there?
2729                 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2730                         // Append it
2731                         $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2732                 } else {
2733                         // Add it
2734                         $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2735                 }
2736         }
2737
2738         /**
2739          * Append a string to a given generic array element
2740          *
2741          * @param       $keyGroup       Main group for the key
2742          * @param       $subGroup       Sub group for the key
2743          * @param       $key            Key to unset
2744          * @param       $element        Element to check
2745          * @param       $value          Value to add/append
2746          * @return      void
2747          */
2748         protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2749                 // Debug message
2750                 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, TRUE) . ',appendGlue=' . $appendGlue);
2751
2752                 // Is it already there?
2753                 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2754                         // Append it
2755                         $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2756                 } else {
2757                         // Add it
2758                         $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2759                 }
2760         }
2761
2762         /**
2763          * Initializes given generic array group
2764          *
2765          * @param       $keyGroup       Main group for the key
2766          * @param       $subGroup       Sub group for the key
2767          * @param       $key            Key to use
2768          * @param       $forceInit      Optionally force initialization
2769          * @return      void
2770          */
2771         protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2772                 // Debug message
2773                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2774
2775                 // Is it already set?
2776                 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2777                         // Already initialized
2778                         trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2779                         exit;
2780                 } // END - if
2781
2782                 // Initialize it
2783                 $this->genericArray[$keyGroup][$subGroup] = array();
2784         }
2785
2786         /**
2787          * Initializes given generic array key
2788          *
2789          * @param       $keyGroup       Main group for the key
2790          * @param       $subGroup       Sub group for the key
2791          * @param       $key            Key to use
2792          * @param       $forceInit      Optionally force initialization
2793          * @return      void
2794          */
2795         protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2796                 // Debug message
2797                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2798
2799                 // Is it already set?
2800                 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2801                         // Already initialized
2802                         trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2803                         exit;
2804                 } // END - if
2805
2806                 // Initialize it
2807                 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2808         }
2809
2810         /**
2811          * Initializes given generic array element
2812          *
2813          * @param       $keyGroup       Main group for the key
2814          * @param       $subGroup       Sub group for the key
2815          * @param       $key            Key to use
2816          * @param       $element        Element to use
2817          * @param       $forceInit      Optionally force initialization
2818          * @return      void
2819          */
2820         protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2821                 // Debug message
2822                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2823
2824                 // Is it already set?
2825                 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2826                         // Already initialized
2827                         trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2828                         exit;
2829                 } // END - if
2830
2831                 // Initialize it
2832                 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2833         }
2834
2835         /**
2836          * Pushes an element to a generic key
2837          *
2838          * @param       $keyGroup       Main group for the key
2839          * @param       $subGroup       Sub group for the key
2840          * @param       $key            Key to use
2841          * @param       $value          Value to add/append
2842          * @return      $count          Number of array elements
2843          */
2844         protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2845                 // Debug message
2846                 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2847
2848                 // Is it set?
2849                 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2850                         // Initialize array
2851                         $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2852                 } // END - if
2853
2854                 // Then push it
2855                 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2856
2857                 // Return count
2858                 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2859                 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2860                 return $count;
2861         }
2862
2863         /**
2864          * Pushes an element to a generic array element
2865          *
2866          * @param       $keyGroup       Main group for the key
2867          * @param       $subGroup       Sub group for the key
2868          * @param       $key            Key to use
2869          * @param       $element        Element to check
2870          * @param       $value          Value to add/append
2871          * @return      $count          Number of array elements
2872          */
2873         protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2874                 // Debug message
2875                 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2876
2877                 // Is it set?
2878                 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2879                         // Initialize array
2880                         $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2881                 } // END - if
2882
2883                 // Then push it
2884                 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2885
2886                 // Return count
2887                 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2888                 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2889                 return $count;
2890         }
2891
2892         /**
2893          * Pops an element from  a generic group
2894          *
2895          * @param       $keyGroup       Main group for the key
2896          * @param       $subGroup       Sub group for the key
2897          * @param       $key            Key to unset
2898          * @return      $value          Last "popped" value
2899          */
2900         protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2901                 // Debug message
2902                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2903
2904                 // Is it set?
2905                 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2906                         // Not found
2907                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2908                         exit;
2909                 } // END - if
2910
2911                 // Then "pop" it
2912                 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2913
2914                 // Return value
2915                 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2916                 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2917                 return $value;
2918         }
2919
2920         /**
2921          * Shifts an element from  a generic group
2922          *
2923          * @param       $keyGroup       Main group for the key
2924          * @param       $subGroup       Sub group for the key
2925          * @param       $key            Key to unset
2926          * @return      $value          Last "popped" value
2927          */
2928         protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2929                 // Debug message
2930                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2931
2932                 // Is it set?
2933                 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2934                         // Not found
2935                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2936                         exit;
2937                 } // END - if
2938
2939                 // Then "shift" it
2940                 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2941
2942                 // Return value
2943                 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2944                 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2945                 return $value;
2946         }
2947
2948         /**
2949          * Count generic array group
2950          *
2951          * @param       $keyGroup       Main group for the key
2952          * @return      $count          Count of given group
2953          */
2954         protected final function countGenericArray ($keyGroup) {
2955                 // Debug message
2956                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2957
2958                 // Is it there?
2959                 if (!isset($this->genericArray[$keyGroup])) {
2960                         // Abort here
2961                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2962                         exit;
2963                 } // END - if
2964
2965                 // Then count it
2966                 $count = count($this->genericArray[$keyGroup]);
2967
2968                 // Debug message
2969                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2970
2971                 // Return it
2972                 return $count;
2973         }
2974
2975         /**
2976          * Count generic array sub group
2977          *
2978          * @param       $keyGroup       Main group for the key
2979          * @param       $subGroup       Sub group for the key
2980          * @return      $count          Count of given group
2981          */
2982         protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2983                 // Debug message
2984                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2985
2986                 // Is it there?
2987                 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2988                         // Abort here
2989                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2990                         exit;
2991                 } // END - if
2992
2993                 // Then count it
2994                 $count = count($this->genericArray[$keyGroup][$subGroup]);
2995
2996                 // Debug message
2997                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2998
2999                 // Return it
3000                 return $count;
3001         }
3002
3003         /**
3004          * Count generic array elements
3005          *
3006          * @param       $keyGroup       Main group for the key
3007          * @param       $subGroup       Sub group for the key
3008          * @para        $key            Key to count
3009          * @return      $count          Count of given key
3010          */
3011         protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3012                 // Debug message
3013                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3014
3015                 // Is it there?
3016                 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3017                         // Abort here
3018                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3019                         exit;
3020                 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3021                         // Not valid
3022                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3023                         exit;
3024                 }
3025
3026                 // Then count it
3027                 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3028
3029                 // Debug message
3030                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3031
3032                 // Return it
3033                 return $count;
3034         }
3035
3036         /**
3037          * Getter for whole generic group array
3038          *
3039          * @param       $keyGroup       Key group to get
3040          * @return      $array          Whole generic array group
3041          */
3042         protected final function getGenericArray ($keyGroup) {
3043                 // Debug message
3044                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3045
3046                 // Is it there?
3047                 if (!isset($this->genericArray[$keyGroup])) {
3048                         // Then abort here
3049                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3050                         exit;
3051                 } // END - if
3052
3053                 // Return it
3054                 return $this->genericArray[$keyGroup];
3055         }
3056
3057         /**
3058          * Setter for generic array key
3059          *
3060          * @param       $keyGroup       Key group to get
3061          * @param       $subGroup       Sub group for the key
3062          * @param       $key            Key to unset
3063          * @param       $value          Mixed value from generic array element
3064          * @return      void
3065          */
3066         protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3067                 // Debug message
3068                 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3069
3070                 // Set value here
3071                 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3072         }
3073
3074         /**
3075          * Getter for generic array key
3076          *
3077          * @param       $keyGroup       Key group to get
3078          * @param       $subGroup       Sub group for the key
3079          * @param       $key            Key to unset
3080          * @return      $value          Mixed value from generic array element
3081          */
3082         protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3083                 // Debug message
3084                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3085
3086                 // Is it there?
3087                 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3088                         // Then abort here
3089                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3090                         exit;
3091                 } // END - if
3092
3093                 // Return it
3094                 return $this->genericArray[$keyGroup][$subGroup][$key];
3095         }
3096
3097         /**
3098          * Sets a value in given generic array key/element
3099          *
3100          * @param       $keyGroup       Main group for the key
3101          * @param       $subGroup       Sub group for the key
3102          * @param       $key            Key to set
3103          * @param       $element        Element to set
3104          * @param       $value          Value to set
3105          * @return      void
3106          */
3107         protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3108                 // Debug message
3109                 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3110
3111                 // Then set it
3112                 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3113         }
3114
3115         /**
3116          * Getter for generic array element
3117          *
3118          * @param       $keyGroup       Key group to get
3119          * @param       $subGroup       Sub group for the key
3120          * @param       $key            Key to look for
3121          * @param       $element        Element to look for
3122          * @return      $value          Mixed value from generic array element
3123          */
3124         protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3125                 // Debug message
3126                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3127
3128                 // Is it there?
3129                 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3130                         // Then abort here
3131                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3132                         exit;
3133                 } // END - if
3134
3135                 // Return it
3136                 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3137         }
3138
3139         /**
3140          * Checks if a given sub group is valid (array)
3141          *
3142          * @param       $keyGroup       Key group to get
3143          * @param       $subGroup       Sub group for the key
3144          * @return      $isValid        Whether given sub group is valid
3145          */
3146         protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3147                 // Debug message
3148                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3149
3150                 // Determine it
3151                 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3152
3153                 // Return it
3154                 return $isValid;
3155         }
3156
3157         /**
3158          * Checks if a given key is valid (array)
3159          *
3160          * @param       $keyGroup       Key group to get
3161          * @param       $subGroup       Sub group for the key
3162          * @param       $key            Key to check
3163          * @return      $isValid        Whether given sub group is valid
3164          */
3165         protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3166                 // Debug message
3167                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3168
3169                 // Determine it
3170                 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3171
3172                 // Return it
3173                 return $isValid;
3174         }
3175
3176         /**
3177          * Initializes the web output instance
3178          *
3179          * @return      void
3180          */
3181         protected function initWebOutputInstance () {
3182                 // Get application instance
3183                 $applicationInstance = Registry::getRegistry()->getInstance('app');
3184
3185                 // Is this a response instance?
3186                 if ($this instanceof Responseable) {
3187                         // Then set it in application instance
3188                         $applicationInstance->setResponseInstance($this);
3189                 } // END - if
3190
3191                 // Init web output instance
3192                 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3193
3194                 // Set it locally
3195                 $this->setWebOutputInstance($outputInstance);
3196         }
3197
3198         /**
3199          * Translates boolean TRUE to 'Y' and FALSE to 'N'
3200          *
3201          * @param       $boolean                Boolean value
3202          * @return      $translated             Translated boolean value
3203          */
3204         public static final function translateBooleanToYesNo ($boolean) {
3205                 // Make sure it is really boolean
3206                 assert(is_bool($boolean));
3207
3208                 // "Translate" it
3209                 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3210
3211                 // ... and return it
3212                 return $translated;
3213         }
3214
3215         /**
3216          * Encodes raw data (almost any type) by "serializing" it and then pack it
3217          * into a "binary format".
3218          *
3219          * @param       $rawData        Raw data (almost any type)
3220          * @return      $encoded        Encoded data
3221          */
3222         protected function encodeData ($rawData) {
3223                 // Make sure no objects or resources pass through
3224                 assert(!is_object($rawData));
3225                 assert(!is_resource($rawData));
3226
3227                 // First "serialize" it (json_encode() is faster than serialize())
3228                 $encoded = $this->packString(json_encode($rawData));
3229
3230                 // And return it
3231                 return $encoded;
3232         }
3233
3234         /**
3235          * Pack a string into a "binary format". Please execuse me that this is
3236          * widely undocumented. :-(
3237          *
3238          * @param       $str            Unpacked string
3239          * @return      $packed         Packed string
3240          * @todo        Improve documentation
3241          */
3242         protected function packString ($str) {
3243                 // Debug message
3244                 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3245
3246                 // First compress the string (gzcompress is okay)
3247                 $str = gzcompress($str);
3248
3249                 // Init variable
3250                 $packed = '';
3251
3252                 // And start the "encoding" loop
3253                 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3254                         $big = 0;
3255                         for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3256                                 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3257
3258                                 if (($idx + $i) <= strlen($str)) {
3259                                         $ord = ord(substr($str, ($idx + $i), 1));
3260
3261                                         $add = $ord * pow(256, $factor);
3262
3263                                         $big += $add;
3264
3265                                         //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3266                                 } // END - if
3267                         } // END - for
3268
3269                         $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3270                         $r = $big & $this->packingData[$this->archArrayElement]['right'];
3271
3272                         $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3273                         //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3274
3275                         $packed .= $chunk;
3276                 } // END - for
3277
3278                 // Return it
3279                 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');
3280                 return $packed;
3281         }
3282
3283         /**
3284          * Checks whether the given file/path is in open_basedir(). This does not
3285          * gurantee that the file is actually readable and/or writeable. If you need
3286          * such gurantee then please use isReadableFile() instead.
3287          *
3288          * @param       $filePathName   Name of the file/path to be checked
3289          * @return      $isReachable    Whether it is within open_basedir()
3290          */
3291         public static function isReachableFilePath ($filePathName) {
3292                 // Is not reachable by default
3293                 $isReachable = FALSE;
3294
3295                 // Get open_basedir parameter
3296                 $openBaseDir = ini_get('open_basedir');
3297
3298                 // Is it set?
3299                 if (!empty($openBaseDir)) {
3300                         // Check all entries
3301                         foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3302                                 // Check on existence
3303                                 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3304                                         // Is reachable
3305                                         $isReachable = TRUE;
3306                                 } // END - if
3307                         } // END - foreach
3308                 } else {
3309                         // If open_basedir is not set, all is allowed
3310                         $isReachable = TRUE;
3311                 }
3312
3313                 // Return status
3314                 return $isReachable;
3315         }
3316
3317         /**
3318          * Checks whether the give file is within open_basedir() (done by
3319          * isReachableFilePath()), is actually a file and is readable.
3320          *
3321          * @param       $fileName               Name of the file to be checked
3322          * @return      $isReadable             Whether the file is readable (and therefor exists)
3323          */
3324         public static function isReadableFile ($fileName) {
3325                 // Default is not readable
3326                 $isReadable = FALSE;
3327
3328                 // Is within parameters, so check if it is a file and readable
3329                 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3330
3331                 // Return status
3332                 return $isReadable;
3333         }
3334 }
3335
3336 // [EOF]
3337 ?>