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