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