]> git.mxchange.org Git - core.git/blob - framework/main/classes/class_BaseFrameworkSystem.php
Refacuring:
[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\Criteria\Criteria;
8 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
9 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
10 use Org\Mxchange\CoreFramework\Filesystem\PathWriteProtectedException;
11 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
12 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
13 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
14 use Org\Mxchange\CoreFramework\Loader\ClassLoader;
15 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
16 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
17 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
18 use Org\Mxchange\CoreFramework\Result\Database\CachedDatabaseResult;
19 use Org\Mxchange\CoreFramework\State\Stateable;
20 use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
21 use Org\Mxchange\CoreFramework\Utils\String\StringUtils;
22
23 // Import SPL stuff
24 use \stdClass;
25 use \InvalidArgumentException;
26 use \ReflectionClass;
27 use \SplFileInfo;
28
29 /**
30  * The simulator system class is the super class of all other classes. This
31  * class handles saving of games etc.
32  *
33  * @author              Roland Haeder <webmaster@shipsimu.org>
34  * @version             0.0.0
35  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
36  * @license             GNU GPL 3.0 or any newer version
37  * @link                http://www.shipsimu.org
38  *
39  * This program is free software: you can redistribute it and/or modify
40  * it under the terms of the GNU General Public License as published by
41  * the Free Software Foundation, either version 3 of the License, or
42  * (at your option) any later version.
43  *
44  * This program is distributed in the hope that it will be useful,
45  * but WITHOUT ANY WARRANTY; without even the implied warranty of
46  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
47  * GNU General Public License for more details.
48  *
49  * You should have received a copy of the GNU General Public License
50  * along with this program. If not, see <http://www.gnu.org/licenses/>.
51  */
52 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
53         /**
54          * Length of output from hash()
55          */
56         private static $hashLength = NULL;
57
58         /**
59          * Self-referencing instance
60          */
61         private static $selfInstance = NULL;
62
63         /**
64          * The real class name
65          */
66         private $realClass = __CLASS__;
67
68         /**
69          * Call-back instance
70          */
71         private $callbackInstance = NULL;
72
73         /**
74          * Generic array
75          */
76         private $genericArray = [];
77
78         /***********************
79          * Exception codes.... *
80          ***********************/
81
82         // @todo Try to clean these constants up
83         const EXCEPTION_IS_NULL_POINTER              = 0x001;
84         const EXCEPTION_IS_NO_OBJECT                 = 0x002;
85         const EXCEPTION_IS_NO_ARRAY                  = 0x003;
86         const EXCEPTION_MISSING_METHOD               = 0x004;
87         const EXCEPTION_CLASSES_NOT_MATCHING         = 0x005;
88         const EXCEPTION_INDEX_OUT_OF_BOUNDS          = 0x006;
89         const EXCEPTION_DIMENSION_ARRAY_INVALID      = 0x007;
90         const EXCEPTION_ITEM_NOT_TRADEABLE           = 0x008;
91         const EXCEPTION_ITEM_NOT_IN_PRICE_LIST       = 0x009;
92         const EXCEPTION_GENDER_IS_WRONG              = 0x00a;
93         const EXCEPTION_BIRTH_DATE_IS_INVALID        = 0x00b;
94         const EXCEPTION_EMPTY_STRUCTURES_ARRAY       = 0x00c;
95         const EXCEPTION_HAS_ALREADY_PERSONELL_LIST   = 0x00d;
96         const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES      = 0x00e;
97         const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED   = 0x00f;
98         const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS      = 0x010;
99         const EXCEPTION_CONTRACT_PARTNER_INVALID     = 0x011;
100         const EXCEPTION_CONTRACT_PARTNER_MISMATCH    = 0x012;
101         const EXCEPTION_CONTRACT_ALREADY_SIGNED      = 0x013;
102         const EXCEPTION_UNEXPECTED_EMPTY_STRING      = 0x014;
103         const EXCEPTION_PATH_NOT_FOUND               = 0x015;
104         const EXCEPTION_INVALID_PATH_NAME            = 0x016;
105         const EXCEPTION_READ_PROTECED_PATH           = 0x017;
106         const EXCEPTION_WRITE_PROTECED_PATH          = 0x018;
107         const EXCEPTION_DIR_POINTER_INVALID          = 0x019;
108         const EXCEPTION_FILE_POINTER_INVALID         = 0x01a;
109         const EXCEPTION_INVALID_RESOURCE             = 0x01b;
110         const EXCEPTION_UNEXPECTED_OBJECT            = 0x01c;
111         const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
112         const EXCEPTION_GETTER_IS_MISSING            = 0x01e;
113         const EXCEPTION_ARRAY_EXPECTED               = 0x01f;
114         const EXCEPTION_ARRAY_HAS_INVALID_COUNT      = 0x020;
115         const EXCEPTION_ID_IS_INVALID_FORMAT         = 0x021;
116         const EXCEPTION_MD5_CHECKSUMS_MISMATCH       = 0x022;
117         const EXCEPTION_UNEXPECTED_STRING_SIZE       = 0x023;
118         const EXCEPTION_SIMULATOR_ID_INVALID         = 0x024;
119         const EXCEPTION_MISMATCHING_COMPRESSORS      = 0x025;
120         const EXCEPTION_CONTAINER_ITEM_IS_NULL       = 0x026;
121         const EXCEPTION_ITEM_IS_NO_ARRAY             = 0x027;
122         const EXCEPTION_CONTAINER_MAYBE_DAMAGED      = 0x028;
123         const EXCEPTION_INVALID_STRING               = 0x029;
124         const EXCEPTION_VARIABLE_NOT_SET             = 0x02a;
125         const EXCEPTION_ATTRIBUTES_ARE_MISSING       = 0x02b;
126         const EXCEPTION_ARRAY_ELEMENTS_MISSING       = 0x02c;
127         const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED  = 0x02d;
128         const EXCEPTION_UNSPPORTED_OPERATION         = 0x02e;
129         const EXCEPTION_FACTORY_REQUIRE_PARAMETER    = 0x02f;
130         const EXCEPTION_MISSING_ELEMENT              = 0x030;
131         const EXCEPTION_HEADERS_ALREADY_SENT         = 0x031;
132         const EXCEPTION_DEFAULT_CONTROLLER_GONE      = 0x032;
133         const EXCEPTION_CLASS_NOT_FOUND              = 0x033;
134         const EXCEPTION_REQUIRED_INTERFACE_MISSING   = 0x034;
135         const EXCEPTION_FATAL_ERROR                  = 0x035;
136         const EXCEPTION_FILE_NOT_FOUND               = 0x036;
137         const EXCEPTION_ASSERTION_FAILED             = 0x037;
138         const EXCEPTION_FILE_NOT_REACHABLE           = 0x038;
139         const EXCEPTION_FILE_CANNOT_BE_READ          = 0x039;
140         const EXCEPTION_FILE_CANNOT_BE_WRITTEN       = 0x03a;
141         const EXCEPTION_PATH_CANNOT_BE_WRITTEN       = 0x03b;
142         const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
143         const EXCEPTION_FILTER_CHAIN_INTERCEPTED     = 0x03d;
144         const EXCEPTION_INVALID_SOCKET               = 0x03e;
145         const EXCEPTION_SELF_INSTANCE                = 0x03f;
146
147         /**
148          * Startup time in miliseconds
149          */
150         private static $startupTime = 0;
151
152         /**
153          * Protected super constructor
154          *
155          * @param       $className      Name of the class
156          * @return      void
157          */
158         protected function __construct (string $className) {
159                 // Set real class
160                 $this->setRealClass($className);
161
162                 // Is the startup time set? (0 cannot be true anymore)
163                 if (self::$startupTime == 0) {
164                         // Then set it
165                         self::$startupTime = microtime(true);
166                 }
167         }
168
169         /**
170          * Destructor for all classes. You should not call this method on your own.
171          *
172          * @return      void
173          */
174         public function __destruct () {
175                 // Is this object already destroyed?
176                 if ($this->__toString() != 'DestructedObject') {
177                         // Destroy all informations about this class but keep some text about it alive
178                         $this->setRealClass('DestructedObject');
179                 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
180                         // Already destructed object
181                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
182                                 $this->__toString()
183                         ));
184                 } else {
185                         // Do not call this twice
186                         trigger_error(__METHOD__ . ': Called twice.');
187                         exit;
188                 }
189         }
190
191         /**
192          * The __call() method where all non-implemented methods end up
193          *
194          * @param       $methodName             Name of the missing method
195          * @args        $args                   Arguments passed to the method
196          * @return      void
197          */
198         public final function __call (string $methodName, array $args = NULL) {
199                 // Set self-instance
200                 self::$selfInstance = $this;
201
202                 // Call static method
203                 self::__callStatic($methodName, $args);
204
205                 // Clear self-instance
206                 self::$selfInstance = NULL;
207         }
208
209         /**
210          * The __callStatic() method where all non-implemented static methods end up
211          *
212          * @param       $methodName             Name of the missing method
213          * @param       $args                   Arguments passed to the method
214          * @return      void
215          * @throws      InvalidArgumentException If self::$selfInstance is not a framework's own object
216          */
217         public static final function __callStatic (string $methodName, array $args = NULL) {
218                 // Init argument string and class name
219                 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
220                 $argsString = '';
221                 $className = 'unknown';
222
223                 // Is self-instance set?
224                 if (self::$selfInstance instanceof FrameworkInterface) {
225                         // Framework's own instance
226                         $className = self::$selfInstance->__toString();
227                 } elseif (!is_null(self::$selfInstance)) {
228                         // Invalid argument!
229                         throw new InvalidArgumentException(sprintf('self::instance[%s] is not expected.', gettype(self::$selfInstance)), self::EXCEPTION_SELF_INSTANCE);
230                 }
231
232                 // Is it NULL, empty or an array?
233                 if (is_null($args)) {
234                         // No arguments
235                         $argsString = 'NULL';
236                 } elseif (is_array($args)) {
237                         // Start braces
238                         $argsString = '(';
239
240                         // Some arguments are there
241                         foreach ($args as $arg) {
242                                 // Add data about the argument
243                                 $argsString .= gettype($arg) . ':';
244
245                                 if (is_null($arg)) {
246                                         // Found a NULL argument
247                                         $argsString .= 'NULL';
248                                 } elseif (is_string($arg)) {
249                                         // Add length for strings
250                                         $argsString .= strlen($arg);
251                                 } elseif ((is_int($arg)) || (is_float($arg))) {
252                                         // ... integer/float
253                                         $argsString .= $arg;
254                                 } elseif (is_array($arg)) {
255                                         // .. or size if array
256                                         $argsString .= count($arg);
257                                 } elseif (is_object($arg)) {
258                                         // Get reflection
259                                         $reflection = new ReflectionClass($arg);
260
261                                         // Is an other object, maybe no __toString() available
262                                         $argsString .= $reflection->getName();
263                                 } elseif ($arg === true) {
264                                         // ... is boolean 'true'
265                                         $argsString .= 'true';
266                                 } elseif ($arg === false) {
267                                         // ... is boolean 'false'
268                                         $argsString .= 'false';
269                                 }
270
271                                 // Comma for next one
272                                 $argsString .= ', ';
273                         }
274
275                         // Last comma found?
276                         if (substr($argsString, -2, 1) == ',') {
277                                 // Remove last comma
278                                 $argsString = substr($argsString, 0, -2);
279                         }
280
281                         // Close braces
282                         $argsString .= ')';
283                 }
284
285                 // Output stub message
286                 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
287                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s::%s]: Stub! Args: %s',
288                         $className,
289                         $methodName,
290                         $argsString
291                 ));
292
293                 // Return nothing
294                 return NULL;
295         }
296
297         /**
298          * Getter for $realClass
299          *
300          * @return      $realClass The name of the real class (not BaseFrameworkSystem)
301          */
302         public function __toString () {
303                 return $this->realClass;
304         }
305
306         /**
307          * Magic method to catch setting of missing but set class fields/attributes
308          *
309          * @param       $name   Name of the field/attribute
310          * @param       $value  Value to store
311          * @return      void
312          */
313         public final function __set (string $name, $value) {
314                 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
315                         $name,
316                         gettype($value),
317                         print_r($value, true)
318                 ));
319         }
320
321         /**
322          * Magic method to catch getting of missing fields/attributes
323          *
324          * @param       $name   Name of the field/attribute
325          * @return      void
326          */
327         public final function __get (string $name) {
328                 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
329                         $name
330                 ));
331         }
332
333         /**
334          * Magic method to catch unsetting of missing fields/attributes
335          *
336          * @param       $name   Name of the field/attribute
337          * @return      void
338          */
339         public final function __unset (string $name) {
340                 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
341                         $name
342                 ));
343         }
344
345         /**
346          * Magic method to catch object serialization
347          *
348          * @return      $unsupported    Unsupported method
349          * @throws      UnsupportedOperationException   Objects of this framework cannot be serialized
350          */
351         public final function __sleep () {
352                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
353         }
354
355         /**
356          * Magic method to catch object deserialization
357          *
358          * @return      $unsupported    Unsupported method
359          * @throws      UnsupportedOperationException   Objects of this framework cannot be serialized
360          */
361         public final function __wakeup () {
362                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
363         }
364
365         /**
366          * Magic method to catch calls when an object instance is called
367          *
368          * @return      $unsupported    Unsupported method
369          * @throws      UnsupportedOperationException   Objects of this framework cannot be serialized
370          */
371         public final function __invoke () {
372                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
373         }
374
375         /**
376          * Setter for the real class name
377          *
378          * @param       $realClass      Class name (string)
379          * @return      void
380          */
381         public final function setRealClass (string $realClass) {
382                 // Set real class
383                 $this->realClass = $realClass;
384         }
385
386         /**
387          * Setter for debug instance
388          *
389          * @param       $debugInstance  The instance for debug output class
390          * @return      void
391          */
392         public final function setDebugInstance (DebugMiddleware $debugInstance) {
393                 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
394         }
395
396         /**
397          * Getter for debug instance
398          *
399          * @return      $debugInstance  Instance to class DebugConsoleOutput or DebugWebOutput
400          */
401         public final function getDebugInstance () {
402                 // Get debug instance
403                 $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
404
405                 // Return it
406                 return $debugInstance;
407         }
408
409         /**
410          * Setter for web output instance
411          *
412          * @param       $webInstance    The instance for web output class
413          * @return      void
414          */
415         public final function setWebOutputInstance (OutputStreamer $webInstance) {
416                 GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
417         }
418
419         /**
420          * Getter for web output instance
421          *
422          * @return      $webOutputInstance - Instance to class WebOutput
423          */
424         public final function getWebOutputInstance () {
425                 $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
426                 return $webOutputInstance;
427         }
428
429         /**
430          * Getter for state instance
431          *
432          * @return      $stateInstance  A Stateable instance
433          */
434         public final function getStateInstance () {
435                 return $this->stateInstance;
436         }
437
438         /**
439          * Setter for call-back instance
440          *
441          * @param       $callbackInstance       An instance of a FrameworkInterface class
442          * @return      void
443          */
444         public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
445                 $this->callbackInstance = $callbackInstance;
446         }
447
448         /**
449          * Getter for call-back instance
450          *
451          * @return      $callbackInstance       An instance of a FrameworkInterface class
452          */
453         protected final function getCallbackInstance () {
454                 return $this->callbackInstance;
455         }
456
457         /**
458          * Checks whether an object equals this object. You should overwrite this
459          * method to implement own equality checks
460          *
461          * @param       $objectInstance         An instance of a FrameworkInterface object
462          * @return      $equals                         Whether both objects equals
463          */
464         public function equals (FrameworkInterface $objectInstance) {
465                 // Now test it
466                 $equals = ((
467                         $this->__toString() == $objectInstance->__toString()
468                 ) && (
469                         $this->hashCode() == $objectInstance->hashCode()
470                 ));
471
472                 // Return the result
473                 return $equals;
474         }
475
476         /**
477          * Generates a generic hash code of this class. You should really overwrite
478          * this method with your own hash code generator code. But keep KISS in mind.
479          *
480          * @return      $hashCode       A generic hash code respresenting this whole class
481          */
482         public function hashCode () {
483                 // Simple hash code
484                 return crc32($this->__toString());
485         }
486
487         /**
488          * Appends a trailing slash to a string
489          *
490          * @param       $str    A string (maybe) without trailing slash
491          * @return      $str    A string with an auto-appended trailing slash
492          */
493         public final function addMissingTrailingSlash ($str) {
494                 // Is there a trailing slash?
495                 if (substr($str, -1, 1) != '/') {
496                         $str .= '/';
497                 }
498
499                 // Return string with trailing slash
500                 return $str;
501         }
502
503         /**
504          * Debugs this instance by putting out it's full content
505          *
506          * @param       $message        Optional message to show in debug output
507          * @return      void
508          */
509         public final function debugInstance ($message = '') {
510                 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
511                 restore_error_handler();
512
513                 // Init content
514                 $content = '';
515
516                 // Is a message set?
517                 if (!empty($message)) {
518                         // Construct message
519                         $content = sprintf('<div class="debug_message">
520         Message: %s
521 </div>' . PHP_EOL, $message);
522                 }
523
524                 // Generate the output
525                 $content .= sprintf('<pre>%s</pre>',
526                         trim(
527                                 htmlentities(
528                                         print_r($this, true)
529                                 )
530                         )
531                 );
532
533                 // Output it
534                 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
535         %s debug output:
536 </div>
537 <div class="debug_content">
538         %s
539 </div>
540 Loaded includes:
541 <div class="debug_include_list">
542         %s
543 </div>',
544                         $this->__toString(),
545                         $content,
546                         ClassLoader::getSelfInstance()->getPrintableIncludeList()
547                 ));
548         }
549
550         /**
551          * Replaces control characters with printable output
552          *
553          * @param       $str    String with control characters
554          * @return      $str    Replaced string
555          */
556         protected function replaceControlCharacters ($str) {
557                 // Replace them
558                 $str = str_replace(
559                         chr(13), '[r]', str_replace(
560                         chr(10), '[n]', str_replace(
561                         chr(9) , '[t]',
562                         $str
563                 )));
564
565                 // Return it
566                 return $str;
567         }
568
569         /**
570          * Output a partial stub message for the caller method
571          *
572          * @param       $message        An optional message to display
573          * @return      void
574          */
575         protected function partialStub ($message = '') {
576                 // Init variable
577                 $stubMessage = 'Partial stub!';
578
579                 // Is an extra message given?
580                 if (!empty($message)) {
581                         // Then add it as well
582                         $stubMessage .= ' Message: ' . $message;
583                 }
584
585                 // Debug instance is there?
586                 if (!is_null($this->getDebugInstance())) {
587                         // Output stub message
588                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
589                 } else {
590                         // Trigger an error
591                         trigger_error($stubMessage);
592                         exit;
593                 }
594         }
595
596         /**
597          * Outputs a debug backtrace and stops further script execution
598          *
599          * @param       $message        An optional message to output
600          * @param       $doExit         Whether exit the program (true is default)
601          * @return      void
602          */
603         public function debugBackTrace ($message = '', $doExit = true) {
604                 // Sorry, there is no other way getting this nice backtrace
605                 if (!empty($message)) {
606                         // Output message
607                         printf('Message: %s<br />' . PHP_EOL, $message);
608                 }
609
610                 print('<pre>');
611                 debug_print_backtrace();
612                 print('</pre>');
613
614                 // Exit program?
615                 if ($doExit === true) {
616                         exit();
617                 }
618         }
619
620         /**
621          * Creates an instance of a debugger instance
622          *
623          * @param       $className              Name of the class (currently unsupported)
624          * @param       $lineNumber             Line number where the call was made
625          * @return      $debugInstance  An instance of a debugger class
626          * @deprecated  Not fully, as the new Logger facilities are not finished yet.
627          */
628         public final static function createDebugInstance ($className, $lineNumber = NULL) {
629                 // Is the instance set?
630                 if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
631                         // Init debug instance
632                         $debugInstance = NULL;
633
634                         // Try it
635                         try {
636                                 // Get a debugger instance
637                                 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
638                         } catch (NullPointerException $e) {
639                                 // Didn't work, no instance there
640                                 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
641                         }
642
643                         // Empty string should be ignored and used for testing the middleware
644                         DebugMiddleware::getSelfInstance()->output('');
645
646                         // Set it in registry
647                         GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
648                 } else {
649                         // Get instance from registry
650                         $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
651                 }
652
653                 // Return it
654                 return $debugInstance;
655         }
656
657         /**
658          * Simple output of a message with line-break
659          *
660          * @param       $message        Message to output
661          * @return      void
662          */
663         public function outputLine ($message) {
664                 // Simply output it
665                 print($message . PHP_EOL);
666         }
667
668         /**
669          * Outputs a debug message whether to debug instance (should be set!) or
670          * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
671          * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
672          *
673          * @param       $message        Message we shall send out...
674          * @param       $doPrint        Whether print or die here (default: print)
675          * @paran       $stripTags      Whether to strip tags (default: false)
676          * @return      void
677          */
678         public function debugOutput ($message, $doPrint = true, $stripTags = false) {
679                 // Set debug instance to NULL
680                 $debugInstance = NULL;
681
682                 // Get backtrace
683                 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
684
685                 // Is function partialStub/__callStatic ?
686                 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
687                         // Prepend class::function:line from 3rd element
688                         $message = sprintf('[%s::%s:%d]: %s',
689                                 $backtrace[2]['class'],
690                                 $backtrace[2]['function'],
691                                 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
692                                 $message
693                         );
694                 } else {
695                         // Prepend class::function:line from 2nd element
696                         $message = sprintf('[%s::%s:%d]: %s',
697                                 $backtrace[1]['class'],
698                                 $backtrace[1]['function'],
699                                 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
700                                 $message
701                         );
702                 }
703
704                 // Try it:
705                 try {
706                         // Get debug instance
707                         $debugInstance = $this->getDebugInstance();
708                 } catch (NullPointerException $e) {
709                         // The debug instance is not set (yet)
710                 }
711
712                 // Is the debug instance there?
713                 if (is_object($debugInstance)) {
714                         // Use debug output handler
715                         $debugInstance->output($message, $stripTags);
716
717                         if ($doPrint === false) {
718                                 // Die here if not printed
719                                 exit();
720                         }
721                 } else {
722                         // Are debug times enabled?
723                         if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
724                                 // Prepent it
725                                 $message = $this->getPrintableExecutionTime() . $message;
726                         }
727
728                         // Put directly out
729                         if ($doPrint === true) {
730                                 // Print message
731                                 $this->outputLine($message);
732                         } else {
733                                 // Die here
734                                 exit($message);
735                         }
736                 }
737         }
738
739         /**
740          * Marks up the code by adding e.g. line numbers
741          *
742          * @param       $phpCode                Unmarked PHP code
743          * @return      $markedCode             Marked PHP code
744          */
745         public function markupCode ($phpCode) {
746                 // Init marked code
747                 $markedCode = '';
748
749                 // Get last error
750                 $errorArray = error_get_last();
751
752                 // Init the code with error message
753                 if (is_array($errorArray)) {
754                         // Get error infos
755                         $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>',
756                                 basename($errorArray['file']),
757                                 $errorArray['line'],
758                                 $errorArray['message'],
759                                 $errorArray['type']
760                         );
761                 }
762
763                 // Add line number to the code
764                 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
765                         // Add line numbers
766                         $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
767                                 ($lineNo + 1),
768                                 htmlentities($code, ENT_QUOTES)
769                         );
770                 }
771
772                 // Return the code
773                 return $markedCode;
774         }
775
776         /**
777          * "Getter" for databse entry
778          *
779          * @return      $entry  An array with database entries
780          * @throws      NullPointerException    If the database result is not found
781          * @throws      InvalidDatabaseResultException  If the database result is invalid
782          * @todo        Monolithic method, should be moved to proper classes
783          */
784         protected final function getDatabaseEntry () {
785                 // Is there an instance?
786                 if (!$this->getResultInstance() instanceof SearchableResult) {
787                         // Throw an exception here
788                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
789                 }
790
791                 // Rewind it
792                 $this->getResultInstance()->rewind();
793
794                 // Do we have an entry?
795                 if ($this->getResultInstance()->valid() === false) {
796                         // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
797                         throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
798                 }
799
800                 // Get next entry
801                 $this->getResultInstance()->next();
802
803                 // Fetch it
804                 $entry = $this->getResultInstance()->current();
805
806                 // And return it
807                 return $entry;
808         }
809
810         /**
811          * Getter for field name
812          *
813          * @param       $fieldName              Field name which we shall get
814          * @return      $fieldValue             Field value from the user
815          * @throws      NullPointerException    If the result instance is null
816          */
817         public final function getField (string $fieldName) {
818                 // Default field value
819                 $fieldValue = NULL;
820
821                 // Get result instance
822                 $resultInstance = $this->getResultInstance();
823
824                 // Is this instance null?
825                 if (is_null($resultInstance)) {
826                         // Then the user instance is no longer valid (expired cookies?)
827                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
828                 }
829
830                 // Get current array
831                 $fieldArray = $resultInstance->current();
832                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
833
834                 // Convert dashes to underscore
835                 $fieldName2 = StringUtils::convertDashesToUnderscores($fieldName);
836
837                 // Does the field exist?
838                 if ($this->isFieldSet($fieldName)) {
839                         // Get it
840                         $fieldValue = $fieldArray[$fieldName2];
841                 } elseif (defined('DEVELOPER')) {
842                         // Missing field entry, may require debugging
843                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
844                 } else {
845                         // Missing field entry, may require debugging
846                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
847                 }
848
849                 // Return it
850                 return $fieldValue;
851         }
852
853         /**
854          * Checks if given field is set
855          *
856          * @param       $fieldName      Field name to check
857          * @return      $isSet          Whether the given field name is set
858          * @throws      NullPointerException    If the result instance is null
859          */
860         public function isFieldSet (string $fieldName) {
861                 // Get result instance
862                 $resultInstance = $this->getResultInstance();
863
864                 // Is this instance null?
865                 if (is_null($resultInstance)) {
866                         // Then the user instance is no longer valid (expired cookies?)
867                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
868                 }
869
870                 // Get current array
871                 $fieldArray = $resultInstance->current();
872                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
873
874                 // Convert dashes to underscore
875                 $fieldName = StringUtils::convertDashesToUnderscores($fieldName);
876
877                 // Determine it
878                 $isSet = isset($fieldArray[$fieldName]);
879
880                 // Return result
881                 return $isSet;
882         }
883
884         /**
885          * Outputs a deprecation warning to the developer.
886          *
887          * @param       $message        The message we shall output to the developer
888          * @return      void
889          * @todo        Write a logging mechanism for productive mode
890          */
891         public function deprecationWarning ($message) {
892                 // Is developer mode active?
893                 if (defined('DEVELOPER')) {
894                         // Debug instance is there?
895                         if (!is_null($this->getDebugInstance())) {
896                                 // Output stub message
897                                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
898                         } else {
899                                 // Trigger an error
900                                 trigger_error($message . "<br />\n");
901                                 exit;
902                         }
903                 } else {
904                         // @TODO Finish this part!
905                         $this->partialStub('Developer mode inactive. Message:' . $message);
906                 }
907         }
908
909         /**
910          * Checks whether the given PHP extension is loaded
911          *
912          * @param       $phpExtension   The PHP extension we shall check
913          * @return      $isLoaded       Whether the PHP extension is loaded
914          */
915         public final function isPhpExtensionLoaded ($phpExtension) {
916                 // Is it loaded?
917                 $isLoaded = in_array($phpExtension, get_loaded_extensions());
918
919                 // Return result
920                 return $isLoaded;
921         }
922
923         /**
924          * "Getter" as a time() replacement but with milliseconds. You should use this
925          * method instead of the encapsulated getimeofday() function.
926          *
927          * @return      $milliTime      Timestamp with milliseconds
928          */
929         public function getMilliTime () {
930                 // Get the time of day as float
931                 $milliTime = gettimeofday(true);
932
933                 // Return it
934                 return $milliTime;
935         }
936
937         /**
938          * Idles (sleeps) for given milliseconds
939          *
940          * @return      $hasSlept       Whether it goes fine
941          */
942         public function idle ($milliSeconds) {
943                 // Sleep is fine by default
944                 $hasSlept = true;
945
946                 // Idle so long with found function
947                 if (function_exists('time_sleep_until')) {
948                         // Get current time and add idle time
949                         $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
950
951                         // New PHP 5.1.0 function found, ignore errors
952                         $hasSlept = @time_sleep_until($sleepUntil);
953                 } else {
954                         /*
955                          * My Sun station doesn't have that function even with latest PHP
956                          * package. :(
957                          */
958                         usleep($milliSeconds * 1000);
959                 }
960
961                 // Return result
962                 return $hasSlept;
963         }
964
965         /**
966          * Checks whether the given encoded data was encoded with Base64
967          *
968          * @param       $encodedData    Encoded data we shall check
969          * @return      $isBase64               Whether the encoded data is Base64
970          */
971         protected function isBase64Encoded ($encodedData) {
972                 // Determine it
973                 $isBase64 = (@base64_decode($encodedData, true) !== false);
974
975                 // Return it
976                 return $isBase64;
977         }
978
979         /**
980          * Gets a cache key from Criteria instance
981          *
982          * @param       $criteriaInstance       An instance of a Criteria class
983          * @param       $onlyKeys                       Only use these keys for a cache key
984          * @return      $cacheKey                       A cache key suitable for lookup/storage purposes
985          */
986         protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = []) {
987                 // Generate it
988                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: criteriaInstance=' . $criteriaInstance->__toString() . ',onlyKeys()=' . count($onlyKeys) . ' - CALLED!');
989                 $cacheKey = sprintf('%s@%s',
990                         $this->__toString(),
991                         $criteriaInstance->getCacheKey($onlyKeys)
992                 );
993
994                 // And return it
995                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: cacheKey=' . $cacheKey . ' - EXIT!');
996                 return $cacheKey;
997         }
998
999         /**
1000          * Getter for startup time in miliseconds
1001          *
1002          * @return      $startupTime    Startup time in miliseconds
1003          */
1004         protected function getStartupTime () {
1005                 return self::$startupTime;
1006         }
1007
1008         /**
1009          * "Getter" for a printable currently execution time in nice braces
1010          *
1011          * @return      $executionTime  Current execution time in nice braces
1012          */
1013         protected function getPrintableExecutionTime () {
1014                 // Caculate the execution time
1015                 $executionTime = microtime(true) - $this->getStartupTime();
1016
1017                 // Pack it in nice braces
1018                 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
1019
1020                 // And return it
1021                 return $executionTime;
1022         }
1023
1024         /**
1025          * Hashes a given string with a simple but stronger hash function (no salt)
1026          * and hex-encode it.
1027          *
1028          * @param       $str    The string to be hashed
1029          * @return      $hash   The hash from string $str
1030          */
1031         public static final function hash ($str) {
1032                 // Hash given string with (better secure) hasher
1033                 $hash = bin2hex(mhash(MHASH_SHA256, $str));
1034
1035                 // Return it
1036                 return $hash;
1037         }
1038
1039         /**
1040          * "Getter" for length of hash() output. This will be "cached" to speed up
1041          * things.
1042          *
1043          * @return      $length         Length of hash() output
1044          */
1045         public static final function getHashLength () {
1046                 // Is it cashed?
1047                 if (is_null(self::$hashLength)) {
1048                         // No, then hash a string and save its length.
1049                         self::$hashLength = strlen(self::hash('abc123'));
1050                 }
1051
1052                 // Return it
1053                 return self::$hashLength;
1054         }
1055
1056         /**
1057          * Checks whether the given number is really a number (only chars 0-9).
1058          *
1059          * @param       $num            A string consisting only chars between 0 and 9
1060          * @param       $castValue      Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
1061          * @param       $assertMismatch         Whether to assert mismatches
1062          * @return      $ret            The (hopefully) secured numbered value
1063          */
1064         public function bigintval ($num, $castValue = true, $assertMismatch = false) {
1065                 // Filter all numbers out
1066                 $ret = preg_replace('/[^0123456789]/', '', $num);
1067
1068                 // Shall we cast?
1069                 if ($castValue === true) {
1070                         // Cast to biggest numeric type
1071                         $ret = (double) $ret;
1072                 }
1073
1074                 // Assert only if requested
1075                 if ($assertMismatch === true) {
1076                         // Has the whole value changed?
1077                         assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
1078                 }
1079
1080                 // Return result
1081                 return $ret;
1082         }
1083
1084         /**
1085          * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
1086          *
1087          * @param       $num    A string consisting only chars between 0 and 9
1088          * @param       $assertMismatch         Whether to assert mismatches
1089          * @return      $ret    The (hopefully) secured hext-numbered value
1090          */
1091         public function hexval ($num, $assertMismatch = false) {
1092                 // Filter all numbers out
1093                 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
1094
1095                 // Assert only if requested
1096                 if ($assertMismatch === true) {
1097                         // Has the whole value changed?
1098                         assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
1099                 }
1100
1101                 // Return result
1102                 return $ret;
1103         }
1104
1105         /**
1106          * Determines if an element is set in the generic array
1107          *
1108          * @param       $keyGroup       Main group for the key
1109          * @param       $subGroup       Sub group for the key
1110          * @param       $key            Key to check
1111          * @param       $element        Element to check
1112          * @return      $isset          Whether the given key is set
1113          */
1114         protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
1115                 // Debug message
1116                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
1117
1118                 // Is it there?
1119                 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
1120
1121                 // Return it
1122                 return $isset;
1123         }
1124         /**
1125          * Determines if a key is set in the generic array
1126          *
1127          * @param       $keyGroup       Main group for the key
1128          * @param       $subGroup       Sub group for the key
1129          * @param       $key            Key to check
1130          * @return      $isset          Whether the given key is set
1131          */
1132         protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
1133                 // Debug message
1134                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1135
1136                 // Is it there?
1137                 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
1138
1139                 // Return it
1140                 return $isset;
1141         }
1142
1143
1144         /**
1145          * Determines if a group is set in the generic array
1146          *
1147          * @param       $keyGroup       Main group
1148          * @param       $subGroup       Sub group
1149          * @return      $isset          Whether the given group is set
1150          */
1151         protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
1152                 // Debug message
1153                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
1154
1155                 // Is it there?
1156                 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
1157
1158                 // Return it
1159                 return $isset;
1160         }
1161
1162         /**
1163          * Getter for sub key group
1164          *
1165          * @param       $keyGroup       Main key group
1166          * @param       $subGroup       Sub key group
1167          * @return      $array          An array with all array elements
1168          */
1169         protected final function getGenericSubArray ($keyGroup, $subGroup) {
1170                 // Is it there?
1171                 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
1172                         // No, then abort here
1173                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
1174                         exit;
1175                 }
1176
1177                 // Debug message
1178                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
1179
1180                 // Return it
1181                 return $this->genericArray[$keyGroup][$subGroup];
1182         }
1183
1184         /**
1185          * Unsets a given key in generic array
1186          *
1187          * @param       $keyGroup       Main group for the key
1188          * @param       $subGroup       Sub group for the key
1189          * @param       $key            Key to unset
1190          * @return      void
1191          */
1192         protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
1193                 // Debug message
1194                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1195
1196                 // Remove it
1197                 unset($this->genericArray[$keyGroup][$subGroup][$key]);
1198         }
1199
1200         /**
1201          * Unsets a given element in generic array
1202          *
1203          * @param       $keyGroup       Main group for the key
1204          * @param       $subGroup       Sub group for the key
1205          * @param       $key            Key to unset
1206          * @param       $element        Element to unset
1207          * @return      void
1208          */
1209         protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
1210                 // Debug message
1211                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
1212
1213                 // Remove it
1214                 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
1215         }
1216
1217         /**
1218          * Append a string to a given generic array key
1219          *
1220          * @param       $keyGroup       Main group for the key
1221          * @param       $subGroup       Sub group for the key
1222          * @param       $key            Key to unset
1223          * @param       $value          Value to add/append
1224          * @return      void
1225          */
1226         protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
1227                 // Debug message
1228                 //* 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);
1229
1230                 // Is it already there?
1231                 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1232                         // Append it
1233                         $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
1234                 } else {
1235                         // Add it
1236                         $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
1237                 }
1238         }
1239
1240         /**
1241          * Append a string to a given generic array element
1242          *
1243          * @param       $keyGroup       Main group for the key
1244          * @param       $subGroup       Sub group for the key
1245          * @param       $key            Key to unset
1246          * @param       $element        Element to check
1247          * @param       $value          Value to add/append
1248          * @return      void
1249          */
1250         protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
1251                 // Debug message
1252                 //* 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);
1253
1254                 // Is it already there?
1255                 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
1256                         // Append it
1257                         $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
1258                 } else {
1259                         // Add it
1260                         $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
1261                 }
1262         }
1263
1264         /**
1265          * Sets a string in a given generic array element
1266          *
1267          * @param       $keyGroup       Main group for the key
1268          * @param       $subGroup       Sub group for the key
1269          * @param       $key            Key to unset
1270          * @param       $element        Element to check
1271          * @param       $value          Value to add/append
1272          * @return      void
1273          */
1274         protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
1275                 // Debug message
1276                 //* 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);
1277
1278                 // Set it
1279                 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
1280         }
1281
1282         /**
1283          * Initializes given generic array group
1284          *
1285          * @param       $keyGroup       Main group for the key
1286          * @param       $subGroup       Sub group for the key
1287          * @param       $key            Key to use
1288          * @param       $forceInit      Optionally force initialization
1289          * @return      void
1290          */
1291         protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
1292                 // Debug message
1293                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
1294
1295                 // Is it already set?
1296                 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
1297                         // Already initialized
1298                         trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
1299                         exit;
1300                 }
1301
1302                 // Initialize it
1303                 $this->genericArray[$keyGroup][$subGroup] = [];
1304         }
1305
1306         /**
1307          * Initializes given generic array key
1308          *
1309          * @param       $keyGroup       Main group for the key
1310          * @param       $subGroup       Sub group for the key
1311          * @param       $key            Key to use
1312          * @param       $forceInit      Optionally force initialization
1313          * @return      void
1314          */
1315         protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
1316                 // Debug message
1317                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
1318
1319                 // Is it already set?
1320                 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
1321                         // Already initialized
1322                         trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
1323                         exit;
1324                 }
1325
1326                 // Initialize it
1327                 $this->genericArray[$keyGroup][$subGroup][$key] = [];
1328         }
1329
1330         /**
1331          * Initializes given generic array element
1332          *
1333          * @param       $keyGroup       Main group for the key
1334          * @param       $subGroup       Sub group for the key
1335          * @param       $key            Key to use
1336          * @param       $element        Element to use
1337          * @param       $forceInit      Optionally force initialization
1338          * @return      void
1339          */
1340         protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
1341                 // Debug message
1342                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
1343
1344                 // Is it already set?
1345                 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
1346                         // Already initialized
1347                         trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
1348                         exit;
1349                 }
1350
1351                 // Initialize it
1352                 $this->genericArray[$keyGroup][$subGroup][$key][$element] = [];
1353         }
1354
1355         /**
1356          * Pushes an element to a generic key
1357          *
1358          * @param       $keyGroup       Main group for the key
1359          * @param       $subGroup       Sub group for the key
1360          * @param       $key            Key to use
1361          * @param       $value          Value to add/append
1362          * @return      $count          Number of array elements
1363          */
1364         protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
1365                 // Debug message
1366                 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
1367
1368                 // Is it set?
1369                 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1370                         // Initialize array
1371                         $this->initGenericArrayKey($keyGroup, $subGroup, $key);
1372                 }
1373
1374                 // Then push it
1375                 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
1376
1377                 // Return count
1378                 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
1379                 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
1380                 return $count;
1381         }
1382
1383         /**
1384          * Pushes an element to a generic array element
1385          *
1386          * @param       $keyGroup       Main group for the key
1387          * @param       $subGroup       Sub group for the key
1388          * @param       $key            Key to use
1389          * @param       $element        Element to check
1390          * @param       $value          Value to add/append
1391          * @return      $count          Number of array elements
1392          */
1393         protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
1394                 // Debug message
1395                 //* 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));
1396
1397                 // Is it set?
1398                 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
1399                         // Initialize array
1400                         $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
1401                 }
1402
1403                 // Then push it
1404                 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
1405
1406                 // Return count
1407                 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
1408                 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
1409                 return $count;
1410         }
1411
1412         /**
1413          * Pops an element from  a generic group
1414          *
1415          * @param       $keyGroup       Main group for the key
1416          * @param       $subGroup       Sub group for the key
1417          * @param       $key            Key to unset
1418          * @return      $value          Last "popped" value
1419          */
1420         protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
1421                 // Debug message
1422                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1423
1424                 // Is it set?
1425                 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1426                         // Not found
1427                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
1428                         exit;
1429                 }
1430
1431                 // Then "pop" it
1432                 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
1433
1434                 // Return value
1435                 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
1436                 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
1437                 return $value;
1438         }
1439
1440         /**
1441          * Shifts an element from  a generic group
1442          *
1443          * @param       $keyGroup       Main group for the key
1444          * @param       $subGroup       Sub group for the key
1445          * @param       $key            Key to unset
1446          * @return      $value          Last "popped" value
1447          */
1448         protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
1449                 // Debug message
1450                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1451
1452                 // Is it set?
1453                 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1454                         // Not found
1455                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
1456                         exit;
1457                 }
1458
1459                 // Then "shift" it
1460                 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
1461
1462                 // Return value
1463                 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
1464                 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
1465                 return $value;
1466         }
1467
1468         /**
1469          * Count generic array group
1470          *
1471          * @param       $keyGroup       Main group for the key
1472          * @return      $count          Count of given group
1473          */
1474         protected final function countGenericArray ($keyGroup) {
1475                 // Debug message
1476                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
1477
1478                 // Is it there?
1479                 if (!isset($this->genericArray[$keyGroup])) {
1480                         // Abort here
1481                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
1482                         exit;
1483                 }
1484
1485                 // Then count it
1486                 $count = count($this->genericArray[$keyGroup]);
1487
1488                 // Debug message
1489                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
1490
1491                 // Return it
1492                 return $count;
1493         }
1494
1495         /**
1496          * Count generic array sub group
1497          *
1498          * @param       $keyGroup       Main group for the key
1499          * @param       $subGroup       Sub group for the key
1500          * @return      $count          Count of given group
1501          */
1502         protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
1503                 // Debug message
1504                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
1505
1506                 // Is it there?
1507                 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
1508                         // Abort here
1509                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
1510                         exit;
1511                 }
1512
1513                 // Then count it
1514                 $count = count($this->genericArray[$keyGroup][$subGroup]);
1515
1516                 // Debug message
1517                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
1518
1519                 // Return it
1520                 return $count;
1521         }
1522
1523         /**
1524          * Count generic array elements
1525          *
1526          * @param       $keyGroup       Main group for the key
1527          * @param       $subGroup       Sub group for the key
1528          * @para        $key            Key to count
1529          * @return      $count          Count of given key
1530          */
1531         protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
1532                 // Debug message
1533                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1534
1535                 // Is it there?
1536                 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1537                         // Abort here
1538                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
1539                         exit;
1540                 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
1541                         // Not valid
1542                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
1543                         exit;
1544                 }
1545
1546                 // Then count it
1547                 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
1548
1549                 // Debug message
1550                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
1551
1552                 // Return it
1553                 return $count;
1554         }
1555
1556         /**
1557          * Getter for whole generic group array
1558          *
1559          * @param       $keyGroup       Key group to get
1560          * @return      $array          Whole generic array group
1561          */
1562         protected final function getGenericArray ($keyGroup) {
1563                 // Debug message
1564                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
1565
1566                 // Is it there?
1567                 if (!isset($this->genericArray[$keyGroup])) {
1568                         // Then abort here
1569                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
1570                         exit;
1571                 }
1572
1573                 // Return it
1574                 return $this->genericArray[$keyGroup];
1575         }
1576
1577         /**
1578          * Setter for generic array key
1579          *
1580          * @param       $keyGroup       Key group to get
1581          * @param       $subGroup       Sub group for the key
1582          * @param       $key            Key to unset
1583          * @param       $value          Mixed value from generic array element
1584          * @return      void
1585          */
1586         protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
1587                 // Debug message
1588                 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
1589
1590                 // Set value here
1591                 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
1592         }
1593
1594         /**
1595          * Getter for generic array key
1596          *
1597          * @param       $keyGroup       Key group to get
1598          * @param       $subGroup       Sub group for the key
1599          * @param       $key            Key to unset
1600          * @return      $value          Mixed value from generic array element
1601          */
1602         protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
1603                 // Debug message
1604                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1605
1606                 // Is it there?
1607                 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1608                         // Then abort here
1609                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
1610                         exit;
1611                 }
1612
1613                 // Return it
1614                 return $this->genericArray[$keyGroup][$subGroup][$key];
1615         }
1616
1617         /**
1618          * Sets a value in given generic array key/element
1619          *
1620          * @param       $keyGroup       Main group for the key
1621          * @param       $subGroup       Sub group for the key
1622          * @param       $key            Key to set
1623          * @param       $element        Element to set
1624          * @param       $value          Value to set
1625          * @return      void
1626          */
1627         protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
1628                 // Debug message
1629                 //* 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));
1630
1631                 // Then set it
1632                 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
1633         }
1634
1635         /**
1636          * Getter for generic array element
1637          *
1638          * @param       $keyGroup       Key group to get
1639          * @param       $subGroup       Sub group for the key
1640          * @param       $key            Key to look for
1641          * @param       $element        Element to look for
1642          * @return      $value          Mixed value from generic array element
1643          */
1644         protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
1645                 // Debug message
1646                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
1647
1648                 // Is it there?
1649                 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
1650                         // Then abort here
1651                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
1652                         exit;
1653                 }
1654
1655                 // Return it
1656                 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
1657         }
1658
1659         /**
1660          * Checks if a given sub group is valid (array)
1661          *
1662          * @param       $keyGroup       Key group to get
1663          * @param       $subGroup       Sub group for the key
1664          * @return      $isValid        Whether given sub group is valid
1665          */
1666         protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
1667                 // Debug message
1668                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
1669
1670                 // Determine it
1671                 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
1672
1673                 // Return it
1674                 return $isValid;
1675         }
1676
1677         /**
1678          * Checks if a given key is valid (array)
1679          *
1680          * @param       $keyGroup       Key group to get
1681          * @param       $subGroup       Sub group for the key
1682          * @param       $key            Key to check
1683          * @return      $isValid        Whether given sub group is valid
1684          */
1685         protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
1686                 // Debug message
1687                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1688
1689                 // Determine it
1690                 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
1691
1692                 // Return it
1693                 return $isValid;
1694         }
1695
1696         /**
1697          * Initializes the web output instance
1698          *
1699          * @return      void
1700          */
1701         protected function initWebOutputInstance () {
1702                 // Get application instance
1703                 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1704
1705                 // Init web output instance
1706                 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
1707
1708                 // Set it locally
1709                 $this->setWebOutputInstance($outputInstance);
1710         }
1711
1712         /**
1713          * Translates boolean true to 'Y' and false to 'N'
1714          *
1715          * @param       $boolean                Boolean value
1716          * @return      $translated             Translated boolean value
1717          */
1718         public static final function translateBooleanToYesNo (bool $boolean) {
1719                 // Make sure it is really boolean
1720                 assert(is_bool($boolean));
1721
1722                 // "Translate" it
1723                 $translated = ($boolean === true) ? 'Y' : 'N';
1724
1725                 // ... and return it
1726                 return $translated;
1727         }
1728
1729         /**
1730          * Creates a full-qualified file name (FQFN) for given file name by adding
1731          * a configured temporary file path to it.
1732          *
1733          * @param       $infoInstance   An instance of a SplFileInfo class
1734          * @return      $tempInstance   An instance of a SplFileInfo class (temporary file)
1735          * @throw       PathWriteProtectedException If the path in 'temp_file_path' is write-protected
1736          * @throws      FileIoException If the file cannot be written
1737          */
1738          protected static function createTempPathForFile (SplFileInfo $infoInstance) {
1739                 // Get config entry
1740                 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
1741
1742                 // Is the path writeable?
1743                 if (!is_writable($basePath)) {
1744                         // Path is write-protected
1745                         throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
1746                 }
1747
1748                 // Add it
1749                 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
1750
1751                 // Is it reachable?
1752                 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
1753                         // Not reachable
1754                         throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
1755                 }
1756
1757                 // Return it
1758                 return $tempInstance;
1759          }
1760
1761         /**
1762          * "Getter" for a printable state name
1763          *
1764          * @return      $stateName      Name of the node's state in a printable format
1765          * @todo        Move this class away from this monolithic place (not whole class is monolithic)
1766          */
1767         public final function getPrintableState () {
1768                 // Default is 'null'
1769                 $stateName = 'null';
1770
1771                 // Get the state instance
1772                 $stateInstance = $this->getStateInstance();
1773
1774                 // Is it an instance of Stateable?
1775                 if ($stateInstance instanceof Stateable) {
1776                         // Then use that state name
1777                         $stateName = $stateInstance->getStateName();
1778                 }
1779
1780                 // Return result
1781                 return $stateName;
1782         }
1783
1784 }