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