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