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\Criteria\Local\LocalSearchCriteria;
9 use Org\Mxchange\CoreFramework\Criteria\Local\LocalUpdateCriteria;
10 use Org\Mxchange\CoreFramework\Crypto\Cryptable;
11 use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
12 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
13 use Org\Mxchange\CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
14 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
15 use Org\Mxchange\CoreFramework\Filesystem\PathWriteProtectedException;
16 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
17 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
18 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
19 use Org\Mxchange\CoreFramework\Handler\Handleable;
20 use Org\Mxchange\CoreFramework\Helper\Helper;
21 use Org\Mxchange\CoreFramework\Loader\ClassLoader;
22 use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
23 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
24 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
25 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
26 use Org\Mxchange\CoreFramework\Result\Database\CachedDatabaseResult;
27 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
28 use Org\Mxchange\CoreFramework\State\Stateable;
29 use Org\Mxchange\CoreFramework\Stream\Input\InputStream;
30 use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
31 use Org\Mxchange\CoreFramework\Stream\Output\OutputStream;
32 use Org\Mxchange\CoreFramework\User\ManageableAccount;
33 use Org\Mxchange\CoreFramework\Utils\String\StringUtils;
37 use \InvalidArgumentException;
43 * The simulator system class is the super class of all other classes. This
44 * class handles saving of games etc.
46 * @author Roland Haeder <webmaster@shipsimu.org>
48 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
49 * @license GNU GPL 3.0 or any newer version
50 * @link http://www.shipsimu.org
52 * This program is free software: you can redistribute it and/or modify
53 * it under the terms of the GNU General Public License as published by
54 * the Free Software Foundation, either version 3 of the License, or
55 * (at your option) any later version.
57 * This program is distributed in the hope that it will be useful,
58 * but WITHOUT ANY WARRANTY; without even the implied warranty of
59 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
60 * GNU General Public License for more details.
62 * You should have received a copy of the GNU General Public License
63 * along with this program. If not, see <http://www.gnu.org/licenses/>.
65 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
67 * Length of output from hash()
69 private static $hashLength = NULL;
72 * Self-referencing instance
74 private static $instance = NULL;
79 private $realClass = __CLASS__;
82 * Search criteria instance
84 private $searchInstance = NULL;
87 * Update criteria instance
89 private $updateInstance = NULL;
92 * Database result instance
94 private $resultInstance = NULL;
97 * Instance for user class
99 private $userInstance = NULL;
102 * Instance of a crypto helper
104 private $cryptoInstance = NULL;
107 * Instance of an Iterator class
109 private $iteratorInstance = NULL;
112 * A helper instance for the form
114 private $helperInstance = NULL;
117 * An instance of a InputStream class
119 private $inputStreamInstance = NULL;
122 * An instance of a OutputStream class
124 private $outputStreamInstance = NULL;
129 private $handlerInstance = NULL;
132 * An instance of a database wrapper class
134 private $wrapperInstance = NULL;
139 private $stateInstance = NULL;
144 private $callbackInstance = NULL;
149 private $genericArray = array();
151 /***********************
152 * Exception codes.... *
153 ***********************/
155 // @todo Try to clean these constants up
156 const EXCEPTION_IS_NULL_POINTER = 0x001;
157 const EXCEPTION_IS_NO_OBJECT = 0x002;
158 const EXCEPTION_IS_NO_ARRAY = 0x003;
159 const EXCEPTION_MISSING_METHOD = 0x004;
160 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
161 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
162 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
163 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
164 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
165 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
166 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
167 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
168 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
169 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
170 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
171 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
172 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
173 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
174 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
175 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
176 const EXCEPTION_PATH_NOT_FOUND = 0x015;
177 const EXCEPTION_INVALID_PATH_NAME = 0x016;
178 const EXCEPTION_READ_PROTECED_PATH = 0x017;
179 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
180 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
181 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
182 const EXCEPTION_INVALID_RESOURCE = 0x01b;
183 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
184 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
185 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
186 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
187 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
188 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
189 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
190 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
191 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
192 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
193 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
194 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
195 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
196 const EXCEPTION_INVALID_STRING = 0x029;
197 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
198 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
199 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
200 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
201 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
202 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
203 const EXCEPTION_MISSING_ELEMENT = 0x030;
204 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
205 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
206 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
207 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
208 const EXCEPTION_FATAL_ERROR = 0x035;
209 const EXCEPTION_FILE_NOT_FOUND = 0x036;
210 const EXCEPTION_ASSERTION_FAILED = 0x037;
211 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
212 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
213 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
214 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
215 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
216 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
217 const EXCEPTION_INVALID_SOCKET = 0x03e;
218 const EXCEPTION_SELF_INSTANCE = 0x03f;
221 * Startup time in miliseconds
223 private static $startupTime = 0;
226 * Protected super constructor
228 * @param $className Name of the class
231 protected function __construct (string $className) {
233 $this->setRealClass($className);
235 // Is the startup time set? (0 cannot be true anymore)
236 if (self::$startupTime == 0) {
238 self::$startupTime = microtime(true);
243 * Destructor for all classes. You should not call this method on your own.
247 public function __destruct () {
248 // Flush any updated entries to the database
249 $this->flushPendingUpdates();
251 // Is this object already destroyed?
252 if ($this->__toString() != 'DestructedObject') {
253 // Destroy all informations about this class but keep some text about it alive
254 $this->setRealClass('DestructedObject');
255 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
256 // Already destructed object
257 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
261 // Do not call this twice
262 trigger_error(__METHOD__ . ': Called twice.');
268 * The __call() method where all non-implemented methods end up
270 * @param $methodName Name of the missing method
271 * @args $args Arguments passed to the method
274 public final function __call ($methodName, $args) {
276 self::$instance = $this;
278 // Call static method
279 self::__callStatic($methodName, $args);
281 // Clear self-instance
282 self::$instance = NULL;
286 * The __callStatic() method where all non-implemented static methods end up
288 * @param $methodName Name of the missing method
289 * @param $args Arguments passed to the method
291 * @throws InvalidArgumentException If self::$instance is not a framework's own object
293 public static final function __callStatic ($methodName, $args) {
295 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
297 // Init argument string and class name
299 $className = 'unknown';
301 // Is self-instance set?
302 if (self::$instance instanceof FrameworkInterface) {
303 // Framework's own instance
304 $className = self::$instance->__toString();
305 } elseif (!is_null(self::$instance)) {
307 throw new InvalidArgumentException(sprintf('self::instance[%s] is not expected.', gettype(self::$instance)), self::EXCEPTION_SELF_INSTANCE);
310 // Is it NULL, empty or an array?
311 if (is_null($args)) {
313 $argsString = 'NULL';
314 } elseif (is_array($args)) {
318 // Some arguments are there
319 foreach ($args as $arg) {
320 // Add data about the argument
321 $argsString .= gettype($arg) . ':';
324 // Found a NULL argument
325 $argsString .= 'NULL';
326 } elseif (is_string($arg)) {
327 // Add length for strings
328 $argsString .= strlen($arg);
329 } elseif ((is_int($arg)) || (is_float($arg))) {
332 } elseif (is_array($arg)) {
333 // .. or size if array
334 $argsString .= count($arg);
335 } elseif (is_object($arg)) {
337 $reflection = new ReflectionClass($arg);
339 // Is an other object, maybe no __toString() available
340 $argsString .= $reflection->getName();
341 } elseif ($arg === true) {
342 // ... is boolean 'true'
343 $argsString .= 'true';
344 } elseif ($arg === false) {
345 // ... is boolean 'false'
346 $argsString .= 'false';
349 // Comma for next one
354 if (substr($argsString, -2, 1) == ',') {
356 $argsString = substr($argsString, 0, -2);
362 // Invalid arguments!
363 $argsString = sprintf('!INVALID:%s!', gettype($args));
366 // Output stub message
367 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
368 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s::%s]: Stub! Args: %s',
379 * Getter for $realClass
381 * @return $realClass The name of the real class (not BaseFrameworkSystem)
383 public function __toString () {
384 return $this->realClass;
388 * Magic method to catch setting of missing but set class fields/attributes
390 * @param $name Name of the field/attribute
391 * @param $value Value to store
394 public final function __set ($name, $value) {
395 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
398 print_r($value, true)
403 * Magic method to catch getting of missing fields/attributes
405 * @param $name Name of the field/attribute
408 public final function __get ($name) {
409 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
415 * Magic method to catch unsetting of missing fields/attributes
417 * @param $name Name of the field/attribute
420 public final function __unset ($name) {
421 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
427 * Magic method to catch object serialization
429 * @return $unsupported Unsupported method
430 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
432 public final function __sleep () {
433 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
437 * Magic method to catch object deserialization
439 * @return $unsupported Unsupported method
440 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
442 public final function __wakeup () {
443 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
447 * Magic method to catch calls when an object instance is called
449 * @return $unsupported Unsupported method
450 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
452 public final function __invoke () {
453 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
457 * Setter for the real class name
459 * @param $realClass Class name (string)
462 public final function setRealClass ($realClass) {
464 $this->realClass = (string) $realClass;
468 * Setter for database result instance
470 * @param $resultInstance An instance of a database result class
472 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
474 protected final function setResultInstance (SearchableResult $resultInstance) {
475 $this->resultInstance = $resultInstance;
479 * Getter for database result instance
481 * @return $resultInstance An instance of a database result class
483 public final function getResultInstance () {
484 return $this->resultInstance;
488 * Setter for search instance
490 * @param $searchInstance Searchable criteria instance
493 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
494 $this->searchInstance = $searchInstance;
498 * Getter for search instance
500 * @return $searchInstance Searchable criteria instance
502 public final function getSearchInstance () {
503 return $this->searchInstance;
507 * Setter for update instance
509 * @param $updateInstance An instance of a LocalUpdateCriteria clase
512 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
513 $this->updateInstance = $updateInstance;
517 * Getter for update instance
519 * @return $updateInstance Updateable criteria instance
521 public final function getUpdateInstance () {
522 return $this->updateInstance;
526 * Setter for debug instance
528 * @param $debugInstance The instance for debug output class
531 public final function setDebugInstance (DebugMiddleware $debugInstance) {
532 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
536 * Getter for debug instance
538 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
540 public final function getDebugInstance () {
541 // Get debug instance
542 $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
545 return $debugInstance;
549 * Setter for web output instance
551 * @param $webInstance The instance for web output class
554 public final function setWebOutputInstance (OutputStreamer $webInstance) {
555 GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
559 * Getter for web output instance
561 * @return $webOutputInstance - Instance to class WebOutput
563 public final function getWebOutputInstance () {
564 $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
565 return $webOutputInstance;
569 * Private getter for language instance
571 * @return $langInstance An instance to the language sub-system
573 protected final function getLanguageInstance () {
574 $langInstance = GenericRegistry::getRegistry()->getInstance('language');
575 return $langInstance;
579 * Setter for language instance
581 * @param $langInstance An instance to the language sub-system
583 * @see LanguageSystem
585 public final function setLanguageInstance (ManageableLanguage $langInstance) {
586 GenericRegistry::getRegistry()->addInstance('language', $langInstance);
590 * Protected setter for user instance
592 * @param $userInstance An instance of a user class
595 protected final function setUserInstance (ManageableAccount $userInstance) {
596 $this->userInstance = $userInstance;
600 * Getter for user instance
602 * @return $userInstance An instance of a user class
604 public final function getUserInstance () {
605 return $this->userInstance;
609 * Setter for Cryptable instance
611 * @param $cryptoInstance An instance of a Cryptable class
614 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
615 $this->cryptoInstance = $cryptoInstance;
619 * Getter for Cryptable instance
621 * @return $cryptoInstance An instance of a Cryptable class
623 public final function getCryptoInstance () {
624 return $this->cryptoInstance;
628 * Setter for DatabaseWrapper instance
630 * @param $wrapperInstance An instance of an DatabaseWrapper
633 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
634 $this->wrapperInstance = $wrapperInstance;
638 * Getter for DatabaseWrapper instance
640 * @return $wrapperInstance An instance of an DatabaseWrapper
642 public final function getWrapperInstance () {
643 return $this->wrapperInstance;
647 * Setter for helper instance
649 * @param $helperInstance An instance of a helper class
652 protected final function setHelperInstance (Helper $helperInstance) {
653 $this->helperInstance = $helperInstance;
657 * Getter for helper instance
659 * @return $helperInstance An instance of a helper class
661 public final function getHelperInstance () {
662 return $this->helperInstance;
666 * Getter for a InputStream instance
668 * @param $inputStreamInstance The InputStream instance
670 protected final function getInputStreamInstance () {
671 return $this->inputStreamInstance;
675 * Setter for a InputStream instance
677 * @param $inputStreamInstance The InputStream instance
680 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
681 $this->inputStreamInstance = $inputStreamInstance;
685 * Getter for a OutputStream instance
687 * @param $outputStreamInstance The OutputStream instance
689 protected final function getOutputStreamInstance () {
690 return $this->outputStreamInstance;
694 * Setter for a OutputStream instance
696 * @param $outputStreamInstance The OutputStream instance
699 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
700 $this->outputStreamInstance = $outputStreamInstance;
704 * Setter for handler instance
706 * @param $handlerInstance An instance of a Handleable class
709 protected final function setHandlerInstance (Handleable $handlerInstance) {
710 $this->handlerInstance = $handlerInstance;
714 * Getter for handler instance
716 * @return $handlerInstance A Handleable instance
718 protected final function getHandlerInstance () {
719 return $this->handlerInstance;
723 * Setter for Iterator instance
725 * @param $iteratorInstance An instance of an Iterator
728 protected final function setIteratorInstance (Iterator $iteratorInstance) {
729 $this->iteratorInstance = $iteratorInstance;
733 * Getter for Iterator instance
735 * @return $iteratorInstance An instance of an Iterator
737 public final function getIteratorInstance () {
738 return $this->iteratorInstance;
742 * Setter for state instance
744 * @param $stateInstance A Stateable instance
747 public final function setStateInstance (Stateable $stateInstance) {
748 $this->stateInstance = $stateInstance;
752 * Getter for state instance
754 * @return $stateInstance A Stateable instance
756 public final function getStateInstance () {
757 return $this->stateInstance;
761 * Setter for call-back instance
763 * @param $callbackInstance An instance of a FrameworkInterface class
766 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
767 $this->callbackInstance = $callbackInstance;
771 * Getter for call-back instance
773 * @return $callbackInstance An instance of a FrameworkInterface class
775 protected final function getCallbackInstance () {
776 return $this->callbackInstance;
780 * Checks whether an object equals this object. You should overwrite this
781 * method to implement own equality checks
783 * @param $objectInstance An instance of a FrameworkInterface object
784 * @return $equals Whether both objects equals
786 public function equals (FrameworkInterface $objectInstance) {
789 $this->__toString() == $objectInstance->__toString()
791 $this->hashCode() == $objectInstance->hashCode()
799 * Generates a generic hash code of this class. You should really overwrite
800 * this method with your own hash code generator code. But keep KISS in mind.
802 * @return $hashCode A generic hash code respresenting this whole class
804 public function hashCode () {
806 return crc32($this->__toString());
810 * Appends a trailing slash to a string
812 * @param $str A string (maybe) without trailing slash
813 * @return $str A string with an auto-appended trailing slash
815 public final function addMissingTrailingSlash ($str) {
816 // Is there a trailing slash?
817 if (substr($str, -1, 1) != '/') {
821 // Return string with trailing slash
826 * Debugs this instance by putting out it's full content
828 * @param $message Optional message to show in debug output
831 public final function debugInstance ($message = '') {
832 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
833 restore_error_handler();
839 if (!empty($message)) {
841 $content = sprintf('<div class="debug_message">
843 </div>' . PHP_EOL, $message);
846 // Generate the output
847 $content .= sprintf('<pre>%s</pre>',
856 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
859 <div class="debug_content">
863 <div class="debug_include_list">
868 ClassLoader::getSelfInstance()->getPrintableIncludeList()
873 * Replaces control characters with printable output
875 * @param $str String with control characters
876 * @return $str Replaced string
878 protected function replaceControlCharacters ($str) {
881 chr(13), '[r]', str_replace(
882 chr(10), '[n]', str_replace(
892 * Output a partial stub message for the caller method
894 * @param $message An optional message to display
897 protected function partialStub ($message = '') {
899 $stubMessage = 'Partial stub!';
901 // Is an extra message given?
902 if (!empty($message)) {
903 // Then add it as well
904 $stubMessage .= ' Message: ' . $message;
907 // Debug instance is there?
908 if (!is_null($this->getDebugInstance())) {
909 // Output stub message
910 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
913 trigger_error($stubMessage);
919 * Outputs a debug backtrace and stops further script execution
921 * @param $message An optional message to output
922 * @param $doExit Whether exit the program (true is default)
925 public function debugBackTrace ($message = '', $doExit = true) {
926 // Sorry, there is no other way getting this nice backtrace
927 if (!empty($message)) {
929 printf('Message: %s<br />' . PHP_EOL, $message);
933 debug_print_backtrace();
937 if ($doExit === true) {
943 * Creates an instance of a debugger instance
945 * @param $className Name of the class (currently unsupported)
946 * @param $lineNumber Line number where the call was made
947 * @return $debugInstance An instance of a debugger class
948 * @deprecated Not fully, as the new Logger facilities are not finished yet.
950 public final static function createDebugInstance ($className, $lineNumber = NULL) {
951 // Is the instance set?
952 if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
953 // Init debug instance
954 $debugInstance = NULL;
958 // Get a debugger instance
959 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
960 } catch (NullPointerException $e) {
961 // Didn't work, no instance there
962 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
965 // Empty string should be ignored and used for testing the middleware
966 DebugMiddleware::getSelfInstance()->output('');
968 // Set it in registry
969 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
971 // Get instance from registry
972 $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
976 return $debugInstance;
980 * Simple output of a message with line-break
982 * @param $message Message to output
985 public function outputLine ($message) {
987 print($message . PHP_EOL);
991 * Outputs a debug message whether to debug instance (should be set!) or
992 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
993 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
995 * @param $message Message we shall send out...
996 * @param $doPrint Whether print or die here (default: print)
997 * @paran $stripTags Whether to strip tags (default: false)
1000 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1001 // Set debug instance to NULL
1002 $debugInstance = NULL;
1005 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1007 // Is function partialStub/__callStatic ?
1008 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1009 // Prepend class::function:line from 3rd element
1010 $message = sprintf('[%s::%s:%d]: %s',
1011 $backtrace[2]['class'],
1012 $backtrace[2]['function'],
1013 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1017 // Prepend class::function:line from 2nd element
1018 $message = sprintf('[%s::%s:%d]: %s',
1019 $backtrace[1]['class'],
1020 $backtrace[1]['function'],
1021 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1028 // Get debug instance
1029 $debugInstance = $this->getDebugInstance();
1030 } catch (NullPointerException $e) {
1031 // The debug instance is not set (yet)
1034 // Is the debug instance there?
1035 if (is_object($debugInstance)) {
1036 // Use debug output handler
1037 $debugInstance->output($message, $stripTags);
1039 if ($doPrint === false) {
1040 // Die here if not printed
1044 // Are debug times enabled?
1045 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1047 $message = $this->getPrintableExecutionTime() . $message;
1051 if ($doPrint === true) {
1053 $this->outputLine($message);
1062 * Marks up the code by adding e.g. line numbers
1064 * @param $phpCode Unmarked PHP code
1065 * @return $markedCode Marked PHP code
1067 public function markupCode ($phpCode) {
1072 $errorArray = error_get_last();
1074 // Init the code with error message
1075 if (is_array($errorArray)) {
1077 $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>',
1078 basename($errorArray['file']),
1079 $errorArray['line'],
1080 $errorArray['message'],
1085 // Add line number to the code
1086 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1088 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1090 htmlentities($code, ENT_QUOTES)
1099 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1100 * beatiful for web-based front-ends. If null is given a message id
1101 * null_timestamp will be resolved and returned.
1103 * @param $timestamp Timestamp to prepare (filter) for display
1104 * @return $readable A readable timestamp
1106 public function doFilterFormatTimestamp ($timestamp) {
1107 // Default value to return
1110 // Is the timestamp null?
1111 if (is_null($timestamp)) {
1112 // Get a message string
1113 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1115 switch ($this->getLanguageInstance()->getLanguageCode()) {
1116 case 'de': // German format is a bit different to default
1117 // Split the GMT stamp up
1118 $dateTime = explode(' ', $timestamp );
1119 $dateArray = explode('-', $dateTime[0]);
1120 $timeArray = explode(':', $dateTime[1]);
1122 // Construct the timestamp
1123 $readable = sprintf(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('german_date_time'),
1133 default: // Default is pass-through
1134 $readable = $timestamp;
1144 * Filter a given number into a localized number
1146 * @param $value The raw value from e.g. database
1147 * @return $localized Localized value
1149 public function doFilterFormatNumber ($value) {
1150 // Generate it from config and localize dependencies
1151 switch ($this->getLanguageInstance()->getLanguageCode()) {
1152 case 'de': // German format is a bit different to default
1153 $localized = number_format($value, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('decimals'), ',', '.');
1156 default: // US, etc.
1157 $localized = number_format($value, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('decimals'), '.', ',');
1166 * "Getter" for databse entry
1168 * @return $entry An array with database entries
1169 * @throws NullPointerException If the database result is not found
1170 * @throws InvalidDatabaseResultException If the database result is invalid
1172 protected final function getDatabaseEntry () {
1173 // Is there an instance?
1174 if (!$this->getResultInstance() instanceof SearchableResult) {
1175 // Throw an exception here
1176 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1180 $this->getResultInstance()->rewind();
1182 // Do we have an entry?
1183 if ($this->getResultInstance()->valid() === false) {
1184 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
1185 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1189 $this->getResultInstance()->next();
1192 $entry = $this->getResultInstance()->current();
1199 * Getter for field name
1201 * @param $fieldName Field name which we shall get
1202 * @return $fieldValue Field value from the user
1203 * @throws NullPointerException If the result instance is null
1205 public final function getField (string $fieldName) {
1206 // Default field value
1209 // Get result instance
1210 $resultInstance = $this->getResultInstance();
1212 // Is this instance null?
1213 if (is_null($resultInstance)) {
1214 // Then the user instance is no longer valid (expired cookies?)
1215 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1218 // Get current array
1219 $fieldArray = $resultInstance->current();
1220 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1222 // Convert dashes to underscore
1223 $fieldName2 = StringUtils::convertDashesToUnderscores($fieldName);
1225 // Does the field exist?
1226 if ($this->isFieldSet($fieldName)) {
1228 $fieldValue = $fieldArray[$fieldName2];
1229 } elseif (defined('DEVELOPER')) {
1230 // Missing field entry, may require debugging
1231 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
1233 // Missing field entry, may require debugging
1234 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
1242 * Checks if given field is set
1244 * @param $fieldName Field name to check
1245 * @return $isSet Whether the given field name is set
1246 * @throws NullPointerException If the result instance is null
1248 public function isFieldSet (string $fieldName) {
1249 // Get result instance
1250 $resultInstance = $this->getResultInstance();
1252 // Is this instance null?
1253 if (is_null($resultInstance)) {
1254 // Then the user instance is no longer valid (expired cookies?)
1255 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1258 // Get current array
1259 $fieldArray = $resultInstance->current();
1260 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
1262 // Convert dashes to underscore
1263 $fieldName = StringUtils::convertDashesToUnderscores($fieldName);
1266 $isSet = isset($fieldArray[$fieldName]);
1273 * Flushs all pending updates to the database layer
1277 public function flushPendingUpdates () {
1278 // Get result instance
1279 $resultInstance = $this->getResultInstance();
1281 // Do we have data to update?
1282 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1283 // Get wrapper class name config entry
1284 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1286 // Create object instance
1287 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
1289 // Yes, then send the whole result to the database layer
1290 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1295 * Outputs a deprecation warning to the developer.
1297 * @param $message The message we shall output to the developer
1299 * @todo Write a logging mechanism for productive mode
1301 public function deprecationWarning ($message) {
1302 // Is developer mode active?
1303 if (defined('DEVELOPER')) {
1304 // Debug instance is there?
1305 if (!is_null($this->getDebugInstance())) {
1306 // Output stub message
1307 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
1310 trigger_error($message . "<br />\n");
1314 // @TODO Finish this part!
1315 $this->partialStub('Developer mode inactive. Message:' . $message);
1320 * Checks whether the given PHP extension is loaded
1322 * @param $phpExtension The PHP extension we shall check
1323 * @return $isLoaded Whether the PHP extension is loaded
1325 public final function isPhpExtensionLoaded ($phpExtension) {
1327 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1334 * "Getter" as a time() replacement but with milliseconds. You should use this
1335 * method instead of the encapsulated getimeofday() function.
1337 * @return $milliTime Timestamp with milliseconds
1339 public function getMilliTime () {
1340 // Get the time of day as float
1341 $milliTime = gettimeofday(true);
1348 * Idles (sleeps) for given milliseconds
1350 * @return $hasSlept Whether it goes fine
1352 public function idle ($milliSeconds) {
1353 // Sleep is fine by default
1356 // Idle so long with found function
1357 if (function_exists('time_sleep_until')) {
1358 // Get current time and add idle time
1359 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1361 // New PHP 5.1.0 function found, ignore errors
1362 $hasSlept = @time_sleep_until($sleepUntil);
1365 * My Sun station doesn't have that function even with latest PHP
1368 usleep($milliSeconds * 1000);
1376 * Checks whether the given encoded data was encoded with Base64
1378 * @param $encodedData Encoded data we shall check
1379 * @return $isBase64 Whether the encoded data is Base64
1381 protected function isBase64Encoded ($encodedData) {
1383 $isBase64 = (@base64_decode($encodedData, true) !== false);
1390 * Gets a cache key from Criteria instance
1392 * @param $criteriaInstance An instance of a Criteria class
1393 * @param $onlyKeys Only use these keys for a cache key
1394 * @return $cacheKey A cache key suitable for lookup/storage purposes
1396 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
1398 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: criteriaInstance=' . $criteriaInstance->__toString() . ',onlyKeys()=' . count($onlyKeys) . ' - CALLED!');
1399 $cacheKey = sprintf('%s@%s',
1400 $this->__toString(),
1401 $criteriaInstance->getCacheKey($onlyKeys)
1405 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: cacheKey=' . $cacheKey . ' - EXIT!');
1410 * Getter for startup time in miliseconds
1412 * @return $startupTime Startup time in miliseconds
1414 protected function getStartupTime () {
1415 return self::$startupTime;
1419 * "Getter" for a printable currently execution time in nice braces
1421 * @return $executionTime Current execution time in nice braces
1423 protected function getPrintableExecutionTime () {
1424 // Caculate the execution time
1425 $executionTime = microtime(true) - $this->getStartupTime();
1427 // Pack it in nice braces
1428 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
1431 return $executionTime;
1435 * Hashes a given string with a simple but stronger hash function (no salt)
1436 * and hex-encode it.
1438 * @param $str The string to be hashed
1439 * @return $hash The hash from string $str
1441 public static final function hash ($str) {
1442 // Hash given string with (better secure) hasher
1443 $hash = bin2hex(mhash(MHASH_SHA256, $str));
1450 * "Getter" for length of hash() output. This will be "cached" to speed up
1453 * @return $length Length of hash() output
1455 public static final function getHashLength () {
1457 if (is_null(self::$hashLength)) {
1458 // No, then hash a string and save its length.
1459 self::$hashLength = strlen(self::hash('abc123'));
1463 return self::$hashLength;
1467 * Checks whether the given number is really a number (only chars 0-9).
1469 * @param $num A string consisting only chars between 0 and 9
1470 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
1471 * @param $assertMismatch Whether to assert mismatches
1472 * @return $ret The (hopefully) secured numbered value
1474 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
1475 // Filter all numbers out
1476 $ret = preg_replace('/[^0123456789]/', '', $num);
1479 if ($castValue === true) {
1480 // Cast to biggest numeric type
1481 $ret = (double) $ret;
1484 // Assert only if requested
1485 if ($assertMismatch === true) {
1486 // Has the whole value changed?
1487 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
1495 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
1497 * @param $num A string consisting only chars between 0 and 9
1498 * @param $assertMismatch Whether to assert mismatches
1499 * @return $ret The (hopefully) secured hext-numbered value
1501 public function hexval ($num, $assertMismatch = false) {
1502 // Filter all numbers out
1503 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
1505 // Assert only if requested
1506 if ($assertMismatch === true) {
1507 // Has the whole value changed?
1508 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
1516 * Determines if an element is set in the generic array
1518 * @param $keyGroup Main group for the key
1519 * @param $subGroup Sub group for the key
1520 * @param $key Key to check
1521 * @param $element Element to check
1522 * @return $isset Whether the given key is set
1524 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
1526 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
1529 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
1535 * Determines if a key is set in the generic array
1537 * @param $keyGroup Main group for the key
1538 * @param $subGroup Sub group for the key
1539 * @param $key Key to check
1540 * @return $isset Whether the given key is set
1542 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
1544 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1547 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
1555 * Determines if a group is set in the generic array
1557 * @param $keyGroup Main group
1558 * @param $subGroup Sub group
1559 * @return $isset Whether the given group is set
1561 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
1563 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
1566 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
1573 * Getter for sub key group
1575 * @param $keyGroup Main key group
1576 * @param $subGroup Sub key group
1577 * @return $array An array with all array elements
1579 protected final function getGenericSubArray ($keyGroup, $subGroup) {
1581 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
1582 // No, then abort here
1583 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
1588 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
1591 return $this->genericArray[$keyGroup][$subGroup];
1595 * Unsets a given key in generic array
1597 * @param $keyGroup Main group for the key
1598 * @param $subGroup Sub group for the key
1599 * @param $key Key to unset
1602 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
1604 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1607 unset($this->genericArray[$keyGroup][$subGroup][$key]);
1611 * Unsets a given element in generic array
1613 * @param $keyGroup Main group for the key
1614 * @param $subGroup Sub group for the key
1615 * @param $key Key to unset
1616 * @param $element Element to unset
1619 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
1621 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
1624 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
1628 * Append a string to a given generic array key
1630 * @param $keyGroup Main group for the key
1631 * @param $subGroup Sub group for the key
1632 * @param $key Key to unset
1633 * @param $value Value to add/append
1636 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
1638 //* 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);
1640 // Is it already there?
1641 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1643 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
1646 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
1651 * Append a string to a given generic array element
1653 * @param $keyGroup Main group for the key
1654 * @param $subGroup Sub group for the key
1655 * @param $key Key to unset
1656 * @param $element Element to check
1657 * @param $value Value to add/append
1660 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
1662 //* 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);
1664 // Is it already there?
1665 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
1667 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
1670 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
1675 * Sets a string in a given generic array element
1677 * @param $keyGroup Main group for the key
1678 * @param $subGroup Sub group for the key
1679 * @param $key Key to unset
1680 * @param $element Element to check
1681 * @param $value Value to add/append
1684 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
1686 //* 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);
1689 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
1693 * Initializes given generic array group
1695 * @param $keyGroup Main group for the key
1696 * @param $subGroup Sub group for the key
1697 * @param $key Key to use
1698 * @param $forceInit Optionally force initialization
1701 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
1703 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
1705 // Is it already set?
1706 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
1707 // Already initialized
1708 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
1713 $this->genericArray[$keyGroup][$subGroup] = array();
1717 * Initializes given generic array key
1719 * @param $keyGroup Main group for the key
1720 * @param $subGroup Sub group for the key
1721 * @param $key Key to use
1722 * @param $forceInit Optionally force initialization
1725 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
1727 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
1729 // Is it already set?
1730 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
1731 // Already initialized
1732 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
1737 $this->genericArray[$keyGroup][$subGroup][$key] = array();
1741 * Initializes given generic array element
1743 * @param $keyGroup Main group for the key
1744 * @param $subGroup Sub group for the key
1745 * @param $key Key to use
1746 * @param $element Element to use
1747 * @param $forceInit Optionally force initialization
1750 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
1752 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
1754 // Is it already set?
1755 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
1756 // Already initialized
1757 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
1762 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
1766 * Pushes an element to a generic key
1768 * @param $keyGroup Main group for the key
1769 * @param $subGroup Sub group for the key
1770 * @param $key Key to use
1771 * @param $value Value to add/append
1772 * @return $count Number of array elements
1774 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
1776 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
1779 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1781 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
1785 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
1788 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
1789 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
1794 * Pushes an element to a generic array element
1796 * @param $keyGroup Main group for the key
1797 * @param $subGroup Sub group for the key
1798 * @param $key Key to use
1799 * @param $element Element to check
1800 * @param $value Value to add/append
1801 * @return $count Number of array elements
1803 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
1805 //* 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));
1808 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
1810 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
1814 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
1817 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
1818 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
1823 * Pops an element from a generic group
1825 * @param $keyGroup Main group for the key
1826 * @param $subGroup Sub group for the key
1827 * @param $key Key to unset
1828 * @return $value Last "popped" value
1830 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
1832 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1835 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1837 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
1842 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
1845 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
1846 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
1851 * Shifts an element from a generic group
1853 * @param $keyGroup Main group for the key
1854 * @param $subGroup Sub group for the key
1855 * @param $key Key to unset
1856 * @return $value Last "popped" value
1858 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
1860 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1863 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1865 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
1870 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
1873 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
1874 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
1879 * Count generic array group
1881 * @param $keyGroup Main group for the key
1882 * @return $count Count of given group
1884 protected final function countGenericArray ($keyGroup) {
1886 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
1889 if (!isset($this->genericArray[$keyGroup])) {
1891 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
1896 $count = count($this->genericArray[$keyGroup]);
1899 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
1906 * Count generic array sub group
1908 * @param $keyGroup Main group for the key
1909 * @param $subGroup Sub group for the key
1910 * @return $count Count of given group
1912 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
1914 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
1917 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
1919 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
1924 $count = count($this->genericArray[$keyGroup][$subGroup]);
1927 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
1934 * Count generic array elements
1936 * @param $keyGroup Main group for the key
1937 * @param $subGroup Sub group for the key
1938 * @para $key Key to count
1939 * @return $count Count of given key
1941 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
1943 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1946 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1948 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
1950 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
1952 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
1957 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
1960 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
1967 * Getter for whole generic group array
1969 * @param $keyGroup Key group to get
1970 * @return $array Whole generic array group
1972 protected final function getGenericArray ($keyGroup) {
1974 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
1977 if (!isset($this->genericArray[$keyGroup])) {
1979 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
1984 return $this->genericArray[$keyGroup];
1988 * Setter for generic array key
1990 * @param $keyGroup Key group to get
1991 * @param $subGroup Sub group for the key
1992 * @param $key Key to unset
1993 * @param $value Mixed value from generic array element
1996 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
1998 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2001 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2005 * Getter for generic array key
2007 * @param $keyGroup Key group to get
2008 * @param $subGroup Sub group for the key
2009 * @param $key Key to unset
2010 * @return $value Mixed value from generic array element
2012 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2014 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2017 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2019 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2024 return $this->genericArray[$keyGroup][$subGroup][$key];
2028 * Sets a value in given generic array key/element
2030 * @param $keyGroup Main group for the key
2031 * @param $subGroup Sub group for the key
2032 * @param $key Key to set
2033 * @param $element Element to set
2034 * @param $value Value to set
2037 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2039 //* 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));
2042 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2046 * Getter for generic array element
2048 * @param $keyGroup Key group to get
2049 * @param $subGroup Sub group for the key
2050 * @param $key Key to look for
2051 * @param $element Element to look for
2052 * @return $value Mixed value from generic array element
2054 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2056 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2059 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2061 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2066 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2070 * Checks if a given sub group is valid (array)
2072 * @param $keyGroup Key group to get
2073 * @param $subGroup Sub group for the key
2074 * @return $isValid Whether given sub group is valid
2076 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2078 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2081 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
2088 * Checks if a given key is valid (array)
2090 * @param $keyGroup Key group to get
2091 * @param $subGroup Sub group for the key
2092 * @param $key Key to check
2093 * @return $isValid Whether given sub group is valid
2095 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
2097 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2100 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
2107 * Initializes the web output instance
2111 protected function initWebOutputInstance () {
2112 // Get application instance
2113 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
2115 // Init web output instance
2116 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
2119 $this->setWebOutputInstance($outputInstance);
2123 * Translates boolean true to 'Y' and false to 'N'
2125 * @param $boolean Boolean value
2126 * @return $translated Translated boolean value
2128 public static final function translateBooleanToYesNo (bool $boolean) {
2129 // Make sure it is really boolean
2130 assert(is_bool($boolean));
2133 $translated = ($boolean === true) ? 'Y' : 'N';
2135 // ... and return it
2140 * Creates a full-qualified file name (FQFN) for given file name by adding
2141 * a configured temporary file path to it.
2143 * @param $infoInstance An instance of a SplFileInfo class
2144 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
2145 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
2146 * @throws FileIoException If the file cannot be written
2148 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
2150 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
2152 // Is the path writeable?
2153 if (!is_writable($basePath)) {
2154 // Path is write-protected
2155 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
2159 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
2162 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
2164 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
2168 return $tempInstance;
2172 * "Getter" for a printable state name
2174 * @return $stateName Name of the node's state in a printable format
2176 public final function getPrintableState () {
2177 // Default is 'null'
2178 $stateName = 'null';
2180 // Get the state instance
2181 $stateInstance = $this->getStateInstance();
2183 // Is it an instance of Stateable?
2184 if ($stateInstance instanceof Stateable) {
2185 // Then use that state name
2186 $stateName = $stateInstance->getStateName();