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