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