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