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