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