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