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