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