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