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