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