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