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