3 namespace Org\Mxchange\CoreFramework\Object;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Criteria\Criteria;
8 use Org\Mxchange\CoreFramework\Crypto\Cryptable;
9 use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
10 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
11 use Org\Mxchange\CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
12 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
13 use Org\Mxchange\CoreFramework\Filesystem\PathWriteProtectedException;
14 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
15 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
16 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
17 use Org\Mxchange\CoreFramework\Handler\Handleable;
18 use Org\Mxchange\CoreFramework\Helper\Helper;
19 use Org\Mxchange\CoreFramework\Loader\ClassLoader;
20 use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
21 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
22 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
23 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
24 use Org\Mxchange\CoreFramework\Result\Database\CachedDatabaseResult;
25 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
26 use Org\Mxchange\CoreFramework\State\Stateable;
27 use Org\Mxchange\CoreFramework\Stream\Input\InputStream;
28 use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
29 use Org\Mxchange\CoreFramework\Stream\Output\OutputStream;
30 use Org\Mxchange\CoreFramework\User\ManageableAccount;
31 use Org\Mxchange\CoreFramework\Utils\String\StringUtils;
35 use \InvalidArgumentException;
41 * The simulator system class is the super class of all other classes. This
42 * class handles saving of games etc.
44 * @author Roland Haeder <webmaster@shipsimu.org>
46 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
47 * @license GNU GPL 3.0 or any newer version
48 * @link http://www.shipsimu.org
50 * This program is free software: you can redistribute it and/or modify
51 * it under the terms of the GNU General Public License as published by
52 * the Free Software Foundation, either version 3 of the License, or
53 * (at your option) any later version.
55 * This program is distributed in the hope that it will be useful,
56 * but WITHOUT ANY WARRANTY; without even the implied warranty of
57 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
58 * GNU General Public License for more details.
60 * You should have received a copy of the GNU General Public License
61 * along with this program. If not, see <http://www.gnu.org/licenses/>.
63 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
65 * Length of output from hash()
67 private static $hashLength = NULL;
70 * Self-referencing instance
72 private static $instance = NULL;
77 private $realClass = __CLASS__;
80 * Database result instance
82 private $resultInstance = NULL;
85 * Instance for user class
87 private $userInstance = NULL;
90 * Instance of a crypto helper
92 private $cryptoInstance = NULL;
95 * Instance of an Iterator class
97 private $iteratorInstance = NULL;
100 * A helper instance for the form
102 private $helperInstance = NULL;
105 * An instance of a InputStream class
107 private $inputStreamInstance = NULL;
110 * An instance of a OutputStream class
112 private $outputStreamInstance = NULL;
117 private $handlerInstance = NULL;
120 * An instance of a database wrapper class
122 private $wrapperInstance = NULL;
127 private $stateInstance = NULL;
132 private $callbackInstance = NULL;
137 private $genericArray = array();
139 /***********************
140 * Exception codes.... *
141 ***********************/
143 // @todo Try to clean these constants up
144 const EXCEPTION_IS_NULL_POINTER = 0x001;
145 const EXCEPTION_IS_NO_OBJECT = 0x002;
146 const EXCEPTION_IS_NO_ARRAY = 0x003;
147 const EXCEPTION_MISSING_METHOD = 0x004;
148 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
149 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
150 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
151 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
152 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
153 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
154 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
155 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
156 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
157 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
158 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
159 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
160 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
161 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
162 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
163 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
164 const EXCEPTION_PATH_NOT_FOUND = 0x015;
165 const EXCEPTION_INVALID_PATH_NAME = 0x016;
166 const EXCEPTION_READ_PROTECED_PATH = 0x017;
167 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
168 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
169 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
170 const EXCEPTION_INVALID_RESOURCE = 0x01b;
171 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
172 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
173 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
174 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
175 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
176 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
177 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
178 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
179 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
180 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
181 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
182 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
183 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
184 const EXCEPTION_INVALID_STRING = 0x029;
185 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
186 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
187 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
188 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
189 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
190 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
191 const EXCEPTION_MISSING_ELEMENT = 0x030;
192 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
193 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
194 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
195 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
196 const EXCEPTION_FATAL_ERROR = 0x035;
197 const EXCEPTION_FILE_NOT_FOUND = 0x036;
198 const EXCEPTION_ASSERTION_FAILED = 0x037;
199 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
200 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
201 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
202 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
203 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
204 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
205 const EXCEPTION_INVALID_SOCKET = 0x03e;
206 const EXCEPTION_SELF_INSTANCE = 0x03f;
209 * Startup time in miliseconds
211 private static $startupTime = 0;
214 * Protected super constructor
216 * @param $className Name of the class
219 protected function __construct (string $className) {
221 $this->setRealClass($className);
223 // Is the startup time set? (0 cannot be true anymore)
224 if (self::$startupTime == 0) {
226 self::$startupTime = microtime(true);
231 * Destructor for all classes. You should not call this method on your own.
235 public function __destruct () {
236 // Flush any updated entries to the database
237 $this->flushPendingUpdates();
239 // Is this object already destroyed?
240 if ($this->__toString() != 'DestructedObject') {
241 // Destroy all informations about this class but keep some text about it alive
242 $this->setRealClass('DestructedObject');
243 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
244 // Already destructed object
245 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
249 // Do not call this twice
250 trigger_error(__METHOD__ . ': Called twice.');
256 * The __call() method where all non-implemented methods end up
258 * @param $methodName Name of the missing method
259 * @args $args Arguments passed to the method
262 public final function __call ($methodName, $args) {
264 self::$instance = $this;
266 // Call static method
267 self::__callStatic($methodName, $args);
269 // Clear self-instance
270 self::$instance = NULL;
274 * The __callStatic() method where all non-implemented static methods end up
276 * @param $methodName Name of the missing method
277 * @param $args Arguments passed to the method
279 * @throws InvalidArgumentException If self::$instance is not a framework's own object
281 public static final function __callStatic ($methodName, $args) {
283 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
285 // Init argument string and class name
287 $className = 'unknown';
289 // Is self-instance set?
290 if (self::$instance instanceof FrameworkInterface) {
291 // Framework's own instance
292 $className = self::$instance->__toString();
293 } elseif (!is_null(self::$instance)) {
295 throw new InvalidArgumentException(sprintf('self::instance[%s] is not expected.', gettype(self::$instance)), self::EXCEPTION_SELF_INSTANCE);
298 // Is it NULL, empty or an array?
299 if (is_null($args)) {
301 $argsString = 'NULL';
302 } elseif (is_array($args)) {
306 // Some arguments are there
307 foreach ($args as $arg) {
308 // Add data about the argument
309 $argsString .= gettype($arg) . ':';
312 // Found a NULL argument
313 $argsString .= 'NULL';
314 } elseif (is_string($arg)) {
315 // Add length for strings
316 $argsString .= strlen($arg);
317 } elseif ((is_int($arg)) || (is_float($arg))) {
320 } elseif (is_array($arg)) {
321 // .. or size if array
322 $argsString .= count($arg);
323 } elseif (is_object($arg)) {
325 $reflection = new ReflectionClass($arg);
327 // Is an other object, maybe no __toString() available
328 $argsString .= $reflection->getName();
329 } elseif ($arg === true) {
330 // ... is boolean 'true'
331 $argsString .= 'true';
332 } elseif ($arg === false) {
333 // ... is boolean 'false'
334 $argsString .= 'false';
337 // Comma for next one
342 if (substr($argsString, -2, 1) == ',') {
344 $argsString = substr($argsString, 0, -2);
350 // Invalid arguments!
351 $argsString = sprintf('!INVALID:%s!', gettype($args));
354 // Output stub message
355 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
356 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s::%s]: Stub! Args: %s',
367 * Getter for $realClass
369 * @return $realClass The name of the real class (not BaseFrameworkSystem)
371 public function __toString () {
372 return $this->realClass;
376 * Magic method to catch setting of missing but set class fields/attributes
378 * @param $name Name of the field/attribute
379 * @param $value Value to store
382 public final function __set ($name, $value) {
383 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
386 print_r($value, true)
391 * Magic method to catch getting of missing fields/attributes
393 * @param $name Name of the field/attribute
396 public final function __get ($name) {
397 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
403 * Magic method to catch unsetting of missing fields/attributes
405 * @param $name Name of the field/attribute
408 public final function __unset ($name) {
409 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
415 * Magic method to catch object serialization
417 * @return $unsupported Unsupported method
418 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
420 public final function __sleep () {
421 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
425 * Magic method to catch object deserialization
427 * @return $unsupported Unsupported method
428 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
430 public final function __wakeup () {
431 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
435 * Magic method to catch calls when an object instance is called
437 * @return $unsupported Unsupported method
438 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
440 public final function __invoke () {
441 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
445 * Setter for the real class name
447 * @param $realClass Class name (string)
450 public final function setRealClass ($realClass) {
452 $this->realClass = (string) $realClass;
456 * Setter for database result instance
458 * @param $resultInstance An instance of a database result class
460 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
462 protected final function setResultInstance (SearchableResult $resultInstance) {
463 $this->resultInstance = $resultInstance;
467 * Getter for database result instance
469 * @return $resultInstance An instance of a database result class
471 public final function getResultInstance () {
472 return $this->resultInstance;
476 * Setter for debug instance
478 * @param $debugInstance The instance for debug output class
481 public final function setDebugInstance (DebugMiddleware $debugInstance) {
482 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
486 * Getter for debug instance
488 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
490 public final function getDebugInstance () {
491 // Get debug instance
492 $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
495 return $debugInstance;
499 * Setter for web output instance
501 * @param $webInstance The instance for web output class
504 public final function setWebOutputInstance (OutputStreamer $webInstance) {
505 GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
509 * Getter for web output instance
511 * @return $webOutputInstance - Instance to class WebOutput
513 public final function getWebOutputInstance () {
514 $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
515 return $webOutputInstance;
519 * Private getter for language instance
521 * @return $langInstance An instance to the language sub-system
523 protected final function getLanguageInstance () {
524 $langInstance = GenericRegistry::getRegistry()->getInstance('language');
525 return $langInstance;
529 * Setter for language instance
531 * @param $langInstance An instance to the language sub-system
533 * @see LanguageSystem
535 public final function setLanguageInstance (ManageableLanguage $langInstance) {
536 GenericRegistry::getRegistry()->addInstance('language', $langInstance);
540 * Protected setter for user instance
542 * @param $userInstance An instance of a user class
545 protected final function setUserInstance (ManageableAccount $userInstance) {
546 $this->userInstance = $userInstance;
550 * Getter for user instance
552 * @return $userInstance An instance of a user class
554 public final function getUserInstance () {
555 return $this->userInstance;
559 * Setter for Cryptable instance
561 * @param $cryptoInstance An instance of a Cryptable class
564 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
565 $this->cryptoInstance = $cryptoInstance;
569 * Getter for Cryptable instance
571 * @return $cryptoInstance An instance of a Cryptable class
573 public final function getCryptoInstance () {
574 return $this->cryptoInstance;
578 * Setter for DatabaseWrapper instance
580 * @param $wrapperInstance An instance of an DatabaseWrapper
583 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
584 $this->wrapperInstance = $wrapperInstance;
588 * Getter for DatabaseWrapper instance
590 * @return $wrapperInstance An instance of an DatabaseWrapper
592 public final function getWrapperInstance () {
593 return $this->wrapperInstance;
597 * Setter for helper instance
599 * @param $helperInstance An instance of a helper class
602 protected final function setHelperInstance (Helper $helperInstance) {
603 $this->helperInstance = $helperInstance;
607 * Getter for helper instance
609 * @return $helperInstance An instance of a helper class
611 public final function getHelperInstance () {
612 return $this->helperInstance;
616 * Getter for a InputStream instance
618 * @param $inputStreamInstance The InputStream instance
620 protected final function getInputStreamInstance () {
621 return $this->inputStreamInstance;
625 * Setter for a InputStream instance
627 * @param $inputStreamInstance The InputStream instance
630 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
631 $this->inputStreamInstance = $inputStreamInstance;
635 * Getter for a OutputStream instance
637 * @param $outputStreamInstance The OutputStream instance
639 protected final function getOutputStreamInstance () {
640 return $this->outputStreamInstance;
644 * Setter for a OutputStream instance
646 * @param $outputStreamInstance The OutputStream instance
649 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
650 $this->outputStreamInstance = $outputStreamInstance;
654 * Setter for handler instance
656 * @param $handlerInstance An instance of a Handleable class
659 protected final function setHandlerInstance (Handleable $handlerInstance) {
660 $this->handlerInstance = $handlerInstance;
664 * Getter for handler instance
666 * @return $handlerInstance A Handleable instance
668 protected final function getHandlerInstance () {
669 return $this->handlerInstance;
673 * Setter for Iterator instance
675 * @param $iteratorInstance An instance of an Iterator
678 protected final function setIteratorInstance (Iterator $iteratorInstance) {
679 $this->iteratorInstance = $iteratorInstance;
683 * Getter for Iterator instance
685 * @return $iteratorInstance An instance of an Iterator
687 public final function getIteratorInstance () {
688 return $this->iteratorInstance;
692 * Setter for state instance
694 * @param $stateInstance A Stateable instance
697 public final function setStateInstance (Stateable $stateInstance) {
698 $this->stateInstance = $stateInstance;
702 * Getter for state instance
704 * @return $stateInstance A Stateable instance
706 public final function getStateInstance () {
707 return $this->stateInstance;
711 * Setter for call-back instance
713 * @param $callbackInstance An instance of a FrameworkInterface class
716 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
717 $this->callbackInstance = $callbackInstance;
721 * Getter for call-back instance
723 * @return $callbackInstance An instance of a FrameworkInterface class
725 protected final function getCallbackInstance () {
726 return $this->callbackInstance;
730 * Checks whether an object equals this object. You should overwrite this
731 * method to implement own equality checks
733 * @param $objectInstance An instance of a FrameworkInterface object
734 * @return $equals Whether both objects equals
736 public function equals (FrameworkInterface $objectInstance) {
739 $this->__toString() == $objectInstance->__toString()
741 $this->hashCode() == $objectInstance->hashCode()
749 * Generates a generic hash code of this class. You should really overwrite
750 * this method with your own hash code generator code. But keep KISS in mind.
752 * @return $hashCode A generic hash code respresenting this whole class
754 public function hashCode () {
756 return crc32($this->__toString());
760 * Appends a trailing slash to a string
762 * @param $str A string (maybe) without trailing slash
763 * @return $str A string with an auto-appended trailing slash
765 public final function addMissingTrailingSlash ($str) {
766 // Is there a trailing slash?
767 if (substr($str, -1, 1) != '/') {
771 // Return string with trailing slash
776 * Debugs this instance by putting out it's full content
778 * @param $message Optional message to show in debug output
781 public final function debugInstance ($message = '') {
782 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
783 restore_error_handler();
789 if (!empty($message)) {
791 $content = sprintf('<div class="debug_message">
793 </div>' . PHP_EOL, $message);
796 // Generate the output
797 $content .= sprintf('<pre>%s</pre>',
806 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
809 <div class="debug_content">
813 <div class="debug_include_list">
818 ClassLoader::getSelfInstance()->getPrintableIncludeList()
823 * Replaces control characters with printable output
825 * @param $str String with control characters
826 * @return $str Replaced string
828 protected function replaceControlCharacters ($str) {
831 chr(13), '[r]', str_replace(
832 chr(10), '[n]', str_replace(
842 * Output a partial stub message for the caller method
844 * @param $message An optional message to display
847 protected function partialStub ($message = '') {
849 $stubMessage = 'Partial stub!';
851 // Is an extra message given?
852 if (!empty($message)) {
853 // Then add it as well
854 $stubMessage .= ' Message: ' . $message;
857 // Debug instance is there?
858 if (!is_null($this->getDebugInstance())) {
859 // Output stub message
860 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
863 trigger_error($stubMessage);
869 * Outputs a debug backtrace and stops further script execution
871 * @param $message An optional message to output
872 * @param $doExit Whether exit the program (true is default)
875 public function debugBackTrace ($message = '', $doExit = true) {
876 // Sorry, there is no other way getting this nice backtrace
877 if (!empty($message)) {
879 printf('Message: %s<br />' . PHP_EOL, $message);
883 debug_print_backtrace();
887 if ($doExit === true) {
893 * Creates an instance of a debugger instance
895 * @param $className Name of the class (currently unsupported)
896 * @param $lineNumber Line number where the call was made
897 * @return $debugInstance An instance of a debugger class
898 * @deprecated Not fully, as the new Logger facilities are not finished yet.
900 public final static function createDebugInstance ($className, $lineNumber = NULL) {
901 // Is the instance set?
902 if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
903 // Init debug instance
904 $debugInstance = NULL;
908 // Get a debugger instance
909 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
910 } catch (NullPointerException $e) {
911 // Didn't work, no instance there
912 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
915 // Empty string should be ignored and used for testing the middleware
916 DebugMiddleware::getSelfInstance()->output('');
918 // Set it in registry
919 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
921 // Get instance from registry
922 $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
926 return $debugInstance;
930 * Simple output of a message with line-break
932 * @param $message Message to output
935 public function outputLine ($message) {
937 print($message . PHP_EOL);
941 * Outputs a debug message whether to debug instance (should be set!) or
942 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
943 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
945 * @param $message Message we shall send out...
946 * @param $doPrint Whether print or die here (default: print)
947 * @paran $stripTags Whether to strip tags (default: false)
950 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
951 // Set debug instance to NULL
952 $debugInstance = NULL;
955 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
957 // Is function partialStub/__callStatic ?
958 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
959 // Prepend class::function:line from 3rd element
960 $message = sprintf('[%s::%s:%d]: %s',
961 $backtrace[2]['class'],
962 $backtrace[2]['function'],
963 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
967 // Prepend class::function:line from 2nd element
968 $message = sprintf('[%s::%s:%d]: %s',
969 $backtrace[1]['class'],
970 $backtrace[1]['function'],
971 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
978 // Get debug instance
979 $debugInstance = $this->getDebugInstance();
980 } catch (NullPointerException $e) {
981 // The debug instance is not set (yet)
984 // Is the debug instance there?
985 if (is_object($debugInstance)) {
986 // Use debug output handler
987 $debugInstance->output($message, $stripTags);
989 if ($doPrint === false) {
990 // Die here if not printed
994 // Are debug times enabled?
995 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
997 $message = $this->getPrintableExecutionTime() . $message;
1001 if ($doPrint === true) {
1003 $this->outputLine($message);
1012 * Marks up the code by adding e.g. line numbers
1014 * @param $phpCode Unmarked PHP code
1015 * @return $markedCode Marked PHP code
1017 public function markupCode ($phpCode) {
1022 $errorArray = error_get_last();
1024 // Init the code with error message
1025 if (is_array($errorArray)) {
1027 $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>',
1028 basename($errorArray['file']),
1029 $errorArray['line'],
1030 $errorArray['message'],
1035 // Add line number to the code
1036 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1038 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1040 htmlentities($code, ENT_QUOTES)
1049 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1050 * beatiful for web-based front-ends. If null is given a message id
1051 * null_timestamp will be resolved and returned.
1053 * @param $timestamp Timestamp to prepare (filter) for display
1054 * @return $readable A readable timestamp
1056 public function doFilterFormatTimestamp ($timestamp) {
1057 // Default value to return
1060 // Is the timestamp null?
1061 if (is_null($timestamp)) {
1062 // Get a message string
1063 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1065 switch ($this->getLanguageInstance()->getLanguageCode()) {
1066 case 'de': // German format is a bit different to default
1067 // Split the GMT stamp up
1068 $dateTime = explode(' ', $timestamp );
1069 $dateArray = explode('-', $dateTime[0]);
1070 $timeArray = explode(':', $dateTime[1]);
1072 // Construct the timestamp
1073 $readable = sprintf(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('german_date_time'),
1083 default: // Default is pass-through
1084 $readable = $timestamp;
1094 * Filter a given number into a localized number
1096 * @param $value The raw value from e.g. database
1097 * @return $localized Localized value
1099 public function doFilterFormatNumber ($value) {
1100 // Generate it from config and localize dependencies
1101 switch ($this->getLanguageInstance()->getLanguageCode()) {
1102 case 'de': // German format is a bit different to default
1103 $localized = number_format($value, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('decimals'), ',', '.');
1106 default: // US, etc.
1107 $localized = number_format($value, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('decimals'), '.', ',');
1116 * "Getter" for databse entry
1118 * @return $entry An array with database entries
1119 * @throws NullPointerException If the database result is not found
1120 * @throws InvalidDatabaseResultException If the database result is invalid
1122 protected final function getDatabaseEntry () {
1123 // Is there an instance?
1124 if (!$this->getResultInstance() instanceof SearchableResult) {
1125 // Throw an exception here
1126 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1130 $this->getResultInstance()->rewind();
1132 // Do we have an entry?
1133 if ($this->getResultInstance()->valid() === false) {
1134 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
1135 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1139 $this->getResultInstance()->next();
1142 $entry = $this->getResultInstance()->current();
1149 * Getter for field name
1151 * @param $fieldName Field name which we shall get
1152 * @return $fieldValue Field value from the user
1153 * @throws NullPointerException If the result instance is null
1155 public final function getField (string $fieldName) {
1156 // Default field value
1159 // Get result instance
1160 $resultInstance = $this->getResultInstance();
1162 // Is this instance null?
1163 if (is_null($resultInstance)) {
1164 // Then the user instance is no longer valid (expired cookies?)
1165 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1168 // Get current array
1169 $fieldArray = $resultInstance->current();
1170 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1172 // Convert dashes to underscore
1173 $fieldName2 = StringUtils::convertDashesToUnderscores($fieldName);
1175 // Does the field exist?
1176 if ($this->isFieldSet($fieldName)) {
1178 $fieldValue = $fieldArray[$fieldName2];
1179 } elseif (defined('DEVELOPER')) {
1180 // Missing field entry, may require debugging
1181 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
1183 // Missing field entry, may require debugging
1184 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
1192 * Checks if given field is set
1194 * @param $fieldName Field name to check
1195 * @return $isSet Whether the given field name is set
1196 * @throws NullPointerException If the result instance is null
1198 public function isFieldSet (string $fieldName) {
1199 // Get result instance
1200 $resultInstance = $this->getResultInstance();
1202 // Is this instance null?
1203 if (is_null($resultInstance)) {
1204 // Then the user instance is no longer valid (expired cookies?)
1205 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1208 // Get current array
1209 $fieldArray = $resultInstance->current();
1210 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
1212 // Convert dashes to underscore
1213 $fieldName = StringUtils::convertDashesToUnderscores($fieldName);
1216 $isSet = isset($fieldArray[$fieldName]);
1223 * Flushs all pending updates to the database layer
1227 public function flushPendingUpdates () {
1228 // Get result instance
1229 $resultInstance = $this->getResultInstance();
1231 // Do we have data to update?
1232 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1233 // Get wrapper class name config entry
1234 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1236 // Create object instance
1237 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
1239 // Yes, then send the whole result to the database layer
1240 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1245 * Outputs a deprecation warning to the developer.
1247 * @param $message The message we shall output to the developer
1249 * @todo Write a logging mechanism for productive mode
1251 public function deprecationWarning ($message) {
1252 // Is developer mode active?
1253 if (defined('DEVELOPER')) {
1254 // Debug instance is there?
1255 if (!is_null($this->getDebugInstance())) {
1256 // Output stub message
1257 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
1260 trigger_error($message . "<br />\n");
1264 // @TODO Finish this part!
1265 $this->partialStub('Developer mode inactive. Message:' . $message);
1270 * Checks whether the given PHP extension is loaded
1272 * @param $phpExtension The PHP extension we shall check
1273 * @return $isLoaded Whether the PHP extension is loaded
1275 public final function isPhpExtensionLoaded ($phpExtension) {
1277 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1284 * "Getter" as a time() replacement but with milliseconds. You should use this
1285 * method instead of the encapsulated getimeofday() function.
1287 * @return $milliTime Timestamp with milliseconds
1289 public function getMilliTime () {
1290 // Get the time of day as float
1291 $milliTime = gettimeofday(true);
1298 * Idles (sleeps) for given milliseconds
1300 * @return $hasSlept Whether it goes fine
1302 public function idle ($milliSeconds) {
1303 // Sleep is fine by default
1306 // Idle so long with found function
1307 if (function_exists('time_sleep_until')) {
1308 // Get current time and add idle time
1309 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1311 // New PHP 5.1.0 function found, ignore errors
1312 $hasSlept = @time_sleep_until($sleepUntil);
1315 * My Sun station doesn't have that function even with latest PHP
1318 usleep($milliSeconds * 1000);
1326 * Checks whether the given encoded data was encoded with Base64
1328 * @param $encodedData Encoded data we shall check
1329 * @return $isBase64 Whether the encoded data is Base64
1331 protected function isBase64Encoded ($encodedData) {
1333 $isBase64 = (@base64_decode($encodedData, true) !== false);
1340 * Gets a cache key from Criteria instance
1342 * @param $criteriaInstance An instance of a Criteria class
1343 * @param $onlyKeys Only use these keys for a cache key
1344 * @return $cacheKey A cache key suitable for lookup/storage purposes
1346 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
1348 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: criteriaInstance=' . $criteriaInstance->__toString() . ',onlyKeys()=' . count($onlyKeys) . ' - CALLED!');
1349 $cacheKey = sprintf('%s@%s',
1350 $this->__toString(),
1351 $criteriaInstance->getCacheKey($onlyKeys)
1355 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: cacheKey=' . $cacheKey . ' - EXIT!');
1360 * Getter for startup time in miliseconds
1362 * @return $startupTime Startup time in miliseconds
1364 protected function getStartupTime () {
1365 return self::$startupTime;
1369 * "Getter" for a printable currently execution time in nice braces
1371 * @return $executionTime Current execution time in nice braces
1373 protected function getPrintableExecutionTime () {
1374 // Caculate the execution time
1375 $executionTime = microtime(true) - $this->getStartupTime();
1377 // Pack it in nice braces
1378 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
1381 return $executionTime;
1385 * Hashes a given string with a simple but stronger hash function (no salt)
1386 * and hex-encode it.
1388 * @param $str The string to be hashed
1389 * @return $hash The hash from string $str
1391 public static final function hash ($str) {
1392 // Hash given string with (better secure) hasher
1393 $hash = bin2hex(mhash(MHASH_SHA256, $str));
1400 * "Getter" for length of hash() output. This will be "cached" to speed up
1403 * @return $length Length of hash() output
1405 public static final function getHashLength () {
1407 if (is_null(self::$hashLength)) {
1408 // No, then hash a string and save its length.
1409 self::$hashLength = strlen(self::hash('abc123'));
1413 return self::$hashLength;
1417 * Checks whether the given number is really a number (only chars 0-9).
1419 * @param $num A string consisting only chars between 0 and 9
1420 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
1421 * @param $assertMismatch Whether to assert mismatches
1422 * @return $ret The (hopefully) secured numbered value
1424 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
1425 // Filter all numbers out
1426 $ret = preg_replace('/[^0123456789]/', '', $num);
1429 if ($castValue === true) {
1430 // Cast to biggest numeric type
1431 $ret = (double) $ret;
1434 // Assert only if requested
1435 if ($assertMismatch === true) {
1436 // Has the whole value changed?
1437 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
1445 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
1447 * @param $num A string consisting only chars between 0 and 9
1448 * @param $assertMismatch Whether to assert mismatches
1449 * @return $ret The (hopefully) secured hext-numbered value
1451 public function hexval ($num, $assertMismatch = false) {
1452 // Filter all numbers out
1453 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
1455 // Assert only if requested
1456 if ($assertMismatch === true) {
1457 // Has the whole value changed?
1458 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
1466 * Determines if an element is set in the generic array
1468 * @param $keyGroup Main group for the key
1469 * @param $subGroup Sub group for the key
1470 * @param $key Key to check
1471 * @param $element Element to check
1472 * @return $isset Whether the given key is set
1474 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
1476 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
1479 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
1485 * Determines if a key is set in the generic array
1487 * @param $keyGroup Main group for the key
1488 * @param $subGroup Sub group for the key
1489 * @param $key Key to check
1490 * @return $isset Whether the given key is set
1492 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
1494 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1497 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
1505 * Determines if a group is set in the generic array
1507 * @param $keyGroup Main group
1508 * @param $subGroup Sub group
1509 * @return $isset Whether the given group is set
1511 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
1513 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
1516 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
1523 * Getter for sub key group
1525 * @param $keyGroup Main key group
1526 * @param $subGroup Sub key group
1527 * @return $array An array with all array elements
1529 protected final function getGenericSubArray ($keyGroup, $subGroup) {
1531 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
1532 // No, then abort here
1533 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
1538 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
1541 return $this->genericArray[$keyGroup][$subGroup];
1545 * Unsets a given key in generic array
1547 * @param $keyGroup Main group for the key
1548 * @param $subGroup Sub group for the key
1549 * @param $key Key to unset
1552 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
1554 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1557 unset($this->genericArray[$keyGroup][$subGroup][$key]);
1561 * Unsets a given element in generic array
1563 * @param $keyGroup Main group for the key
1564 * @param $subGroup Sub group for the key
1565 * @param $key Key to unset
1566 * @param $element Element to unset
1569 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
1571 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
1574 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
1578 * Append a string to a given generic array key
1580 * @param $keyGroup Main group for the key
1581 * @param $subGroup Sub group for the key
1582 * @param $key Key to unset
1583 * @param $value Value to add/append
1586 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
1588 //* 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);
1590 // Is it already there?
1591 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1593 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
1596 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
1601 * Append a string to a given generic array element
1603 * @param $keyGroup Main group for the key
1604 * @param $subGroup Sub group for the key
1605 * @param $key Key to unset
1606 * @param $element Element to check
1607 * @param $value Value to add/append
1610 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
1612 //* 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);
1614 // Is it already there?
1615 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
1617 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
1620 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
1625 * Sets a string in a given generic array element
1627 * @param $keyGroup Main group for the key
1628 * @param $subGroup Sub group for the key
1629 * @param $key Key to unset
1630 * @param $element Element to check
1631 * @param $value Value to add/append
1634 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
1636 //* 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);
1639 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
1643 * Initializes given generic array group
1645 * @param $keyGroup Main group for the key
1646 * @param $subGroup Sub group for the key
1647 * @param $key Key to use
1648 * @param $forceInit Optionally force initialization
1651 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
1653 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
1655 // Is it already set?
1656 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
1657 // Already initialized
1658 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
1663 $this->genericArray[$keyGroup][$subGroup] = array();
1667 * Initializes given generic array key
1669 * @param $keyGroup Main group for the key
1670 * @param $subGroup Sub group for the key
1671 * @param $key Key to use
1672 * @param $forceInit Optionally force initialization
1675 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
1677 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
1679 // Is it already set?
1680 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
1681 // Already initialized
1682 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
1687 $this->genericArray[$keyGroup][$subGroup][$key] = array();
1691 * Initializes given generic array element
1693 * @param $keyGroup Main group for the key
1694 * @param $subGroup Sub group for the key
1695 * @param $key Key to use
1696 * @param $element Element to use
1697 * @param $forceInit Optionally force initialization
1700 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
1702 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
1704 // Is it already set?
1705 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
1706 // Already initialized
1707 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
1712 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
1716 * Pushes an element to a generic key
1718 * @param $keyGroup Main group for the key
1719 * @param $subGroup Sub group for the key
1720 * @param $key Key to use
1721 * @param $value Value to add/append
1722 * @return $count Number of array elements
1724 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
1726 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
1729 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1731 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
1735 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
1738 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
1739 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
1744 * Pushes an element to a generic array element
1746 * @param $keyGroup Main group for the key
1747 * @param $subGroup Sub group for the key
1748 * @param $key Key to use
1749 * @param $element Element to check
1750 * @param $value Value to add/append
1751 * @return $count Number of array elements
1753 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
1755 //* 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));
1758 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
1760 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
1764 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
1767 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
1768 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
1773 * Pops an element from a generic group
1775 * @param $keyGroup Main group for the key
1776 * @param $subGroup Sub group for the key
1777 * @param $key Key to unset
1778 * @return $value Last "popped" value
1780 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
1782 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1785 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1787 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
1792 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
1795 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
1796 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
1801 * Shifts an element from a generic group
1803 * @param $keyGroup Main group for the key
1804 * @param $subGroup Sub group for the key
1805 * @param $key Key to unset
1806 * @return $value Last "popped" value
1808 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
1810 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1813 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1815 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
1820 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
1823 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
1824 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
1829 * Count generic array group
1831 * @param $keyGroup Main group for the key
1832 * @return $count Count of given group
1834 protected final function countGenericArray ($keyGroup) {
1836 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
1839 if (!isset($this->genericArray[$keyGroup])) {
1841 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
1846 $count = count($this->genericArray[$keyGroup]);
1849 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
1856 * Count generic array sub group
1858 * @param $keyGroup Main group for the key
1859 * @param $subGroup Sub group for the key
1860 * @return $count Count of given group
1862 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
1864 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
1867 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
1869 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
1874 $count = count($this->genericArray[$keyGroup][$subGroup]);
1877 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
1884 * Count generic array elements
1886 * @param $keyGroup Main group for the key
1887 * @param $subGroup Sub group for the key
1888 * @para $key Key to count
1889 * @return $count Count of given key
1891 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
1893 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1896 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1898 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
1900 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
1902 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
1907 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
1910 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
1917 * Getter for whole generic group array
1919 * @param $keyGroup Key group to get
1920 * @return $array Whole generic array group
1922 protected final function getGenericArray ($keyGroup) {
1924 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
1927 if (!isset($this->genericArray[$keyGroup])) {
1929 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
1934 return $this->genericArray[$keyGroup];
1938 * Setter for generic array key
1940 * @param $keyGroup Key group to get
1941 * @param $subGroup Sub group for the key
1942 * @param $key Key to unset
1943 * @param $value Mixed value from generic array element
1946 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
1948 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
1951 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
1955 * Getter for generic array key
1957 * @param $keyGroup Key group to get
1958 * @param $subGroup Sub group for the key
1959 * @param $key Key to unset
1960 * @return $value Mixed value from generic array element
1962 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
1964 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1967 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1969 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
1974 return $this->genericArray[$keyGroup][$subGroup][$key];
1978 * Sets a value in given generic array key/element
1980 * @param $keyGroup Main group for the key
1981 * @param $subGroup Sub group for the key
1982 * @param $key Key to set
1983 * @param $element Element to set
1984 * @param $value Value to set
1987 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
1989 //* 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));
1992 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
1996 * Getter for generic array element
1998 * @param $keyGroup Key group to get
1999 * @param $subGroup Sub group for the key
2000 * @param $key Key to look for
2001 * @param $element Element to look for
2002 * @return $value Mixed value from generic array element
2004 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2006 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2009 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2011 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2016 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2020 * Checks if a given sub group is valid (array)
2022 * @param $keyGroup Key group to get
2023 * @param $subGroup Sub group for the key
2024 * @return $isValid Whether given sub group is valid
2026 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2028 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2031 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
2038 * Checks if a given key is valid (array)
2040 * @param $keyGroup Key group to get
2041 * @param $subGroup Sub group for the key
2042 * @param $key Key to check
2043 * @return $isValid Whether given sub group is valid
2045 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
2047 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2050 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
2057 * Initializes the web output instance
2061 protected function initWebOutputInstance () {
2062 // Get application instance
2063 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
2065 // Init web output instance
2066 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
2069 $this->setWebOutputInstance($outputInstance);
2073 * Translates boolean true to 'Y' and false to 'N'
2075 * @param $boolean Boolean value
2076 * @return $translated Translated boolean value
2078 public static final function translateBooleanToYesNo (bool $boolean) {
2079 // Make sure it is really boolean
2080 assert(is_bool($boolean));
2083 $translated = ($boolean === true) ? 'Y' : 'N';
2085 // ... and return it
2090 * Creates a full-qualified file name (FQFN) for given file name by adding
2091 * a configured temporary file path to it.
2093 * @param $infoInstance An instance of a SplFileInfo class
2094 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
2095 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
2096 * @throws FileIoException If the file cannot be written
2098 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
2100 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
2102 // Is the path writeable?
2103 if (!is_writable($basePath)) {
2104 // Path is write-protected
2105 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
2109 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
2112 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
2114 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
2118 return $tempInstance;
2122 * "Getter" for a printable state name
2124 * @return $stateName Name of the node's state in a printable format
2126 public final function getPrintableState () {
2127 // Default is 'null'
2128 $stateName = 'null';
2130 // Get the state instance
2131 $stateInstance = $this->getStateInstance();
2133 // Is it an instance of Stateable?
2134 if ($stateInstance instanceof Stateable) {
2135 // Then use that state name
2136 $stateName = $stateInstance->getStateName();