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\Crypto\RandomNumber\RandomNumberGenerator;
12 use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
13 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
14 use Org\Mxchange\CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
15 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
16 use Org\Mxchange\CoreFramework\Filesystem\PathWriteProtectedException;
17 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
18 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
19 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
20 use Org\Mxchange\CoreFramework\Handler\Handleable;
21 use Org\Mxchange\CoreFramework\Helper\Helper;
22 use Org\Mxchange\CoreFramework\Lists\Listable;
23 use Org\Mxchange\CoreFramework\Loader\ClassLoader;
24 use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
25 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
26 use Org\Mxchange\CoreFramework\Menu\RenderableMenu;
27 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
28 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
29 use Org\Mxchange\CoreFramework\Result\Database\CachedDatabaseResult;
30 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
31 use Org\Mxchange\CoreFramework\State\Stateable;
32 use Org\Mxchange\CoreFramework\Stream\Input\InputStream;
33 use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
34 use Org\Mxchange\CoreFramework\Stream\Output\OutputStream;
35 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
36 use Org\Mxchange\CoreFramework\User\ManageableAccount;
37 use Org\Mxchange\CoreFramework\Utils\String\StringUtils;
41 use \InvalidArgumentException;
47 * The simulator system class is the super class of all other classes. This
48 * class handles saving of games etc.
50 * @author Roland Haeder <webmaster@shipsimu.org>
52 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
53 * @license GNU GPL 3.0 or any newer version
54 * @link http://www.shipsimu.org
56 * This program is free software: you can redistribute it and/or modify
57 * it under the terms of the GNU General Public License as published by
58 * the Free Software Foundation, either version 3 of the License, or
59 * (at your option) any later version.
61 * This program is distributed in the hope that it will be useful,
62 * but WITHOUT ANY WARRANTY; without even the implied warranty of
63 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
64 * GNU General Public License for more details.
66 * You should have received a copy of the GNU General Public License
67 * along with this program. If not, see <http://www.gnu.org/licenses/>.
69 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
71 * Length of output from hash()
73 private static $hashLength = NULL;
76 * Self-referencing instance
78 private static $instance = NULL;
83 private $realClass = __CLASS__;
86 * Search criteria instance
88 private $searchInstance = NULL;
91 * Update criteria instance
93 private $updateInstance = NULL;
96 * Template engine instance
98 private $templateInstance = NULL;
101 * Database result instance
103 private $resultInstance = NULL;
106 * Instance for user class
108 private $userInstance = NULL;
113 private $rngInstance = NULL;
116 * Instance of a crypto helper
118 private $cryptoInstance = NULL;
121 * Instance of an Iterator class
123 private $iteratorInstance = NULL;
126 * Instance of the list
128 private $listInstance = NULL;
133 private $menuInstance = NULL;
136 * Instance of the image
138 private $imageInstance = NULL;
141 * A helper instance for the form
143 private $helperInstance = NULL;
146 * An instance of a InputStream class
148 private $inputStreamInstance = NULL;
151 * An instance of a OutputStream class
153 private $outputStreamInstance = NULL;
158 private $handlerInstance = NULL;
161 * An instance of a database wrapper class
163 private $wrapperInstance = NULL;
168 private $stateInstance = NULL;
173 private $callbackInstance = NULL;
178 private $genericArray = array();
180 /***********************
181 * Exception codes.... *
182 ***********************/
184 // @todo Try to clean these constants up
185 const EXCEPTION_IS_NULL_POINTER = 0x001;
186 const EXCEPTION_IS_NO_OBJECT = 0x002;
187 const EXCEPTION_IS_NO_ARRAY = 0x003;
188 const EXCEPTION_MISSING_METHOD = 0x004;
189 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
190 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
191 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
192 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
193 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
194 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
195 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
196 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
197 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
198 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
199 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
200 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
201 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
202 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
203 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
204 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
205 const EXCEPTION_PATH_NOT_FOUND = 0x015;
206 const EXCEPTION_INVALID_PATH_NAME = 0x016;
207 const EXCEPTION_READ_PROTECED_PATH = 0x017;
208 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
209 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
210 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
211 const EXCEPTION_INVALID_RESOURCE = 0x01b;
212 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
213 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
214 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
215 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
216 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
217 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
218 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
219 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
220 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
221 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
222 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
223 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
224 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
225 const EXCEPTION_INVALID_STRING = 0x029;
226 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
227 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
228 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
229 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
230 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
231 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
232 const EXCEPTION_MISSING_ELEMENT = 0x030;
233 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
234 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
235 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
236 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
237 const EXCEPTION_FATAL_ERROR = 0x035;
238 const EXCEPTION_FILE_NOT_FOUND = 0x036;
239 const EXCEPTION_ASSERTION_FAILED = 0x037;
240 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
241 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
242 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
243 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
244 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
245 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
246 const EXCEPTION_INVALID_SOCKET = 0x03e;
247 const EXCEPTION_SELF_INSTANCE = 0x03f;
250 * Startup time in miliseconds
252 private static $startupTime = 0;
255 * Protected super constructor
257 * @param $className Name of the class
260 protected function __construct (string $className) {
262 $this->setRealClass($className);
264 // Is the startup time set? (0 cannot be true anymore)
265 if (self::$startupTime == 0) {
267 self::$startupTime = microtime(true);
272 * Destructor for all classes. You should not call this method on your own.
276 public function __destruct () {
277 // Flush any updated entries to the database
278 $this->flushPendingUpdates();
280 // Is this object already destroyed?
281 if ($this->__toString() != 'DestructedObject') {
282 // Destroy all informations about this class but keep some text about it alive
283 $this->setRealClass('DestructedObject');
284 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
285 // Already destructed object
286 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
290 // Do not call this twice
291 trigger_error(__METHOD__ . ': Called twice.');
297 * The __call() method where all non-implemented methods end up
299 * @param $methodName Name of the missing method
300 * @args $args Arguments passed to the method
303 public final function __call ($methodName, $args) {
305 self::$instance = $this;
307 // Call static method
308 self::__callStatic($methodName, $args);
310 // Clear self-instance
311 self::$instance = NULL;
315 * The __callStatic() method where all non-implemented static methods end up
317 * @param $methodName Name of the missing method
318 * @param $args Arguments passed to the method
320 * @throws InvalidArgumentException If self::$instance is not a framework's own object
322 public static final function __callStatic ($methodName, $args) {
324 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
326 // Init argument string and class name
328 $className = 'unknown';
330 // Is self-instance set?
331 if (self::$instance instanceof FrameworkInterface) {
332 // Framework's own instance
333 $className = self::$instance->__toString();
334 } elseif (!is_null(self::$instance)) {
336 throw new InvalidArgumentException(sprintf('self::instance[%s] is not expected.', gettype(self::$instance)), self::EXCEPTION_SELF_INSTANCE);
339 // Is it NULL, empty or an array?
340 if (is_null($args)) {
342 $argsString = 'NULL';
343 } elseif (is_array($args)) {
347 // Some arguments are there
348 foreach ($args as $arg) {
349 // Add data about the argument
350 $argsString .= gettype($arg) . ':';
353 // Found a NULL argument
354 $argsString .= 'NULL';
355 } elseif (is_string($arg)) {
356 // Add length for strings
357 $argsString .= strlen($arg);
358 } elseif ((is_int($arg)) || (is_float($arg))) {
361 } elseif (is_array($arg)) {
362 // .. or size if array
363 $argsString .= count($arg);
364 } elseif (is_object($arg)) {
366 $reflection = new ReflectionClass($arg);
368 // Is an other object, maybe no __toString() available
369 $argsString .= $reflection->getName();
370 } elseif ($arg === true) {
371 // ... is boolean 'true'
372 $argsString .= 'true';
373 } elseif ($arg === false) {
374 // ... is boolean 'false'
375 $argsString .= 'false';
378 // Comma for next one
383 if (substr($argsString, -2, 1) == ',') {
385 $argsString = substr($argsString, 0, -2);
391 // Invalid arguments!
392 $argsString = sprintf('!INVALID:%s!', gettype($args));
395 // Output stub message
396 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
397 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s::%s]: Stub! Args: %s',
408 * Getter for $realClass
410 * @return $realClass The name of the real class (not BaseFrameworkSystem)
412 public function __toString () {
413 return $this->realClass;
417 * Magic method to catch setting of missing but set class fields/attributes
419 * @param $name Name of the field/attribute
420 * @param $value Value to store
423 public final function __set ($name, $value) {
424 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
427 print_r($value, true)
432 * Magic method to catch getting of missing fields/attributes
434 * @param $name Name of the field/attribute
437 public final function __get ($name) {
438 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
444 * Magic method to catch unsetting of missing fields/attributes
446 * @param $name Name of the field/attribute
449 public final function __unset ($name) {
450 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
456 * Magic method to catch object serialization
458 * @return $unsupported Unsupported method
459 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
461 public final function __sleep () {
462 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
466 * Magic method to catch object deserialization
468 * @return $unsupported Unsupported method
469 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
471 public final function __wakeup () {
472 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
476 * Magic method to catch calls when an object instance is called
478 * @return $unsupported Unsupported method
479 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
481 public final function __invoke () {
482 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
486 * Setter for the real class name
488 * @param $realClass Class name (string)
491 public final function setRealClass ($realClass) {
493 $this->realClass = (string) $realClass;
497 * Setter for database result instance
499 * @param $resultInstance An instance of a database result class
501 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
503 protected final function setResultInstance (SearchableResult $resultInstance) {
504 $this->resultInstance = $resultInstance;
508 * Getter for database result instance
510 * @return $resultInstance An instance of a database result class
512 public final function getResultInstance () {
513 return $this->resultInstance;
517 * Setter for template engine instances
519 * @param $templateInstance An instance of a template engine class
522 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
523 $this->templateInstance = $templateInstance;
527 * Getter for template engine instances
529 * @return $templateInstance An instance of a template engine class
531 protected final function getTemplateInstance () {
532 return $this->templateInstance;
536 * Setter for search instance
538 * @param $searchInstance Searchable criteria instance
541 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
542 $this->searchInstance = $searchInstance;
546 * Getter for search instance
548 * @return $searchInstance Searchable criteria instance
550 public final function getSearchInstance () {
551 return $this->searchInstance;
555 * Setter for update instance
557 * @param $updateInstance An instance of a LocalUpdateCriteria clase
560 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
561 $this->updateInstance = $updateInstance;
565 * Getter for update instance
567 * @return $updateInstance Updateable criteria instance
569 public final function getUpdateInstance () {
570 return $this->updateInstance;
574 * Setter for debug instance
576 * @param $debugInstance The instance for debug output class
579 public final function setDebugInstance (DebugMiddleware $debugInstance) {
580 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
584 * Getter for debug instance
586 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
588 public final function getDebugInstance () {
589 // Get debug instance
590 $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
593 return $debugInstance;
597 * Setter for web output instance
599 * @param $webInstance The instance for web output class
602 public final function setWebOutputInstance (OutputStreamer $webInstance) {
603 GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
607 * Getter for web output instance
609 * @return $webOutputInstance - Instance to class WebOutput
611 public final function getWebOutputInstance () {
612 $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
613 return $webOutputInstance;
617 * Private getter for language instance
619 * @return $langInstance An instance to the language sub-system
621 protected final function getLanguageInstance () {
622 $langInstance = GenericRegistry::getRegistry()->getInstance('language');
623 return $langInstance;
627 * Setter for language instance
629 * @param $langInstance An instance to the language sub-system
631 * @see LanguageSystem
633 public final function setLanguageInstance (ManageableLanguage $langInstance) {
634 GenericRegistry::getRegistry()->addInstance('language', $langInstance);
638 * Protected setter for user instance
640 * @param $userInstance An instance of a user class
643 protected final function setUserInstance (ManageableAccount $userInstance) {
644 $this->userInstance = $userInstance;
648 * Getter for user instance
650 * @return $userInstance An instance of a user class
652 public final function getUserInstance () {
653 return $this->userInstance;
657 * Setter for RNG instance
659 * @param $rngInstance An instance of a random number generator (RNG)
662 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
663 $this->rngInstance = $rngInstance;
667 * Getter for RNG instance
669 * @return $rngInstance An instance of a random number generator (RNG)
671 public final function getRngInstance () {
672 return $this->rngInstance;
676 * Setter for Cryptable instance
678 * @param $cryptoInstance An instance of a Cryptable class
681 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
682 $this->cryptoInstance = $cryptoInstance;
686 * Getter for Cryptable instance
688 * @return $cryptoInstance An instance of a Cryptable class
690 public final function getCryptoInstance () {
691 return $this->cryptoInstance;
695 * Setter for the list instance
697 * @param $listInstance A list of Listable
700 protected final function setListInstance (Listable $listInstance) {
701 $this->listInstance = $listInstance;
705 * Getter for the list instance
707 * @return $listInstance A list of Listable
709 protected final function getListInstance () {
710 return $this->listInstance;
714 * Setter for the menu instance
716 * @param $menuInstance A RenderableMenu instance
719 protected final function setMenuInstance (RenderableMenu $menuInstance) {
720 $this->menuInstance = $menuInstance;
724 * Getter for the menu instance
726 * @return $menuInstance A RenderableMenu instance
728 protected final function getMenuInstance () {
729 return $this->menuInstance;
733 * Setter for image instance
735 * @param $imageInstance An instance of an image
738 public final function setImageInstance (BaseImage $imageInstance) {
739 $this->imageInstance = $imageInstance;
743 * Getter for image instance
745 * @return $imageInstance An instance of an image
747 public final function getImageInstance () {
748 return $this->imageInstance;
752 * Setter for DatabaseWrapper instance
754 * @param $wrapperInstance An instance of an DatabaseWrapper
757 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
758 $this->wrapperInstance = $wrapperInstance;
762 * Getter for DatabaseWrapper instance
764 * @return $wrapperInstance An instance of an DatabaseWrapper
766 public final function getWrapperInstance () {
767 return $this->wrapperInstance;
771 * Setter for helper instance
773 * @param $helperInstance An instance of a helper class
776 protected final function setHelperInstance (Helper $helperInstance) {
777 $this->helperInstance = $helperInstance;
781 * Getter for helper instance
783 * @return $helperInstance An instance of a helper class
785 public final function getHelperInstance () {
786 return $this->helperInstance;
790 * Getter for a InputStream instance
792 * @param $inputStreamInstance The InputStream instance
794 protected final function getInputStreamInstance () {
795 return $this->inputStreamInstance;
799 * Setter for a InputStream instance
801 * @param $inputStreamInstance The InputStream instance
804 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
805 $this->inputStreamInstance = $inputStreamInstance;
809 * Getter for a OutputStream instance
811 * @param $outputStreamInstance The OutputStream instance
813 protected final function getOutputStreamInstance () {
814 return $this->outputStreamInstance;
818 * Setter for a OutputStream instance
820 * @param $outputStreamInstance The OutputStream instance
823 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
824 $this->outputStreamInstance = $outputStreamInstance;
828 * Setter for handler instance
830 * @param $handlerInstance An instance of a Handleable class
833 protected final function setHandlerInstance (Handleable $handlerInstance) {
834 $this->handlerInstance = $handlerInstance;
838 * Getter for handler instance
840 * @return $handlerInstance A Handleable instance
842 protected final function getHandlerInstance () {
843 return $this->handlerInstance;
847 * Setter for Iterator instance
849 * @param $iteratorInstance An instance of an Iterator
852 protected final function setIteratorInstance (Iterator $iteratorInstance) {
853 $this->iteratorInstance = $iteratorInstance;
857 * Getter for Iterator instance
859 * @return $iteratorInstance An instance of an Iterator
861 public final function getIteratorInstance () {
862 return $this->iteratorInstance;
866 * Setter for state instance
868 * @param $stateInstance A Stateable instance
871 public final function setStateInstance (Stateable $stateInstance) {
872 $this->stateInstance = $stateInstance;
876 * Getter for state instance
878 * @return $stateInstance A Stateable instance
880 public final function getStateInstance () {
881 return $this->stateInstance;
885 * Setter for call-back instance
887 * @param $callbackInstance An instance of a FrameworkInterface class
890 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
891 $this->callbackInstance = $callbackInstance;
895 * Getter for call-back instance
897 * @return $callbackInstance An instance of a FrameworkInterface class
899 protected final function getCallbackInstance () {
900 return $this->callbackInstance;
904 * Checks whether an object equals this object. You should overwrite this
905 * method to implement own equality checks
907 * @param $objectInstance An instance of a FrameworkInterface object
908 * @return $equals Whether both objects equals
910 public function equals (FrameworkInterface $objectInstance) {
913 $this->__toString() == $objectInstance->__toString()
915 $this->hashCode() == $objectInstance->hashCode()
923 * Generates a generic hash code of this class. You should really overwrite
924 * this method with your own hash code generator code. But keep KISS in mind.
926 * @return $hashCode A generic hash code respresenting this whole class
928 public function hashCode () {
930 return crc32($this->__toString());
934 * Appends a trailing slash to a string
936 * @param $str A string (maybe) without trailing slash
937 * @return $str A string with an auto-appended trailing slash
939 public final function addMissingTrailingSlash ($str) {
940 // Is there a trailing slash?
941 if (substr($str, -1, 1) != '/') {
945 // Return string with trailing slash
950 * Prepare the template engine (HtmlTemplateEngine by default) for a given
951 * application helper instance (ApplicationHelper by default).
953 * @param $applicationInstance An application helper instance or
954 * null if we shall use the default
955 * @return $templateInstance The template engine instance
956 * @throws NullPointerException If the discovered application
957 * instance is still null
959 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
960 // Is the application instance set?
961 if (is_null($applicationInstance)) {
962 // Get the current instance
963 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
966 if (is_null($applicationInstance)) {
967 // Thrown an exception
968 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
972 // Initialize the template engine
973 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
975 // Return the prepared instance
976 return $templateInstance;
980 * Debugs this instance by putting out it's full content
982 * @param $message Optional message to show in debug output
985 public final function debugInstance ($message = '') {
986 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
987 restore_error_handler();
993 if (!empty($message)) {
995 $content = sprintf('<div class="debug_message">
997 </div>' . PHP_EOL, $message);
1000 // Generate the output
1001 $content .= sprintf('<pre>%s</pre>',
1004 print_r($this, true)
1010 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1013 <div class="debug_content">
1017 <div class="debug_include_list">
1020 $this->__toString(),
1022 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1027 * Replaces control characters with printable output
1029 * @param $str String with control characters
1030 * @return $str Replaced string
1032 protected function replaceControlCharacters ($str) {
1035 chr(13), '[r]', str_replace(
1036 chr(10), '[n]', str_replace(
1046 * Output a partial stub message for the caller method
1048 * @param $message An optional message to display
1051 protected function partialStub ($message = '') {
1053 $stubMessage = 'Partial stub!';
1055 // Is an extra message given?
1056 if (!empty($message)) {
1057 // Then add it as well
1058 $stubMessage .= ' Message: ' . $message;
1061 // Debug instance is there?
1062 if (!is_null($this->getDebugInstance())) {
1063 // Output stub message
1064 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1067 trigger_error($stubMessage);
1073 * Outputs a debug backtrace and stops further script execution
1075 * @param $message An optional message to output
1076 * @param $doExit Whether exit the program (true is default)
1079 public function debugBackTrace ($message = '', $doExit = true) {
1080 // Sorry, there is no other way getting this nice backtrace
1081 if (!empty($message)) {
1083 printf('Message: %s<br />' . PHP_EOL, $message);
1087 debug_print_backtrace();
1091 if ($doExit === true) {
1097 * Creates an instance of a debugger instance
1099 * @param $className Name of the class (currently unsupported)
1100 * @param $lineNumber Line number where the call was made
1101 * @return $debugInstance An instance of a debugger class
1102 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1104 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1105 // Is the instance set?
1106 if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
1107 // Init debug instance
1108 $debugInstance = NULL;
1112 // Get a debugger instance
1113 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1114 } catch (NullPointerException $e) {
1115 // Didn't work, no instance there
1116 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1119 // Empty string should be ignored and used for testing the middleware
1120 DebugMiddleware::getSelfInstance()->output('');
1122 // Set it in registry
1123 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
1125 // Get instance from registry
1126 $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
1130 return $debugInstance;
1134 * Simple output of a message with line-break
1136 * @param $message Message to output
1139 public function outputLine ($message) {
1141 print($message . PHP_EOL);
1145 * Outputs a debug message whether to debug instance (should be set!) or
1146 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1147 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1149 * @param $message Message we shall send out...
1150 * @param $doPrint Whether print or die here (default: print)
1151 * @paran $stripTags Whether to strip tags (default: false)
1154 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1155 // Set debug instance to NULL
1156 $debugInstance = NULL;
1159 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1161 // Is function partialStub/__callStatic ?
1162 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1163 // Prepend class::function:line from 3rd element
1164 $message = sprintf('[%s::%s:%d]: %s',
1165 $backtrace[2]['class'],
1166 $backtrace[2]['function'],
1167 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1171 // Prepend class::function:line from 2nd element
1172 $message = sprintf('[%s::%s:%d]: %s',
1173 $backtrace[1]['class'],
1174 $backtrace[1]['function'],
1175 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1182 // Get debug instance
1183 $debugInstance = $this->getDebugInstance();
1184 } catch (NullPointerException $e) {
1185 // The debug instance is not set (yet)
1188 // Is the debug instance there?
1189 if (is_object($debugInstance)) {
1190 // Use debug output handler
1191 $debugInstance->output($message, $stripTags);
1193 if ($doPrint === false) {
1194 // Die here if not printed
1198 // Are debug times enabled?
1199 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1201 $message = $this->getPrintableExecutionTime() . $message;
1205 if ($doPrint === true) {
1207 $this->outputLine($message);
1216 * Marks up the code by adding e.g. line numbers
1218 * @param $phpCode Unmarked PHP code
1219 * @return $markedCode Marked PHP code
1221 public function markupCode ($phpCode) {
1226 $errorArray = error_get_last();
1228 // Init the code with error message
1229 if (is_array($errorArray)) {
1231 $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>',
1232 basename($errorArray['file']),
1233 $errorArray['line'],
1234 $errorArray['message'],
1239 // Add line number to the code
1240 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1242 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1244 htmlentities($code, ENT_QUOTES)
1253 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1254 * beatiful for web-based front-ends. If null is given a message id
1255 * null_timestamp will be resolved and returned.
1257 * @param $timestamp Timestamp to prepare (filter) for display
1258 * @return $readable A readable timestamp
1260 public function doFilterFormatTimestamp ($timestamp) {
1261 // Default value to return
1264 // Is the timestamp null?
1265 if (is_null($timestamp)) {
1266 // Get a message string
1267 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1269 switch ($this->getLanguageInstance()->getLanguageCode()) {
1270 case 'de': // German format is a bit different to default
1271 // Split the GMT stamp up
1272 $dateTime = explode(' ', $timestamp );
1273 $dateArray = explode('-', $dateTime[0]);
1274 $timeArray = explode(':', $dateTime[1]);
1276 // Construct the timestamp
1277 $readable = sprintf(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('german_date_time'),
1287 default: // Default is pass-through
1288 $readable = $timestamp;
1298 * Filter a given number into a localized number
1300 * @param $value The raw value from e.g. database
1301 * @return $localized Localized value
1303 public function doFilterFormatNumber ($value) {
1304 // Generate it from config and localize dependencies
1305 switch ($this->getLanguageInstance()->getLanguageCode()) {
1306 case 'de': // German format is a bit different to default
1307 $localized = number_format($value, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('decimals'), ',', '.');
1310 default: // US, etc.
1311 $localized = number_format($value, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('decimals'), '.', ',');
1320 * "Getter" for databse entry
1322 * @return $entry An array with database entries
1323 * @throws NullPointerException If the database result is not found
1324 * @throws InvalidDatabaseResultException If the database result is invalid
1326 protected final function getDatabaseEntry () {
1327 // Is there an instance?
1328 if (!$this->getResultInstance() instanceof SearchableResult) {
1329 // Throw an exception here
1330 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1334 $this->getResultInstance()->rewind();
1336 // Do we have an entry?
1337 if ($this->getResultInstance()->valid() === false) {
1338 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
1339 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1343 $this->getResultInstance()->next();
1346 $entry = $this->getResultInstance()->current();
1353 * Getter for field name
1355 * @param $fieldName Field name which we shall get
1356 * @return $fieldValue Field value from the user
1357 * @throws NullPointerException If the result instance is null
1359 public final function getField (string $fieldName) {
1360 // Default field value
1363 // Get result instance
1364 $resultInstance = $this->getResultInstance();
1366 // Is this instance null?
1367 if (is_null($resultInstance)) {
1368 // Then the user instance is no longer valid (expired cookies?)
1369 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1372 // Get current array
1373 $fieldArray = $resultInstance->current();
1374 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1376 // Convert dashes to underscore
1377 $fieldName2 = StringUtils::convertDashesToUnderscores($fieldName);
1379 // Does the field exist?
1380 if ($this->isFieldSet($fieldName)) {
1382 $fieldValue = $fieldArray[$fieldName2];
1383 } elseif (defined('DEVELOPER')) {
1384 // Missing field entry, may require debugging
1385 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
1387 // Missing field entry, may require debugging
1388 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
1396 * Checks if given field is set
1398 * @param $fieldName Field name to check
1399 * @return $isSet Whether the given field name is set
1400 * @throws NullPointerException If the result instance is null
1402 public function isFieldSet (string $fieldName) {
1403 // Get result instance
1404 $resultInstance = $this->getResultInstance();
1406 // Is this instance null?
1407 if (is_null($resultInstance)) {
1408 // Then the user instance is no longer valid (expired cookies?)
1409 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1412 // Get current array
1413 $fieldArray = $resultInstance->current();
1414 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
1416 // Convert dashes to underscore
1417 $fieldName = StringUtils::convertDashesToUnderscores($fieldName);
1420 $isSet = isset($fieldArray[$fieldName]);
1427 * Flushs all pending updates to the database layer
1431 public function flushPendingUpdates () {
1432 // Get result instance
1433 $resultInstance = $this->getResultInstance();
1435 // Do we have data to update?
1436 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1437 // Get wrapper class name config entry
1438 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1440 // Create object instance
1441 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
1443 // Yes, then send the whole result to the database layer
1444 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1449 * Outputs a deprecation warning to the developer.
1451 * @param $message The message we shall output to the developer
1453 * @todo Write a logging mechanism for productive mode
1455 public function deprecationWarning ($message) {
1456 // Is developer mode active?
1457 if (defined('DEVELOPER')) {
1458 // Debug instance is there?
1459 if (!is_null($this->getDebugInstance())) {
1460 // Output stub message
1461 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
1464 trigger_error($message . "<br />\n");
1468 // @TODO Finish this part!
1469 $this->partialStub('Developer mode inactive. Message:' . $message);
1474 * Checks whether the given PHP extension is loaded
1476 * @param $phpExtension The PHP extension we shall check
1477 * @return $isLoaded Whether the PHP extension is loaded
1479 public final function isPhpExtensionLoaded ($phpExtension) {
1481 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1488 * "Getter" as a time() replacement but with milliseconds. You should use this
1489 * method instead of the encapsulated getimeofday() function.
1491 * @return $milliTime Timestamp with milliseconds
1493 public function getMilliTime () {
1494 // Get the time of day as float
1495 $milliTime = gettimeofday(true);
1502 * Idles (sleeps) for given milliseconds
1504 * @return $hasSlept Whether it goes fine
1506 public function idle ($milliSeconds) {
1507 // Sleep is fine by default
1510 // Idle so long with found function
1511 if (function_exists('time_sleep_until')) {
1512 // Get current time and add idle time
1513 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1515 // New PHP 5.1.0 function found, ignore errors
1516 $hasSlept = @time_sleep_until($sleepUntil);
1519 * My Sun station doesn't have that function even with latest PHP
1522 usleep($milliSeconds * 1000);
1530 * Checks whether the given encoded data was encoded with Base64
1532 * @param $encodedData Encoded data we shall check
1533 * @return $isBase64 Whether the encoded data is Base64
1535 protected function isBase64Encoded ($encodedData) {
1537 $isBase64 = (@base64_decode($encodedData, true) !== false);
1544 * Gets a cache key from Criteria instance
1546 * @param $criteriaInstance An instance of a Criteria class
1547 * @param $onlyKeys Only use these keys for a cache key
1548 * @return $cacheKey A cache key suitable for lookup/storage purposes
1550 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
1552 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: criteriaInstance=' . $criteriaInstance->__toString() . ',onlyKeys()=' . count($onlyKeys) . ' - CALLED!');
1553 $cacheKey = sprintf('%s@%s',
1554 $this->__toString(),
1555 $criteriaInstance->getCacheKey($onlyKeys)
1559 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: cacheKey=' . $cacheKey . ' - EXIT!');
1564 * Getter for startup time in miliseconds
1566 * @return $startupTime Startup time in miliseconds
1568 protected function getStartupTime () {
1569 return self::$startupTime;
1573 * "Getter" for a printable currently execution time in nice braces
1575 * @return $executionTime Current execution time in nice braces
1577 protected function getPrintableExecutionTime () {
1578 // Caculate the execution time
1579 $executionTime = microtime(true) - $this->getStartupTime();
1581 // Pack it in nice braces
1582 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
1585 return $executionTime;
1589 * Hashes a given string with a simple but stronger hash function (no salt)
1590 * and hex-encode it.
1592 * @param $str The string to be hashed
1593 * @return $hash The hash from string $str
1595 public static final function hash ($str) {
1596 // Hash given string with (better secure) hasher
1597 $hash = bin2hex(mhash(MHASH_SHA256, $str));
1604 * "Getter" for length of hash() output. This will be "cached" to speed up
1607 * @return $length Length of hash() output
1609 public static final function getHashLength () {
1611 if (is_null(self::$hashLength)) {
1612 // No, then hash a string and save its length.
1613 self::$hashLength = strlen(self::hash('abc123'));
1617 return self::$hashLength;
1621 * Checks whether the given number is really a number (only chars 0-9).
1623 * @param $num A string consisting only chars between 0 and 9
1624 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
1625 * @param $assertMismatch Whether to assert mismatches
1626 * @return $ret The (hopefully) secured numbered value
1628 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
1629 // Filter all numbers out
1630 $ret = preg_replace('/[^0123456789]/', '', $num);
1633 if ($castValue === true) {
1634 // Cast to biggest numeric type
1635 $ret = (double) $ret;
1638 // Assert only if requested
1639 if ($assertMismatch === true) {
1640 // Has the whole value changed?
1641 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
1649 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
1651 * @param $num A string consisting only chars between 0 and 9
1652 * @param $assertMismatch Whether to assert mismatches
1653 * @return $ret The (hopefully) secured hext-numbered value
1655 public function hexval ($num, $assertMismatch = false) {
1656 // Filter all numbers out
1657 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
1659 // Assert only if requested
1660 if ($assertMismatch === true) {
1661 // Has the whole value changed?
1662 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
1670 * Determines if an element is set in the generic array
1672 * @param $keyGroup Main group for the key
1673 * @param $subGroup Sub group for the key
1674 * @param $key Key to check
1675 * @param $element Element to check
1676 * @return $isset Whether the given key is set
1678 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
1680 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
1683 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
1689 * Determines if a key is set in the generic array
1691 * @param $keyGroup Main group for the key
1692 * @param $subGroup Sub group for the key
1693 * @param $key Key to check
1694 * @return $isset Whether the given key is set
1696 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
1698 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1701 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
1709 * Determines if a group is set in the generic array
1711 * @param $keyGroup Main group
1712 * @param $subGroup Sub group
1713 * @return $isset Whether the given group is set
1715 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
1717 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
1720 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
1727 * Getter for sub key group
1729 * @param $keyGroup Main key group
1730 * @param $subGroup Sub key group
1731 * @return $array An array with all array elements
1733 protected final function getGenericSubArray ($keyGroup, $subGroup) {
1735 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
1736 // No, then abort here
1737 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
1742 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
1745 return $this->genericArray[$keyGroup][$subGroup];
1749 * Unsets a given key in generic array
1751 * @param $keyGroup Main group for the key
1752 * @param $subGroup Sub group for the key
1753 * @param $key Key to unset
1756 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
1758 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1761 unset($this->genericArray[$keyGroup][$subGroup][$key]);
1765 * Unsets a given element in generic array
1767 * @param $keyGroup Main group for the key
1768 * @param $subGroup Sub group for the key
1769 * @param $key Key to unset
1770 * @param $element Element to unset
1773 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
1775 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
1778 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
1782 * Append a string to a given generic array key
1784 * @param $keyGroup Main group for the key
1785 * @param $subGroup Sub group for the key
1786 * @param $key Key to unset
1787 * @param $value Value to add/append
1790 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
1792 //* 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);
1794 // Is it already there?
1795 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1797 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
1800 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
1805 * Append a string to a given generic array element
1807 * @param $keyGroup Main group for the key
1808 * @param $subGroup Sub group for the key
1809 * @param $key Key to unset
1810 * @param $element Element to check
1811 * @param $value Value to add/append
1814 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
1816 //* 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);
1818 // Is it already there?
1819 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
1821 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
1824 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
1829 * Sets a string in a given generic array element
1831 * @param $keyGroup Main group for the key
1832 * @param $subGroup Sub group for the key
1833 * @param $key Key to unset
1834 * @param $element Element to check
1835 * @param $value Value to add/append
1838 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
1840 //* 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);
1843 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
1847 * Initializes given generic array group
1849 * @param $keyGroup Main group for the key
1850 * @param $subGroup Sub group for the key
1851 * @param $key Key to use
1852 * @param $forceInit Optionally force initialization
1855 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
1857 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
1859 // Is it already set?
1860 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
1861 // Already initialized
1862 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
1867 $this->genericArray[$keyGroup][$subGroup] = array();
1871 * Initializes given generic array key
1873 * @param $keyGroup Main group for the key
1874 * @param $subGroup Sub group for the key
1875 * @param $key Key to use
1876 * @param $forceInit Optionally force initialization
1879 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
1881 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
1883 // Is it already set?
1884 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
1885 // Already initialized
1886 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
1891 $this->genericArray[$keyGroup][$subGroup][$key] = array();
1895 * Initializes given generic array element
1897 * @param $keyGroup Main group for the key
1898 * @param $subGroup Sub group for the key
1899 * @param $key Key to use
1900 * @param $element Element to use
1901 * @param $forceInit Optionally force initialization
1904 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
1906 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
1908 // Is it already set?
1909 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
1910 // Already initialized
1911 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
1916 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
1920 * Pushes an element to a generic key
1922 * @param $keyGroup Main group for the key
1923 * @param $subGroup Sub group for the key
1924 * @param $key Key to use
1925 * @param $value Value to add/append
1926 * @return $count Number of array elements
1928 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
1930 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
1933 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1935 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
1939 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
1942 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
1943 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
1948 * Pushes an element to a generic array element
1950 * @param $keyGroup Main group for the key
1951 * @param $subGroup Sub group for the key
1952 * @param $key Key to use
1953 * @param $element Element to check
1954 * @param $value Value to add/append
1955 * @return $count Number of array elements
1957 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
1959 //* 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));
1962 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
1964 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
1968 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
1971 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
1972 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
1977 * Pops an element from a generic group
1979 * @param $keyGroup Main group for the key
1980 * @param $subGroup Sub group for the key
1981 * @param $key Key to unset
1982 * @return $value Last "popped" value
1984 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
1986 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
1989 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
1991 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
1996 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
1999 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2000 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2005 * Shifts an element from a generic group
2007 * @param $keyGroup Main group for the key
2008 * @param $subGroup Sub group for the key
2009 * @param $key Key to unset
2010 * @return $value Last "popped" value
2012 protected final function shiftGenericArrayElement ($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 . ' not found.');
2024 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2027 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2028 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2033 * Count generic array group
2035 * @param $keyGroup Main group for the key
2036 * @return $count Count of given group
2038 protected final function countGenericArray ($keyGroup) {
2040 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2043 if (!isset($this->genericArray[$keyGroup])) {
2045 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2050 $count = count($this->genericArray[$keyGroup]);
2053 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2060 * Count generic array sub group
2062 * @param $keyGroup Main group for the key
2063 * @param $subGroup Sub group for the key
2064 * @return $count Count of given group
2066 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2068 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2071 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2073 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2078 $count = count($this->genericArray[$keyGroup][$subGroup]);
2081 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2088 * Count generic array elements
2090 * @param $keyGroup Main group for the key
2091 * @param $subGroup Sub group for the key
2092 * @para $key Key to count
2093 * @return $count Count of given key
2095 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2097 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2100 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2102 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2104 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2106 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2111 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2114 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2121 * Getter for whole generic group array
2123 * @param $keyGroup Key group to get
2124 * @return $array Whole generic array group
2126 protected final function getGenericArray ($keyGroup) {
2128 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2131 if (!isset($this->genericArray[$keyGroup])) {
2133 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2138 return $this->genericArray[$keyGroup];
2142 * Setter for generic array key
2144 * @param $keyGroup Key group to get
2145 * @param $subGroup Sub group for the key
2146 * @param $key Key to unset
2147 * @param $value Mixed value from generic array element
2150 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2152 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2155 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2159 * Getter for generic array key
2161 * @param $keyGroup Key group to get
2162 * @param $subGroup Sub group for the key
2163 * @param $key Key to unset
2164 * @return $value Mixed value from generic array element
2166 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2168 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2171 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2173 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2178 return $this->genericArray[$keyGroup][$subGroup][$key];
2182 * Sets a value in given generic array key/element
2184 * @param $keyGroup Main group for the key
2185 * @param $subGroup Sub group for the key
2186 * @param $key Key to set
2187 * @param $element Element to set
2188 * @param $value Value to set
2191 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2193 //* 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));
2196 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2200 * Getter for generic array element
2202 * @param $keyGroup Key group to get
2203 * @param $subGroup Sub group for the key
2204 * @param $key Key to look for
2205 * @param $element Element to look for
2206 * @return $value Mixed value from generic array element
2208 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2210 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2213 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2215 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2220 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2224 * Checks if a given sub group is valid (array)
2226 * @param $keyGroup Key group to get
2227 * @param $subGroup Sub group for the key
2228 * @return $isValid Whether given sub group is valid
2230 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2232 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2235 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
2242 * Checks if a given key is valid (array)
2244 * @param $keyGroup Key group to get
2245 * @param $subGroup Sub group for the key
2246 * @param $key Key to check
2247 * @return $isValid Whether given sub group is valid
2249 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
2251 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2254 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
2261 * Initializes the web output instance
2265 protected function initWebOutputInstance () {
2266 // Get application instance
2267 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
2269 // Init web output instance
2270 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
2273 $this->setWebOutputInstance($outputInstance);
2277 * Translates boolean true to 'Y' and false to 'N'
2279 * @param $boolean Boolean value
2280 * @return $translated Translated boolean value
2282 public static final function translateBooleanToYesNo (bool $boolean) {
2283 // Make sure it is really boolean
2284 assert(is_bool($boolean));
2287 $translated = ($boolean === true) ? 'Y' : 'N';
2289 // ... and return it
2294 * Creates a full-qualified file name (FQFN) for given file name by adding
2295 * a configured temporary file path to it.
2297 * @param $infoInstance An instance of a SplFileInfo class
2298 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
2299 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
2300 * @throws FileIoException If the file cannot be written
2302 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
2304 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
2306 // Is the path writeable?
2307 if (!is_writable($basePath)) {
2308 // Path is write-protected
2309 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
2313 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
2316 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
2318 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
2322 return $tempInstance;
2326 * "Getter" for a printable state name
2328 * @return $stateName Name of the node's state in a printable format
2330 public final function getPrintableState () {
2331 // Default is 'null'
2332 $stateName = 'null';
2334 // Get the state instance
2335 $stateInstance = $this->getStateInstance();
2337 // Is it an instance of Stateable?
2338 if ($stateInstance instanceof Stateable) {
2339 // Then use that state name
2340 $stateName = $stateInstance->getStateName();