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