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