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