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