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