3 namespace Org\Mxchange\CoreFramework\Object;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Compressor\Compressor;
8 use Org\Mxchange\CoreFramework\Configuration\FrameworkConfiguration;
9 use Org\Mxchange\CoreFramework\Connection\Database\DatabaseConnection;
10 use Org\Mxchange\CoreFramework\Controller\Controller;
11 use Org\Mxchange\CoreFramework\Criteria\Criteria;
12 use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
13 use Org\Mxchange\CoreFramework\Criteria\Local\LocalUpdateCriteria;
14 use Org\Mxchange\CoreFramework\Crypto\Cryptable;
15 use Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
16 use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
17 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
18 use Org\Mxchange\CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
19 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
20 use Org\Mxchange\CoreFramework\Filesystem\Block;
21 use Org\Mxchange\CoreFramework\Filesystem\FilePointer;
22 use Org\Mxchange\CoreFramework\Filesystem\FrameworkDirectory;
23 use Org\Mxchange\CoreFramework\Filesystem\PathWriteProtectedException;
24 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
25 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
26 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
27 use Org\Mxchange\CoreFramework\Handler\Handleable;
28 use Org\Mxchange\CoreFramework\Handler\Stream\IoHandler;
29 use Org\Mxchange\CoreFramework\Helper\Helper;
30 use Org\Mxchange\CoreFramework\Index\Indexable;
31 use Org\Mxchange\CoreFramework\Lists\Listable;
32 use Org\Mxchange\CoreFramework\Loader\ClassLoader;
33 use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
34 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
35 use Org\Mxchange\CoreFramework\Menu\RenderableMenu;
36 use Org\Mxchange\CoreFramework\Middleware\Compressor\CompressorChannel;
37 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
38 use Org\Mxchange\CoreFramework\Parser\Parseable;
39 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
40 use Org\Mxchange\CoreFramework\Registry\Register;
41 use Org\Mxchange\CoreFramework\Resolver\Resolver;
42 use Org\Mxchange\CoreFramework\Result\Database\CachedDatabaseResult;
43 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
44 use Org\Mxchange\CoreFramework\Stacker\Stackable;
45 use Org\Mxchange\CoreFramework\State\Stateable;
46 use Org\Mxchange\CoreFramework\Stream\Input\InputStream;
47 use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
48 use Org\Mxchange\CoreFramework\Stream\Output\OutputStream;
49 use Org\Mxchange\CoreFramework\String\Utils\StringUtils;
50 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
51 use Org\Mxchange\CoreFramework\User\ManageableAccount;
52 use Org\Mxchange\CoreFramework\Visitor\Visitor;
56 use \InvalidArgumentException;
62 * The simulator system class is the super class of all other classes. This
63 * class handles saving of games etc.
65 * @author Roland Haeder <webmaster@shipsimu.org>
67 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
68 * @license GNU GPL 3.0 or any newer version
69 * @link http://www.shipsimu.org
71 * This program is free software: you can redistribute it and/or modify
72 * it under the terms of the GNU General Public License as published by
73 * the Free Software Foundation, either version 3 of the License, or
74 * (at your option) any later version.
76 * This program is distributed in the hope that it will be useful,
77 * but WITHOUT ANY WARRANTY; without even the implied warranty of
78 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
79 * GNU General Public License for more details.
81 * You should have received a copy of the GNU General Public License
82 * along with this program. If not, see <http://www.gnu.org/licenses/>.
84 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
86 * Length of output from hash()
88 private static $hashLength = NULL;
93 private $realClass = 'BaseFrameworkSystem';
96 * Search criteria instance
98 private $searchInstance = NULL;
101 * Update criteria instance
103 private $updateInstance = NULL;
106 * The file I/O instance for the template loader
108 private $fileIoInstance = NULL;
113 private $resolverInstance = NULL;
116 * Template engine instance
118 private $templateInstance = NULL;
121 * Database result instance
123 private $resultInstance = NULL;
126 * Instance for user class
128 private $userInstance = NULL;
131 * A controller instance
133 private $controllerInstance = NULL;
138 private $rngInstance = NULL;
141 * Instance of a crypto helper
143 private $cryptoInstance = NULL;
146 * Instance of an Iterator class
148 private $iteratorInstance = NULL;
151 * Instance of the list
153 private $listInstance = NULL;
158 private $menuInstance = NULL;
161 * Instance of the image
163 private $imageInstance = NULL;
166 * Instance of the stacker
168 private $stackInstance = NULL;
171 * A Compressor instance
173 private $compressorInstance = NULL;
176 * A Parseable instance
178 private $parserInstance = NULL;
181 * A database wrapper instance
183 private $databaseInstance = NULL;
186 * A helper instance for the form
188 private $helperInstance = NULL;
191 * An instance of a InputStream class
193 private $inputStreamInstance = NULL;
196 * An instance of a OutputStream class
198 private $outputStreamInstance = NULL;
203 private $handlerInstance = NULL;
206 * Visitor handler instance
208 private $visitorInstance = NULL;
211 * An instance of a database wrapper class
213 private $wrapperInstance = NULL;
216 * An instance of a file I/O pointer class (not handler)
218 private $pointerInstance = NULL;
221 * An instance of an Indexable class
223 private $indexInstance = NULL;
226 * An instance of a Block class
228 private $blockInstance = NULL;
233 private $minableInstance = NULL;
236 * A FrameworkDirectory instance
238 private $directoryInstance = NULL;
241 * The concrete output instance
243 private $outputInstance = NULL;
248 private $stateInstance = NULL;
251 * Registry instance (implementing Register)
253 private $registryInstance = NULL;
258 private $callbackInstance = NULL;
261 * Thousands separator
263 private $thousands = '.'; // German
268 private $decimals = ','; // German
273 private $socketResource = false;
278 private $packageData = array();
283 private $genericArray = array();
288 private $commandName = '';
293 private $controllerName = '';
296 * Array with bitmasks and such for pack/unpack methods to support both
297 * 32-bit and 64-bit systems
299 private $packingData = array(
302 'left' => 0xffff0000,
303 'right' => 0x0000ffff,
309 'left' => 0xffffffff00000000,
310 'right' => 0x00000000ffffffff,
317 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
319 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
321 private $archArrayElement = false;
323 /***********************
324 * Exception codes.... *
325 ***********************/
327 // @todo Try to clean these constants up
328 const EXCEPTION_IS_NULL_POINTER = 0x001;
329 const EXCEPTION_IS_NO_OBJECT = 0x002;
330 const EXCEPTION_IS_NO_ARRAY = 0x003;
331 const EXCEPTION_MISSING_METHOD = 0x004;
332 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
333 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
334 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
335 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
336 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
337 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
338 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
339 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
340 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
341 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
342 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
343 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
344 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
345 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
346 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
347 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
348 const EXCEPTION_PATH_NOT_FOUND = 0x015;
349 const EXCEPTION_INVALID_PATH_NAME = 0x016;
350 const EXCEPTION_READ_PROTECED_PATH = 0x017;
351 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
352 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
353 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
354 const EXCEPTION_INVALID_RESOURCE = 0x01b;
355 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
356 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
357 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
358 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
359 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
360 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
361 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
362 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
363 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
364 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
365 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
366 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
367 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
368 const EXCEPTION_INVALID_STRING = 0x029;
369 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
370 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
371 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
372 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
373 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
374 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
375 const EXCEPTION_MISSING_ELEMENT = 0x030;
376 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
377 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
378 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
379 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
380 const EXCEPTION_FATAL_ERROR = 0x035;
381 const EXCEPTION_FILE_NOT_FOUND = 0x036;
382 const EXCEPTION_ASSERTION_FAILED = 0x037;
383 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
384 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
385 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
386 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
387 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
388 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
389 const EXCEPTION_INVALID_SOCKET = 0x03e;
392 * Hexadecimal->Decimal translation array
394 private static $hexdec = array(
414 * Decimal->hexadecimal translation array
416 private static $dechex = array(
436 * Startup time in miliseconds
438 private static $startupTime = 0;
441 * Protected super constructor
443 * @param $className Name of the class
446 protected function __construct ($className) {
448 $this->setRealClass($className);
450 // Set configuration instance if no registry ...
451 if (!$this instanceof Register) {
452 // ... because registries doesn't need to be configured
453 $this->setConfigInstance(FrameworkBootstrap::getConfigurationInstance());
456 // Is the startup time set? (0 cannot be true anymore)
457 if (self::$startupTime == 0) {
459 self::$startupTime = microtime(true);
463 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
467 * Destructor for all classes. You should not call this method on your own.
471 public function __destruct () {
472 // Flush any updated entries to the database
473 $this->flushPendingUpdates();
475 // Is this object already destroyed?
476 if ($this->__toString() != 'DestructedObject') {
477 // Destroy all informations about this class but keep some text about it alive
478 $this->setRealClass('DestructedObject');
479 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
480 // Already destructed object
481 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
485 // Do not call this twice
486 trigger_error(__METHOD__ . ': Called twice.');
492 * The __call() method where all non-implemented methods end up
494 * @param $methodName Name of the missing method
495 * @args $args Arguments passed to the method
498 public final function __call ($methodName, $args) {
499 return self::__callStatic($methodName, $args);
503 * The __callStatic() method where all non-implemented static methods end up
505 * @param $methodName Name of the missing method
506 * @args $args Arguments passed to the method
509 public static final function __callStatic ($methodName, $args) {
511 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
513 // Init argument string
516 // Is it NULL, empty or an array?
517 if (is_null($args)) {
519 $argsString = 'NULL';
520 } elseif (is_array($args)) {
524 // Some arguments are there
525 foreach ($args as $arg) {
526 // Add data about the argument
527 $argsString .= gettype($arg) . ':';
530 // Found a NULL argument
531 $argsString .= 'NULL';
532 } elseif (is_string($arg)) {
533 // Add length for strings
534 $argsString .= strlen($arg);
535 } elseif ((is_int($arg)) || (is_float($arg))) {
538 } elseif (is_array($arg)) {
539 // .. or size if array
540 $argsString .= count($arg);
541 } elseif (is_object($arg)) {
543 $reflection = new ReflectionClass($arg);
545 // Is an other object, maybe no __toString() available
546 $argsString .= $reflection->getName();
547 } elseif ($arg === true) {
548 // ... is boolean 'true'
549 $argsString .= 'true';
550 } elseif ($arg === false) {
551 // ... is boolean 'false'
552 $argsString .= 'false';
555 // Comma for next one
560 if (substr($argsString, -2, 1) == ',') {
561 $argsString = substr($argsString, 0, -2);
567 // Invalid arguments!
568 $argsString = '!INVALID:' . gettype($args) . '!';
571 // Output stub message
572 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
573 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
583 * Getter for $realClass
585 * @return $realClass The name of the real class (not BaseFrameworkSystem)
587 public function __toString () {
588 return $this->realClass;
592 * Magic method to catch setting of missing but set class fields/attributes
594 * @param $name Name of the field/attribute
595 * @param $value Value to store
598 public final function __set ($name, $value) {
599 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
602 print_r($value, true)
607 * Magic method to catch getting of missing fields/attributes
609 * @param $name Name of the field/attribute
612 public final function __get ($name) {
613 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
619 * Magic method to catch unsetting of missing fields/attributes
621 * @param $name Name of the field/attribute
624 public final function __unset ($name) {
625 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
631 * Magic method to catch object serialization
633 * @return $unsupported Unsupported method
634 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
636 public final function __sleep () {
637 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
641 * Magic method to catch object deserialization
643 * @return $unsupported Unsupported method
644 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
646 public final function __wakeup () {
647 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
651 * Magic method to catch calls when an object instance is called
653 * @return $unsupported Unsupported method
654 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
656 public final function __invoke () {
657 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
661 * Setter for the real class name
663 * @param $realClass Class name (string)
666 public final function setRealClass ($realClass) {
668 $this->realClass = (string) $realClass;
672 * Setter for database result instance
674 * @param $resultInstance An instance of a database result class
676 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
678 protected final function setResultInstance (SearchableResult $resultInstance) {
679 $this->resultInstance = $resultInstance;
683 * Getter for database result instance
685 * @return $resultInstance An instance of a database result class
687 public final function getResultInstance () {
688 return $this->resultInstance;
692 * Setter for template engine instances
694 * @param $templateInstance An instance of a template engine class
697 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
698 $this->templateInstance = $templateInstance;
702 * Getter for template engine instances
704 * @return $templateInstance An instance of a template engine class
706 protected final function getTemplateInstance () {
707 return $this->templateInstance;
711 * Setter for search instance
713 * @param $searchInstance Searchable criteria instance
716 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
717 $this->searchInstance = $searchInstance;
721 * Getter for search instance
723 * @return $searchInstance Searchable criteria instance
725 public final function getSearchInstance () {
726 return $this->searchInstance;
730 * Setter for update instance
732 * @param $updateInstance An instance of a LocalUpdateCriteria clase
735 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
736 $this->updateInstance = $updateInstance;
740 * Getter for update instance
742 * @return $updateInstance Updateable criteria instance
744 public final function getUpdateInstance () {
745 return $this->updateInstance;
749 * Setter for resolver instance
751 * @param $resolverInstance Instance of a command resolver class
754 public final function setResolverInstance (Resolver $resolverInstance) {
755 $this->resolverInstance = $resolverInstance;
759 * Getter for resolver instance
761 * @return $resolverInstance Instance of a command resolver class
763 public final function getResolverInstance () {
764 return $this->resolverInstance;
768 * Setter for language instance
770 * @param $configInstance The configuration instance which shall
771 * be FrameworkConfiguration
774 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
775 GenericRegistry::getRegistry()->addInstance('config', $configInstance);
779 * Getter for configuration instance
781 * @return $configInstance Configuration instance
783 public final function getConfigInstance () {
784 $configInstance = GenericRegistry::getRegistry()->getInstance('config');
785 return $configInstance;
789 * Setter for debug instance
791 * @param $debugInstance The instance for debug output class
794 public final function setDebugInstance (DebugMiddleware $debugInstance) {
795 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
799 * Getter for debug instance
801 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
803 public final function getDebugInstance () {
804 // Get debug instance
805 $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
808 return $debugInstance;
812 * Setter for web output instance
814 * @param $webInstance The instance for web output class
817 public final function setWebOutputInstance (OutputStreamer $webInstance) {
818 GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
822 * Getter for web output instance
824 * @return $webOutputInstance - Instance to class WebOutput
826 public final function getWebOutputInstance () {
827 $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
828 return $webOutputInstance;
832 * Setter for database instance
834 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
837 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
838 GenericRegistry::getRegistry()->addInstance('db_instance', $databaseInstance);
842 * Getter for database layer
844 * @return $databaseInstance The database layer instance
846 public final function getDatabaseInstance () {
848 $databaseInstance = GenericRegistry::getRegistry()->getInstance('db_instance');
851 return $databaseInstance;
855 * Setter for compressor channel
857 * @param $compressorInstance An instance of CompressorChannel
860 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
861 GenericRegistry::getRegistry()->addInstance('compressor', $compressorInstance);
865 * Getter for compressor channel
867 * @return $compressorInstance The compressor channel
869 public final function getCompressorChannel () {
870 $compressorInstance = GenericRegistry::getRegistry()->getInstance('compressor');
871 return $compressorInstance;
875 * Private getter for language instance
877 * @return $langInstance An instance to the language sub-system
879 protected final function getLanguageInstance () {
880 $langInstance = GenericRegistry::getRegistry()->getInstance('language');
881 return $langInstance;
885 * Setter for language instance
887 * @param $langInstance An instance to the language sub-system
889 * @see LanguageSystem
891 public final function setLanguageInstance (ManageableLanguage $langInstance) {
892 GenericRegistry::getRegistry()->addInstance('language', $langInstance);
896 * Private getter for file IO instance
898 * @return $fileIoInstance An instance to the file I/O sub-system
900 protected final function getFileIoInstance () {
901 return $this->fileIoInstance;
905 * Setter for file I/O instance
907 * @param $fileIoInstance An instance to the file I/O sub-system
910 public final function setFileIoInstance (IoHandler $fileIoInstance) {
911 $this->fileIoInstance = $fileIoInstance;
915 * Protected setter for user instance
917 * @param $userInstance An instance of a user class
920 protected final function setUserInstance (ManageableAccount $userInstance) {
921 $this->userInstance = $userInstance;
925 * Getter for user instance
927 * @return $userInstance An instance of a user class
929 public final function getUserInstance () {
930 return $this->userInstance;
934 * Setter for controller instance (this surely breaks a bit the MVC patterm)
936 * @param $controllerInstance An instance of the controller
939 public final function setControllerInstance (Controller $controllerInstance) {
940 $this->controllerInstance = $controllerInstance;
944 * Getter for controller instance (this surely breaks a bit the MVC patterm)
946 * @return $controllerInstance An instance of the controller
948 public final function getControllerInstance () {
949 return $this->controllerInstance;
953 * Setter for RNG instance
955 * @param $rngInstance An instance of a random number generator (RNG)
958 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
959 $this->rngInstance = $rngInstance;
963 * Getter for RNG instance
965 * @return $rngInstance An instance of a random number generator (RNG)
967 public final function getRngInstance () {
968 return $this->rngInstance;
972 * Setter for Cryptable instance
974 * @param $cryptoInstance An instance of a Cryptable class
977 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
978 $this->cryptoInstance = $cryptoInstance;
982 * Getter for Cryptable instance
984 * @return $cryptoInstance An instance of a Cryptable class
986 public final function getCryptoInstance () {
987 return $this->cryptoInstance;
991 * Setter for the list instance
993 * @param $listInstance A list of Listable
996 protected final function setListInstance (Listable $listInstance) {
997 $this->listInstance = $listInstance;
1001 * Getter for the list instance
1003 * @return $listInstance A list of Listable
1005 protected final function getListInstance () {
1006 return $this->listInstance;
1010 * Setter for the menu instance
1012 * @param $menuInstance A RenderableMenu instance
1015 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1016 $this->menuInstance = $menuInstance;
1020 * Getter for the menu instance
1022 * @return $menuInstance A RenderableMenu instance
1024 protected final function getMenuInstance () {
1025 return $this->menuInstance;
1029 * Setter for image instance
1031 * @param $imageInstance An instance of an image
1034 public final function setImageInstance (BaseImage $imageInstance) {
1035 $this->imageInstance = $imageInstance;
1039 * Getter for image instance
1041 * @return $imageInstance An instance of an image
1043 public final function getImageInstance () {
1044 return $this->imageInstance;
1048 * Setter for stacker instance
1050 * @param $stackInstance An instance of an stacker
1053 public final function setStackInstance (Stackable $stackInstance) {
1054 $this->stackInstance = $stackInstance;
1058 * Getter for stacker instance
1060 * @return $stackInstance An instance of an stacker
1062 public final function getStackInstance () {
1063 return $this->stackInstance;
1067 * Setter for compressor instance
1069 * @param $compressorInstance An instance of an compressor
1072 public final function setCompressorInstance (Compressor $compressorInstance) {
1073 $this->compressorInstance = $compressorInstance;
1077 * Getter for compressor instance
1079 * @return $compressorInstance An instance of an compressor
1081 public final function getCompressorInstance () {
1082 return $this->compressorInstance;
1086 * Setter for Parseable instance
1088 * @param $parserInstance An instance of an Parseable
1091 public final function setParserInstance (Parseable $parserInstance) {
1092 $this->parserInstance = $parserInstance;
1096 * Getter for Parseable instance
1098 * @return $parserInstance An instance of an Parseable
1100 public final function getParserInstance () {
1101 return $this->parserInstance;
1105 * Setter for DatabaseWrapper instance
1107 * @param $wrapperInstance An instance of an DatabaseWrapper
1110 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1111 $this->wrapperInstance = $wrapperInstance;
1115 * Getter for DatabaseWrapper instance
1117 * @return $wrapperInstance An instance of an DatabaseWrapper
1119 public final function getWrapperInstance () {
1120 return $this->wrapperInstance;
1124 * Setter for socket resource
1126 * @param $socketResource A valid socket resource
1129 public final function setSocketResource ($socketResource) {
1130 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1131 $this->socketResource = $socketResource;
1135 * Getter for socket resource
1137 * @return $socketResource A valid socket resource
1139 public final function getSocketResource () {
1140 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1141 return $this->socketResource;
1145 * Setter for helper instance
1147 * @param $helperInstance An instance of a helper class
1150 protected final function setHelperInstance (Helper $helperInstance) {
1151 $this->helperInstance = $helperInstance;
1155 * Getter for helper instance
1157 * @return $helperInstance An instance of a helper class
1159 public final function getHelperInstance () {
1160 return $this->helperInstance;
1164 * Getter for a InputStream instance
1166 * @param $inputStreamInstance The InputStream instance
1168 protected final function getInputStreamInstance () {
1169 return $this->inputStreamInstance;
1173 * Setter for a InputStream instance
1175 * @param $inputStreamInstance The InputStream instance
1178 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1179 $this->inputStreamInstance = $inputStreamInstance;
1183 * Getter for a OutputStream instance
1185 * @param $outputStreamInstance The OutputStream instance
1187 protected final function getOutputStreamInstance () {
1188 return $this->outputStreamInstance;
1192 * Setter for a OutputStream instance
1194 * @param $outputStreamInstance The OutputStream instance
1197 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1198 $this->outputStreamInstance = $outputStreamInstance;
1202 * Setter for handler instance
1204 * @param $handlerInstance An instance of a Handleable class
1207 protected final function setHandlerInstance (Handleable $handlerInstance) {
1208 $this->handlerInstance = $handlerInstance;
1212 * Getter for handler instance
1214 * @return $handlerInstance A Handleable instance
1216 protected final function getHandlerInstance () {
1217 return $this->handlerInstance;
1221 * Setter for visitor instance
1223 * @param $visitorInstance A Visitor instance
1226 protected final function setVisitorInstance (Visitor $visitorInstance) {
1227 $this->visitorInstance = $visitorInstance;
1231 * Getter for visitor instance
1233 * @return $visitorInstance A Visitor instance
1235 protected final function getVisitorInstance () {
1236 return $this->visitorInstance;
1240 * Setter for raw package Data
1242 * @param $packageData Raw package Data
1245 public final function setPackageData (array $packageData) {
1246 $this->packageData = $packageData;
1250 * Getter for raw package Data
1252 * @return $packageData Raw package Data
1254 public function getPackageData () {
1255 return $this->packageData;
1260 * Setter for Iterator instance
1262 * @param $iteratorInstance An instance of an Iterator
1265 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1266 $this->iteratorInstance = $iteratorInstance;
1270 * Getter for Iterator instance
1272 * @return $iteratorInstance An instance of an Iterator
1274 public final function getIteratorInstance () {
1275 return $this->iteratorInstance;
1279 * Setter for FilePointer instance
1281 * @param $pointerInstance An instance of an FilePointer class
1284 protected final function setPointerInstance (FilePointer $pointerInstance) {
1285 $this->pointerInstance = $pointerInstance;
1289 * Getter for FilePointer instance
1291 * @return $pointerInstance An instance of an FilePointer class
1293 public final function getPointerInstance () {
1294 return $this->pointerInstance;
1298 * Unsets pointer instance which triggers a call of __destruct() if the
1299 * instance is still there. This is surely not fatal on already "closed"
1300 * file pointer instances.
1302 * I don't want to mess around with above setter by giving it a default
1303 * value NULL as setter should always explicitly only set (existing) object
1304 * instances and NULL is NULL.
1308 protected final function unsetPointerInstance () {
1309 // Simply it to NULL
1310 $this->pointerInstance = NULL;
1314 * Setter for Indexable instance
1316 * @param $indexInstance An instance of an Indexable class
1319 protected final function setIndexInstance (Indexable $indexInstance) {
1320 $this->indexInstance = $indexInstance;
1324 * Getter for Indexable instance
1326 * @return $indexInstance An instance of an Indexable class
1328 public final function getIndexInstance () {
1329 return $this->indexInstance;
1333 * Setter for Block instance
1335 * @param $blockInstance An instance of an Block class
1338 protected final function setBlockInstance (Block $blockInstance) {
1339 $this->blockInstance = $blockInstance;
1343 * Getter for Block instance
1345 * @return $blockInstance An instance of an Block class
1347 public final function getBlockInstance () {
1348 return $this->blockInstance;
1352 * Setter for Minable instance
1354 * @param $minableInstance A Minable instance
1357 protected final function setMinableInstance (Minable $minableInstance) {
1358 $this->minableInstance = $minableInstance;
1362 * Getter for minable instance
1364 * @return $minableInstance A Minable instance
1366 protected final function getMinableInstance () {
1367 return $this->minableInstance;
1371 * Setter for FrameworkDirectory instance
1373 * @param $directoryInstance A FrameworkDirectory instance
1376 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1377 $this->directoryInstance = $directoryInstance;
1381 * Getter for FrameworkDirectory instance
1383 * @return $directoryInstance A FrameworkDirectory instance
1385 protected final function getDirectoryInstance () {
1386 return $this->directoryInstance;
1390 * Setter for state instance
1392 * @param $stateInstance A Stateable instance
1395 public final function setStateInstance (Stateable $stateInstance) {
1396 $this->stateInstance = $stateInstance;
1400 * Getter for state instance
1402 * @return $stateInstance A Stateable instance
1404 public final function getStateInstance () {
1405 return $this->stateInstance;
1409 * Setter for output instance
1411 * @param $outputInstance The debug output instance
1414 public final function setOutputInstance (OutputStreamer $outputInstance) {
1415 $this->outputInstance = $outputInstance;
1419 * Getter for output instance
1421 * @return $outputInstance The debug output instance
1423 public final function getOutputInstance () {
1424 return $this->outputInstance;
1428 * Setter for registry instance
1430 * @param $registryInstance An instance of a Register class
1433 protected final function setRegistryInstance (Register $registryInstance) {
1434 $this->registryInstance = $registryInstance;
1438 * Getter for registry instance
1440 * @return $registryInstance The debug registry instance
1442 public final function getRegistryInstance () {
1443 return $this->registryInstance;
1447 * Setter for call-back instance
1449 * @param $callbackInstance An instance of a FrameworkInterface class
1452 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1453 $this->callbackInstance = $callbackInstance;
1457 * Getter for call-back instance
1459 * @return $callbackInstance An instance of a FrameworkInterface class
1461 protected final function getCallbackInstance () {
1462 return $this->callbackInstance;
1466 * Setter for command name
1468 * @param $commandName Last validated command name
1471 protected final function setCommandName ($commandName) {
1472 $this->commandName = $commandName;
1476 * Getter for command name
1478 * @return $commandName Last validated command name
1480 protected final function getCommandName () {
1481 return $this->commandName;
1485 * Setter for controller name
1487 * @param $controllerName Last validated controller name
1490 protected final function setControllerName ($controllerName) {
1491 $this->controllerName = $controllerName;
1495 * Getter for controller name
1497 * @return $controllerName Last validated controller name
1499 protected final function getControllerName () {
1500 return $this->controllerName;
1504 * Checks whether an object equals this object. You should overwrite this
1505 * method to implement own equality checks
1507 * @param $objectInstance An instance of a FrameworkInterface object
1508 * @return $equals Whether both objects equals
1510 public function equals (FrameworkInterface $objectInstance) {
1513 $this->__toString() == $objectInstance->__toString()
1515 $this->hashCode() == $objectInstance->hashCode()
1518 // Return the result
1523 * Generates a generic hash code of this class. You should really overwrite
1524 * this method with your own hash code generator code. But keep KISS in mind.
1526 * @return $hashCode A generic hash code respresenting this whole class
1528 public function hashCode () {
1530 return crc32($this->__toString());
1534 * Formats computer generated price values into human-understandable formats
1535 * with thousand and decimal separators.
1537 * @param $value The in computer format value for a price
1538 * @param $currency The currency symbol (use HTML-valid characters!)
1539 * @param $decNum Number of decimals after commata
1540 * @return $price The for the current language formated price string
1541 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1542 * thousands separator
1545 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1546 // Are all required attriutes set?
1547 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1548 // Throw an exception
1549 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1553 $value = (float) $value;
1555 // Reformat the US number
1556 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1558 // Return as string...
1563 * Appends a trailing slash to a string
1565 * @param $str A string (maybe) without trailing slash
1566 * @return $str A string with an auto-appended trailing slash
1568 public final function addMissingTrailingSlash ($str) {
1569 // Is there a trailing slash?
1570 if (substr($str, -1, 1) != '/') {
1574 // Return string with trailing slash
1579 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1580 * application helper instance (ApplicationHelper by default).
1582 * @param $applicationInstance An application helper instance or
1583 * null if we shall use the default
1584 * @return $templateInstance The template engine instance
1585 * @throws NullPointerException If the discovered application
1586 * instance is still null
1588 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1589 // Is the application instance set?
1590 if (is_null($applicationInstance)) {
1591 // Get the current instance
1592 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1595 if (is_null($applicationInstance)) {
1596 // Thrown an exception
1597 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1601 // Initialize the template engine
1602 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1604 // Return the prepared instance
1605 return $templateInstance;
1609 * Debugs this instance by putting out it's full content
1611 * @param $message Optional message to show in debug output
1614 public final function debugInstance ($message = '') {
1615 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1616 restore_error_handler();
1621 // Is a message set?
1622 if (!empty($message)) {
1623 // Construct message
1624 $content = sprintf('<div class="debug_message">
1626 </div>' . PHP_EOL, $message);
1629 // Generate the output
1630 $content .= sprintf('<pre>%s</pre>',
1633 print_r($this, true)
1639 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1642 <div class="debug_content">
1646 <div class="debug_include_list">
1649 $this->__toString(),
1651 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1656 * Replaces control characters with printable output
1658 * @param $str String with control characters
1659 * @return $str Replaced string
1661 protected function replaceControlCharacters ($str) {
1664 chr(13), '[r]', str_replace(
1665 chr(10), '[n]', str_replace(
1675 * Output a partial stub message for the caller method
1677 * @param $message An optional message to display
1680 protected function partialStub ($message = '') {
1682 $stubMessage = 'Partial Stub!';
1684 // Is the extra message given?
1685 if (!empty($message)) {
1686 // Then add it as well
1687 $stubMessage .= ' Message: ' . $message;
1690 // Debug instance is there?
1691 if (!is_null($this->getDebugInstance())) {
1692 // Output stub message
1693 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1696 trigger_error($stubMessage);
1702 * Outputs a debug backtrace and stops further script execution
1704 * @param $message An optional message to output
1705 * @param $doExit Whether exit the program (true is default)
1708 public function debugBackTrace ($message = '', $doExit = true) {
1709 // Sorry, there is no other way getting this nice backtrace
1710 if (!empty($message)) {
1712 printf('Message: %s<br />' . PHP_EOL, $message);
1716 debug_print_backtrace();
1720 if ($doExit === true) {
1726 * Creates an instance of a debugger instance
1728 * @param $className Name of the class (currently unsupported)
1729 * @param $lineNumber Line number where the call was made
1730 * @return $debugInstance An instance of a debugger class
1731 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1733 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1734 // Is the instance set?
1735 if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
1736 // Init debug instance
1737 $debugInstance = NULL;
1741 // Get a debugger instance
1742 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1743 } catch (NullPointerException $e) {
1744 // Didn't work, no instance there
1745 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1748 // Empty string should be ignored and used for testing the middleware
1749 DebugMiddleware::getSelfInstance()->output('');
1751 // Set it in registry
1752 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
1754 // Get instance from registry
1755 $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
1759 return $debugInstance;
1763 * Simple output of a message with line-break
1765 * @param $message Message to output
1768 public function outputLine ($message) {
1770 print($message . PHP_EOL);
1774 * Outputs a debug message whether to debug instance (should be set!) or
1775 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1776 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1778 * @param $message Message we shall send out...
1779 * @param $doPrint Whether print or die here (default: print)
1780 * @paran $stripTags Whether to strip tags (default: false)
1783 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1784 // Set debug instance to NULL
1785 $debugInstance = NULL;
1788 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1790 // Is function partialStub/__callStatic ?
1791 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1792 // Prepend class::function:line from 3rd element
1793 $message = sprintf('[%s::%s:%d]: %s',
1794 $backtrace[2]['class'],
1795 $backtrace[2]['function'],
1796 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1800 // Prepend class::function:line from 2nd element
1801 $message = sprintf('[%s::%s:%d]: %s',
1802 $backtrace[1]['class'],
1803 $backtrace[1]['function'],
1804 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1811 // Get debug instance
1812 $debugInstance = $this->getDebugInstance();
1813 } catch (NullPointerException $e) {
1814 // The debug instance is not set (yet)
1817 // Is the debug instance there?
1818 if (is_object($debugInstance)) {
1819 // Use debug output handler
1820 $debugInstance->output($message, $stripTags);
1822 if ($doPrint === false) {
1823 // Die here if not printed
1827 // Are debug times enabled?
1828 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1830 $message = $this->getPrintableExecutionTime() . $message;
1834 if ($doPrint === true) {
1836 $this->outputLine($message);
1845 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1847 * @param $str The string, what ever it is needs to be converted
1848 * @return $className Generated class name
1850 public static final function convertToClassName ($str) {
1854 // Convert all dashes in underscores
1855 $str = StringUtils::convertDashesToUnderscores($str);
1857 // Now use that underscores to get classname parts for hungarian style
1858 foreach (explode('_', $str) as $strPart) {
1859 // Make the class name part lower case and first upper case
1860 $className .= ucfirst(strtolower($strPart));
1863 // Return class name
1868 * Marks up the code by adding e.g. line numbers
1870 * @param $phpCode Unmarked PHP code
1871 * @return $markedCode Marked PHP code
1873 public function markupCode ($phpCode) {
1878 $errorArray = error_get_last();
1880 // Init the code with error message
1881 if (is_array($errorArray)) {
1883 $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>',
1884 basename($errorArray['file']),
1885 $errorArray['line'],
1886 $errorArray['message'],
1891 // Add line number to the code
1892 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1894 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1896 htmlentities($code, ENT_QUOTES)
1905 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1906 * beatiful for web-based front-ends. If null is given a message id
1907 * null_timestamp will be resolved and returned.
1909 * @param $timestamp Timestamp to prepare (filter) for display
1910 * @return $readable A readable timestamp
1912 public function doFilterFormatTimestamp ($timestamp) {
1913 // Default value to return
1916 // Is the timestamp null?
1917 if (is_null($timestamp)) {
1918 // Get a message string
1919 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1921 switch ($this->getLanguageInstance()->getLanguageCode()) {
1922 case 'de': // German format is a bit different to default
1923 // Split the GMT stamp up
1924 $dateTime = explode(' ', $timestamp );
1925 $dateArray = explode('-', $dateTime[0]);
1926 $timeArray = explode(':', $dateTime[1]);
1928 // Construct the timestamp
1929 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1939 default: // Default is pass-through
1940 $readable = $timestamp;
1950 * Filter a given number into a localized number
1952 * @param $value The raw value from e.g. database
1953 * @return $localized Localized value
1955 public function doFilterFormatNumber ($value) {
1956 // Generate it from config and localize dependencies
1957 switch ($this->getLanguageInstance()->getLanguageCode()) {
1958 case 'de': // German format is a bit different to default
1959 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1962 default: // US, etc.
1963 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1972 * "Getter" for databse entry
1974 * @return $entry An array with database entries
1975 * @throws NullPointerException If the database result is not found
1976 * @throws InvalidDatabaseResultException If the database result is invalid
1978 protected final function getDatabaseEntry () {
1979 // Is there an instance?
1980 if (!$this->getResultInstance() instanceof SearchableResult) {
1981 // Throw an exception here
1982 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1986 $this->getResultInstance()->rewind();
1988 // Do we have an entry?
1989 if ($this->getResultInstance()->valid() === false) {
1990 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
1991 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1995 $this->getResultInstance()->next();
1998 $entry = $this->getResultInstance()->current();
2005 * Getter for field name
2007 * @param $fieldName Field name which we shall get
2008 * @return $fieldValue Field value from the user
2009 * @throws NullPointerException If the result instance is null
2011 public final function getField ($fieldName) {
2012 // Default field value
2015 // Get result instance
2016 $resultInstance = $this->getResultInstance();
2018 // Is this instance null?
2019 if (is_null($resultInstance)) {
2020 // Then the user instance is no longer valid (expired cookies?)
2021 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2024 // Get current array
2025 $fieldArray = $resultInstance->current();
2026 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2028 // Convert dashes to underscore
2029 $fieldName2 = StringUtils::convertDashesToUnderscores($fieldName);
2031 // Does the field exist?
2032 if ($this->isFieldSet($fieldName)) {
2034 $fieldValue = $fieldArray[$fieldName2];
2035 } elseif (defined('DEVELOPER')) {
2036 // Missing field entry, may require debugging
2037 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2039 // Missing field entry, may require debugging
2040 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2048 * Checks if given field is set
2050 * @param $fieldName Field name to check
2051 * @return $isSet Whether the given field name is set
2052 * @throws NullPointerException If the result instance is null
2054 public function isFieldSet ($fieldName) {
2055 // Get result instance
2056 $resultInstance = $this->getResultInstance();
2058 // Is this instance null?
2059 if (is_null($resultInstance)) {
2060 // Then the user instance is no longer valid (expired cookies?)
2061 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2064 // Get current array
2065 $fieldArray = $resultInstance->current();
2066 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2068 // Convert dashes to underscore
2069 $fieldName = StringUtils::convertDashesToUnderscores($fieldName);
2072 $isSet = isset($fieldArray[$fieldName]);
2079 * Flushs all pending updates to the database layer
2083 public function flushPendingUpdates () {
2084 // Get result instance
2085 $resultInstance = $this->getResultInstance();
2087 // Do we have data to update?
2088 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2089 // Get wrapper class name config entry
2090 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2092 // Create object instance
2093 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2095 // Yes, then send the whole result to the database layer
2096 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2101 * Outputs a deprecation warning to the developer.
2103 * @param $message The message we shall output to the developer
2105 * @todo Write a logging mechanism for productive mode
2107 public function deprecationWarning ($message) {
2108 // Is developer mode active?
2109 if (defined('DEVELOPER')) {
2110 // Debug instance is there?
2111 if (!is_null($this->getDebugInstance())) {
2112 // Output stub message
2113 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2116 trigger_error($message . "<br />\n");
2120 // @TODO Finish this part!
2121 $this->partialStub('Developer mode inactive. Message:' . $message);
2126 * Checks whether the given PHP extension is loaded
2128 * @param $phpExtension The PHP extension we shall check
2129 * @return $isLoaded Whether the PHP extension is loaded
2131 public final function isPhpExtensionLoaded ($phpExtension) {
2133 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2140 * "Getter" as a time() replacement but with milliseconds. You should use this
2141 * method instead of the encapsulated getimeofday() function.
2143 * @return $milliTime Timestamp with milliseconds
2145 public function getMilliTime () {
2146 // Get the time of day as float
2147 $milliTime = gettimeofday(true);
2154 * Idles (sleeps) for given milliseconds
2156 * @return $hasSlept Whether it goes fine
2158 public function idle ($milliSeconds) {
2159 // Sleep is fine by default
2162 // Idle so long with found function
2163 if (function_exists('time_sleep_until')) {
2164 // Get current time and add idle time
2165 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2167 // New PHP 5.1.0 function found, ignore errors
2168 $hasSlept = @time_sleep_until($sleepUntil);
2171 * My Sun station doesn't have that function even with latest PHP
2174 usleep($milliSeconds * 1000);
2181 * Converts a hexadecimal string, even with negative sign as first string to
2182 * a decimal number using BC functions.
2184 * This work is based on comment #86673 on php.net documentation page at:
2185 * <http://de.php.net/manual/en/function.dechex.php#86673>
2187 * @param $hex Hexadecimal string
2188 * @return $dec Decimal number
2190 protected function hex2dec ($hex) {
2191 // Convert to all lower-case
2192 $hex = strtolower($hex);
2194 // Detect sign (negative/positive numbers)
2196 if (substr($hex, 0, 1) == '-') {
2198 $hex = substr($hex, 1);
2201 // Decode the hexadecimal string into a decimal number
2203 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2204 $factor = self::$hexdec[substr($hex, $i, 1)];
2205 $dec = bcadd($dec, bcmul($factor, $e));
2208 // Return the decimal number
2209 return $sign . $dec;
2213 * Converts even very large decimal numbers, also signed, to a hexadecimal
2216 * This work is based on comment #97756 on php.net documentation page at:
2217 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2219 * @param $dec Decimal number, even with negative sign
2220 * @param $maxLength Optional maximum length of the string
2221 * @return $hex Hexadecimal string
2223 protected function dec2hex ($dec, $maxLength = 0) {
2224 // maxLength can be zero or devideable by 2
2225 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2227 // Detect sign (negative/positive numbers)
2234 // Encode the decimal number into a hexadecimal string
2237 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2239 } while ($dec >= 1);
2242 * Leading zeros are required for hex-decimal "numbers". In some
2243 * situations more leading zeros are wanted, so check for both
2246 if ($maxLength > 0) {
2247 // Prepend more zeros
2248 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2249 } elseif ((strlen($hex) % 2) != 0) {
2250 // Only make string's length dividable by 2
2254 // Return the hexadecimal string
2255 return $sign . $hex;
2259 * Converts a ASCII string (0 to 255) into a decimal number.
2261 * @param $asc The ASCII string to be converted
2262 * @return $dec Decimal number
2264 protected function asc2dec ($asc) {
2265 // Convert it into a hexadecimal number
2266 $hex = bin2hex($asc);
2268 // And back into a decimal number
2269 $dec = $this->hex2dec($hex);
2276 * Converts a decimal number into an ASCII string.
2278 * @param $dec Decimal number
2279 * @return $asc An ASCII string
2281 protected function dec2asc ($dec) {
2282 // First convert the number into a hexadecimal string
2283 $hex = $this->dec2hex($dec);
2285 // Then convert it into the ASCII string
2286 $asc = $this->hex2asc($hex);
2293 * Converts a hexadecimal number into an ASCII string. Negative numbers
2296 * @param $hex Hexadecimal string
2297 * @return $asc An ASCII string
2299 protected function hex2asc ($hex) {
2300 // Check for length, it must be devideable by 2
2301 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2302 assert((strlen($hex) % 2) == 0);
2306 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2307 // Get the decimal number of the chunk
2308 $part = hexdec(substr($hex, $idx, 2));
2310 // Add it to the final string
2314 // Return the final string
2319 * Checks whether the given encoded data was encoded with Base64
2321 * @param $encodedData Encoded data we shall check
2322 * @return $isBase64 Whether the encoded data is Base64
2324 protected function isBase64Encoded ($encodedData) {
2326 $isBase64 = (@base64_decode($encodedData, true) !== false);
2333 * Gets a cache key from Criteria instance
2335 * @param $criteriaInstance An instance of a Criteria class
2336 * @param $onlyKeys Only use these keys for a cache key
2337 * @return $cacheKey A cache key suitable for lookup/storage purposes
2339 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2341 $cacheKey = sprintf('%s@%s',
2342 $this->__toString(),
2343 $criteriaInstance->getCacheKey($onlyKeys)
2347 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2352 * Getter for startup time in miliseconds
2354 * @return $startupTime Startup time in miliseconds
2356 protected function getStartupTime () {
2357 return self::$startupTime;
2361 * "Getter" for a printable currently execution time in nice braces
2363 * @return $executionTime Current execution time in nice braces
2365 protected function getPrintableExecutionTime () {
2366 // Caculate the execution time
2367 $executionTime = microtime(true) - $this->getStartupTime();
2369 // Pack it in nice braces
2370 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2373 return $executionTime;
2377 * Hashes a given string with a simple but stronger hash function (no salt)
2378 * and hex-encode it.
2380 * @param $str The string to be hashed
2381 * @return $hash The hash from string $str
2383 public static final function hash ($str) {
2384 // Hash given string with (better secure) hasher
2385 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2392 * "Getter" for length of hash() output. This will be "cached" to speed up
2395 * @return $length Length of hash() output
2397 public static final function getHashLength () {
2399 if (is_null(self::$hashLength)) {
2400 // No, then hash a string and save its length.
2401 self::$hashLength = strlen(self::hash('abc123'));
2405 return self::$hashLength;
2409 * Checks whether the given number is really a number (only chars 0-9).
2411 * @param $num A string consisting only chars between 0 and 9
2412 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2413 * @param $assertMismatch Whether to assert mismatches
2414 * @return $ret The (hopefully) secured numbered value
2416 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2417 // Filter all numbers out
2418 $ret = preg_replace('/[^0123456789]/', '', $num);
2421 if ($castValue === true) {
2422 // Cast to biggest numeric type
2423 $ret = (double) $ret;
2426 // Assert only if requested
2427 if ($assertMismatch === true) {
2428 // Has the whole value changed?
2429 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2437 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2439 * @param $num A string consisting only chars between 0 and 9
2440 * @param $assertMismatch Whether to assert mismatches
2441 * @return $ret The (hopefully) secured hext-numbered value
2443 public function hexval ($num, $assertMismatch = false) {
2444 // Filter all numbers out
2445 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2447 // Assert only if requested
2448 if ($assertMismatch === true) {
2449 // Has the whole value changed?
2450 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2458 * Determines if an element is set in the generic array
2460 * @param $keyGroup Main group for the key
2461 * @param $subGroup Sub group for the key
2462 * @param $key Key to check
2463 * @param $element Element to check
2464 * @return $isset Whether the given key is set
2466 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2468 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2471 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2477 * Determines if a key is set in the generic array
2479 * @param $keyGroup Main group for the key
2480 * @param $subGroup Sub group for the key
2481 * @param $key Key to check
2482 * @return $isset Whether the given key is set
2484 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2486 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2489 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2497 * Determines if a group is set in the generic array
2499 * @param $keyGroup Main group
2500 * @param $subGroup Sub group
2501 * @return $isset Whether the given group is set
2503 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2505 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2508 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2515 * Getter for sub key group
2517 * @param $keyGroup Main key group
2518 * @param $subGroup Sub key group
2519 * @return $array An array with all array elements
2521 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2523 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2524 // No, then abort here
2525 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2530 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2533 return $this->genericArray[$keyGroup][$subGroup];
2537 * Unsets a given key in generic array
2539 * @param $keyGroup Main group for the key
2540 * @param $subGroup Sub group for the key
2541 * @param $key Key to unset
2544 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2546 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2549 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2553 * Unsets a given element in generic array
2555 * @param $keyGroup Main group for the key
2556 * @param $subGroup Sub group for the key
2557 * @param $key Key to unset
2558 * @param $element Element to unset
2561 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2563 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2566 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2570 * Append a string to a given generic array key
2572 * @param $keyGroup Main group for the key
2573 * @param $subGroup Sub group for the key
2574 * @param $key Key to unset
2575 * @param $value Value to add/append
2578 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2580 //* 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);
2582 // Is it already there?
2583 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2585 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2588 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2593 * Append a string to a given generic array element
2595 * @param $keyGroup Main group for the key
2596 * @param $subGroup Sub group for the key
2597 * @param $key Key to unset
2598 * @param $element Element to check
2599 * @param $value Value to add/append
2602 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2604 //* 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);
2606 // Is it already there?
2607 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2609 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2612 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2617 * Sets a string in a given generic array element
2619 * @param $keyGroup Main group for the key
2620 * @param $subGroup Sub group for the key
2621 * @param $key Key to unset
2622 * @param $element Element to check
2623 * @param $value Value to add/append
2626 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2628 //* 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);
2631 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2635 * Initializes given generic array group
2637 * @param $keyGroup Main group for the key
2638 * @param $subGroup Sub group for the key
2639 * @param $key Key to use
2640 * @param $forceInit Optionally force initialization
2643 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2645 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2647 // Is it already set?
2648 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2649 // Already initialized
2650 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2655 $this->genericArray[$keyGroup][$subGroup] = array();
2659 * Initializes given generic array key
2661 * @param $keyGroup Main group for the key
2662 * @param $subGroup Sub group for the key
2663 * @param $key Key to use
2664 * @param $forceInit Optionally force initialization
2667 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2669 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2671 // Is it already set?
2672 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2673 // Already initialized
2674 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2679 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2683 * Initializes given generic array element
2685 * @param $keyGroup Main group for the key
2686 * @param $subGroup Sub group for the key
2687 * @param $key Key to use
2688 * @param $element Element to use
2689 * @param $forceInit Optionally force initialization
2692 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2694 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2696 // Is it already set?
2697 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2698 // Already initialized
2699 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2704 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2708 * Pushes an element to a generic key
2710 * @param $keyGroup Main group for the key
2711 * @param $subGroup Sub group for the key
2712 * @param $key Key to use
2713 * @param $value Value to add/append
2714 * @return $count Number of array elements
2716 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2718 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2721 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2723 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2727 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2730 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2731 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2736 * Pushes an element to a generic array element
2738 * @param $keyGroup Main group for the key
2739 * @param $subGroup Sub group for the key
2740 * @param $key Key to use
2741 * @param $element Element to check
2742 * @param $value Value to add/append
2743 * @return $count Number of array elements
2745 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2747 //* 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));
2750 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2752 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2756 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2759 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2760 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2765 * Pops an element from a generic group
2767 * @param $keyGroup Main group for the key
2768 * @param $subGroup Sub group for the key
2769 * @param $key Key to unset
2770 * @return $value Last "popped" value
2772 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2774 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2777 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2779 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2784 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2787 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2788 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2793 * Shifts an element from a generic group
2795 * @param $keyGroup Main group for the key
2796 * @param $subGroup Sub group for the key
2797 * @param $key Key to unset
2798 * @return $value Last "popped" value
2800 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2802 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2805 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2807 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2812 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2815 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2816 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2821 * Count generic array group
2823 * @param $keyGroup Main group for the key
2824 * @return $count Count of given group
2826 protected final function countGenericArray ($keyGroup) {
2828 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2831 if (!isset($this->genericArray[$keyGroup])) {
2833 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2838 $count = count($this->genericArray[$keyGroup]);
2841 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2848 * Count generic array sub group
2850 * @param $keyGroup Main group for the key
2851 * @param $subGroup Sub group for the key
2852 * @return $count Count of given group
2854 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2856 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2859 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2861 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2866 $count = count($this->genericArray[$keyGroup][$subGroup]);
2869 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2876 * Count generic array elements
2878 * @param $keyGroup Main group for the key
2879 * @param $subGroup Sub group for the key
2880 * @para $key Key to count
2881 * @return $count Count of given key
2883 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2885 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2888 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2890 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2892 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2894 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2899 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2902 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2909 * Getter for whole generic group array
2911 * @param $keyGroup Key group to get
2912 * @return $array Whole generic array group
2914 protected final function getGenericArray ($keyGroup) {
2916 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2919 if (!isset($this->genericArray[$keyGroup])) {
2921 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2926 return $this->genericArray[$keyGroup];
2930 * Setter for generic array key
2932 * @param $keyGroup Key group to get
2933 * @param $subGroup Sub group for the key
2934 * @param $key Key to unset
2935 * @param $value Mixed value from generic array element
2938 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2940 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2943 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2947 * Getter for generic array key
2949 * @param $keyGroup Key group to get
2950 * @param $subGroup Sub group for the key
2951 * @param $key Key to unset
2952 * @return $value Mixed value from generic array element
2954 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2956 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2959 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2961 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2966 return $this->genericArray[$keyGroup][$subGroup][$key];
2970 * Sets a value in given generic array key/element
2972 * @param $keyGroup Main group for the key
2973 * @param $subGroup Sub group for the key
2974 * @param $key Key to set
2975 * @param $element Element to set
2976 * @param $value Value to set
2979 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2981 //* 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));
2984 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2988 * Getter for generic array element
2990 * @param $keyGroup Key group to get
2991 * @param $subGroup Sub group for the key
2992 * @param $key Key to look for
2993 * @param $element Element to look for
2994 * @return $value Mixed value from generic array element
2996 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2998 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3001 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3003 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3008 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3012 * Checks if a given sub group is valid (array)
3014 * @param $keyGroup Key group to get
3015 * @param $subGroup Sub group for the key
3016 * @return $isValid Whether given sub group is valid
3018 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3020 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3023 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3030 * Checks if a given key is valid (array)
3032 * @param $keyGroup Key group to get
3033 * @param $subGroup Sub group for the key
3034 * @param $key Key to check
3035 * @return $isValid Whether given sub group is valid
3037 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3039 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3042 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3049 * Initializes the web output instance
3053 protected function initWebOutputInstance () {
3054 // Get application instance
3055 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
3057 // Init web output instance
3058 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3061 $this->setWebOutputInstance($outputInstance);
3065 * Translates boolean true to 'Y' and false to 'N'
3067 * @param $boolean Boolean value
3068 * @return $translated Translated boolean value
3070 public static final function translateBooleanToYesNo ($boolean) {
3071 // Make sure it is really boolean
3072 assert(is_bool($boolean));
3075 $translated = ($boolean === true) ? 'Y' : 'N';
3077 // ... and return it
3082 * Encodes raw data (almost any type) by "serializing" it and then pack it
3083 * into a "binary format".
3085 * @param $rawData Raw data (almost any type)
3086 * @return $encoded Encoded data
3088 protected function encodeData ($rawData) {
3089 // Make sure no objects or resources pass through
3090 assert(!is_object($rawData));
3091 assert(!is_resource($rawData));
3093 // First "serialize" it (json_encode() is faster than serialize())
3094 $encoded = $this->packString(json_encode($rawData));
3101 * Pack a string into a "binary format". Please execuse me that this is
3102 * widely undocumented. :-(
3104 * @param $str Unpacked string
3105 * @return $packed Packed string
3106 * @todo Improve documentation
3108 protected function packString ($str) {
3110 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3112 // First compress the string (gzcompress is okay)
3113 $str = gzcompress($str);
3118 // And start the "encoding" loop
3119 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3121 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3122 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3124 if (($idx + $i) <= strlen($str)) {
3125 $ord = ord(substr($str, ($idx + $i), 1));
3127 $add = $ord * pow(256, $factor);
3131 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3135 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3136 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3138 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3139 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3145 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3150 * Creates a full-qualified file name (FQFN) for given file name by adding
3151 * a configured temporary file path to it.
3153 * @param $infoInstance An instance of a SplFileInfo class
3154 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
3155 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3156 * @throws FileIoException If the file cannot be written
3158 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
3160 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
3162 // Is the path writeable?
3163 if (!is_writable($basePath)) {
3164 // Path is write-protected
3165 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3169 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
3172 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
3174 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
3178 return $tempInstance;
3182 * "Getter" for a printable state name
3184 * @return $stateName Name of the node's state in a printable format
3186 public final function getPrintableState () {
3187 // Default is 'null'
3188 $stateName = 'null';
3190 // Get the state instance
3191 $stateInstance = $this->getStateInstance();
3193 // Is it an instance of Stateable?
3194 if ($stateInstance instanceof Stateable) {
3195 // Then use that state name
3196 $stateName = $stateInstance->getStateName();