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