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