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