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