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