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