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