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