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