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