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