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