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