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