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