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