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