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