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