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