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