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