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