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