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