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