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