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\Manager\ManageableApplication;
34 use Org\Mxchange\CoreFramework\Middleware\Compressor\CompressorChannel;
35 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
36 use Org\Mxchange\CoreFramework\Parser\Parseable;
37 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
38 use Org\Mxchange\CoreFramework\Registry\Register;
39 use Org\Mxchange\CoreFramework\Resolver\Resolver;
40 use Org\Mxchange\CoreFramework\Result\Database\CachedDatabaseResult;
41 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
42 use Org\Mxchange\CoreFramework\Stacker\Stackable;
43 use Org\Mxchange\CoreFramework\State\Stateable;
44 use Org\Mxchange\CoreFramework\Stream\Input\InputStream;
45 use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
46 use Org\Mxchange\CoreFramework\Stream\Output\OutputStream;
47 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
48 use Org\Mxchange\CoreFramework\User\ManageableAccount;
49 use Org\Mxchange\CoreFramework\Visitor\Visitor;
53 use \InvalidArgumentException;
59 * The simulator system class is the super class of all other classes. This
60 * class handles saving of games etc.
62 * @author Roland Haeder <webmaster@shipsimu.org>
64 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
65 * @license GNU GPL 3.0 or any newer version
66 * @link http://www.shipsimu.org
68 * This program is free software: you can redistribute it and/or modify
69 * it under the terms of the GNU General Public License as published by
70 * the Free Software Foundation, either version 3 of the License, or
71 * (at your option) any later version.
73 * This program is distributed in the hope that it will be useful,
74 * but WITHOUT ANY WARRANTY; without even the implied warranty of
75 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
76 * GNU General Public License for more details.
78 * You should have received a copy of the GNU General Public License
79 * along with this program. If not, see <http://www.gnu.org/licenses/>.
81 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
83 * Length of output from hash()
85 private static $hashLength = NULL;
90 private $realClass = 'BaseFrameworkSystem';
93 * Search criteria instance
95 private $searchInstance = NULL;
98 * Update criteria instance
100 private $updateInstance = NULL;
103 * The file I/O instance for the template loader
105 private $fileIoInstance = NULL;
110 private $resolverInstance = NULL;
113 * Template engine instance
115 private $templateInstance = NULL;
118 * Database result instance
120 private $resultInstance = NULL;
123 * Instance for user class
125 private $userInstance = NULL;
128 * A controller instance
130 private $controllerInstance = NULL;
135 private $rngInstance = NULL;
138 * Instance of a crypto helper
140 private $cryptoInstance = NULL;
143 * Instance of an Iterator class
145 private $iteratorInstance = NULL;
148 * Instance of the list
150 private $listInstance = NULL;
155 private $menuInstance = NULL;
158 * Instance of the image
160 private $imageInstance = NULL;
163 * Instance of the stacker
165 private $stackInstance = NULL;
168 * A Compressor instance
170 private $compressorInstance = NULL;
173 * A Parseable instance
175 private $parserInstance = NULL;
178 * A database wrapper instance
180 private $databaseInstance = NULL;
183 * A helper instance for the form
185 private $helperInstance = NULL;
188 * An instance of a InputStream class
190 private $inputStreamInstance = NULL;
193 * An instance of a OutputStream class
195 private $outputStreamInstance = NULL;
200 private $handlerInstance = NULL;
203 * Visitor handler instance
205 private $visitorInstance = NULL;
208 * An instance of a database wrapper class
210 private $wrapperInstance = NULL;
213 * An instance of a file I/O pointer class (not handler)
215 private $pointerInstance = NULL;
218 * An instance of an Indexable class
220 private $indexInstance = NULL;
223 * An instance of a Block class
225 private $blockInstance = NULL;
230 private $minableInstance = NULL;
233 * A FrameworkDirectory instance
235 private $directoryInstance = NULL;
238 * The concrete output instance
240 private $outputInstance = NULL;
245 private $stateInstance = NULL;
248 * Registry instance (implementing Register)
250 private $registryInstance = NULL;
255 private $callbackInstance = NULL;
258 * Thousands separator
260 private $thousands = '.'; // German
265 private $decimals = ','; // German
270 private $socketResource = false;
273 * Regular expression to use for validation
275 private $regularExpression = '';
280 private $packageData = array();
285 private $genericArray = array();
290 private $commandName = '';
295 private $controllerName = '';
298 * Array with bitmasks and such for pack/unpack methods to support both
299 * 32-bit and 64-bit systems
301 private $packingData = array(
304 'left' => 0xffff0000,
305 'right' => 0x0000ffff,
311 'left' => 0xffffffff00000000,
312 'right' => 0x00000000ffffffff,
319 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
321 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
323 private $archArrayElement = false;
325 /***********************
326 * Exception codes.... *
327 ***********************/
329 // @todo Try to clean these constants up
330 const EXCEPTION_IS_NULL_POINTER = 0x001;
331 const EXCEPTION_IS_NO_OBJECT = 0x002;
332 const EXCEPTION_IS_NO_ARRAY = 0x003;
333 const EXCEPTION_MISSING_METHOD = 0x004;
334 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
335 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
336 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
337 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
338 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
339 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
340 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
341 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
342 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
343 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
344 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
345 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
346 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
347 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
348 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
349 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
350 const EXCEPTION_PATH_NOT_FOUND = 0x015;
351 const EXCEPTION_INVALID_PATH_NAME = 0x016;
352 const EXCEPTION_READ_PROTECED_PATH = 0x017;
353 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
354 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
355 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
356 const EXCEPTION_INVALID_RESOURCE = 0x01b;
357 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
358 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
359 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
360 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
361 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
362 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
363 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
364 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
365 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
366 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
367 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
368 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
369 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
370 const EXCEPTION_INVALID_STRING = 0x029;
371 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
372 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
373 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
374 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
375 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
376 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
377 const EXCEPTION_MISSING_ELEMENT = 0x030;
378 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
379 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
380 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
381 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
382 const EXCEPTION_FATAL_ERROR = 0x035;
383 const EXCEPTION_FILE_NOT_FOUND = 0x036;
384 const EXCEPTION_ASSERTION_FAILED = 0x037;
385 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
386 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
387 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
388 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
389 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
390 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
391 const EXCEPTION_INVALID_SOCKET = 0x03e;
394 * Hexadecimal->Decimal translation array
396 private static $hexdec = array(
416 * Decimal->hexadecimal translation array
418 private static $dechex = array(
438 * Startup time in miliseconds
440 private static $startupTime = 0;
443 * Protected super constructor
445 * @param $className Name of the class
448 protected function __construct ($className) {
450 $this->setRealClass($className);
452 // Set configuration instance if no registry ...
453 if (!$this instanceof Register) {
454 // ... because registries doesn't need to be configured
455 $this->setConfigInstance(FrameworkBootstrap::getConfigurationInstance());
458 // Is the startup time set? (0 cannot be true anymore)
459 if (self::$startupTime == 0) {
461 self::$startupTime = microtime(true);
465 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
469 * Destructor for all classes. You should not call this method on your own.
473 public function __destruct () {
474 // Flush any updated entries to the database
475 $this->flushPendingUpdates();
477 // Is this object already destroyed?
478 if ($this->__toString() != 'DestructedObject') {
479 // Destroy all informations about this class but keep some text about it alive
480 $this->setRealClass('DestructedObject');
481 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
482 // Already destructed object
483 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
487 // Do not call this twice
488 trigger_error(__METHOD__ . ': Called twice.');
494 * The __call() method where all non-implemented methods end up
496 * @param $methodName Name of the missing method
497 * @args $args Arguments passed to the method
500 public final function __call ($methodName, $args) {
501 return self::__callStatic($methodName, $args);
505 * The __callStatic() method where all non-implemented static methods end up
507 * @param $methodName Name of the missing method
508 * @args $args Arguments passed to the method
511 public static final function __callStatic ($methodName, $args) {
513 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
515 // Init argument string
518 // Is it NULL, empty or an array?
519 if (is_null($args)) {
521 $argsString = 'NULL';
522 } elseif (is_array($args)) {
526 // Some arguments are there
527 foreach ($args as $arg) {
528 // Add data about the argument
529 $argsString .= gettype($arg) . ':';
532 // Found a NULL argument
533 $argsString .= 'NULL';
534 } elseif (is_string($arg)) {
535 // Add length for strings
536 $argsString .= strlen($arg);
537 } elseif ((is_int($arg)) || (is_float($arg))) {
540 } elseif (is_array($arg)) {
541 // .. or size if array
542 $argsString .= count($arg);
543 } elseif (is_object($arg)) {
545 $reflection = new ReflectionClass($arg);
547 // Is an other object, maybe no __toString() available
548 $argsString .= $reflection->getName();
549 } elseif ($arg === true) {
550 // ... is boolean 'true'
551 $argsString .= 'true';
552 } elseif ($arg === false) {
553 // ... is boolean 'false'
554 $argsString .= 'false';
557 // Comma for next one
562 if (substr($argsString, -2, 1) == ',') {
563 $argsString = substr($argsString, 0, -2);
569 // Invalid arguments!
570 $argsString = '!INVALID:' . gettype($args) . '!';
573 // Output stub message
574 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
575 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
585 * Getter for $realClass
587 * @return $realClass The name of the real class (not BaseFrameworkSystem)
589 public function __toString () {
590 return $this->realClass;
594 * Magic method to catch setting of missing but set class fields/attributes
596 * @param $name Name of the field/attribute
597 * @param $value Value to store
600 public final function __set ($name, $value) {
601 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
604 print_r($value, true)
609 * Magic method to catch getting of missing fields/attributes
611 * @param $name Name of the field/attribute
614 public final function __get ($name) {
615 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
621 * Magic method to catch unsetting of missing fields/attributes
623 * @param $name Name of the field/attribute
626 public final function __unset ($name) {
627 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
633 * Magic method to catch object serialization
635 * @return $unsupported Unsupported method
636 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
638 public final function __sleep () {
639 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
643 * Magic method to catch object deserialization
645 * @return $unsupported Unsupported method
646 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
648 public final function __wakeup () {
649 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
653 * Magic method to catch calls when an object instance is called
655 * @return $unsupported Unsupported method
656 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
658 public final function __invoke () {
659 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
663 * Setter for the real class name
665 * @param $realClass Class name (string)
668 public final function setRealClass ($realClass) {
670 $this->realClass = (string) $realClass;
674 * Setter for database result instance
676 * @param $resultInstance An instance of a database result class
678 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
680 protected final function setResultInstance (SearchableResult $resultInstance) {
681 $this->resultInstance = $resultInstance;
685 * Getter for database result instance
687 * @return $resultInstance An instance of a database result class
689 public final function getResultInstance () {
690 return $this->resultInstance;
694 * Setter for template engine instances
696 * @param $templateInstance An instance of a template engine class
699 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
700 $this->templateInstance = $templateInstance;
704 * Getter for template engine instances
706 * @return $templateInstance An instance of a template engine class
708 protected final function getTemplateInstance () {
709 return $this->templateInstance;
713 * Setter for search instance
715 * @param $searchInstance Searchable criteria instance
718 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
719 $this->searchInstance = $searchInstance;
723 * Getter for search instance
725 * @return $searchInstance Searchable criteria instance
727 public final function getSearchInstance () {
728 return $this->searchInstance;
732 * Setter for update instance
734 * @param $updateInstance An instance of a LocalUpdateCriteria clase
737 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
738 $this->updateInstance = $updateInstance;
742 * Getter for update instance
744 * @return $updateInstance Updateable criteria instance
746 public final function getUpdateInstance () {
747 return $this->updateInstance;
751 * Setter for resolver instance
753 * @param $resolverInstance Instance of a command resolver class
756 public final function setResolverInstance (Resolver $resolverInstance) {
757 $this->resolverInstance = $resolverInstance;
761 * Getter for resolver instance
763 * @return $resolverInstance Instance of a command resolver class
765 public final function getResolverInstance () {
766 return $this->resolverInstance;
770 * Setter for language instance
772 * @param $configInstance The configuration instance which shall
773 * be FrameworkConfiguration
776 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
777 GenericRegistry::getRegistry()->addInstance('config', $configInstance);
781 * Getter for configuration instance
783 * @return $configInstance Configuration instance
785 public final function getConfigInstance () {
786 $configInstance = GenericRegistry::getRegistry()->getInstance('config');
787 return $configInstance;
791 * Setter for debug instance
793 * @param $debugInstance The instance for debug output class
796 public final function setDebugInstance (DebugMiddleware $debugInstance) {
797 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
801 * Getter for debug instance
803 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
805 public final function getDebugInstance () {
806 // Get debug instance
807 $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
810 return $debugInstance;
814 * Setter for web output instance
816 * @param $webInstance The instance for web output class
819 public final function setWebOutputInstance (OutputStreamer $webInstance) {
820 GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
824 * Getter for web output instance
826 * @return $webOutputInstance - Instance to class WebOutput
828 public final function getWebOutputInstance () {
829 $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
830 return $webOutputInstance;
834 * Setter for database instance
836 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
839 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
840 GenericRegistry::getRegistry()->addInstance('db_instance', $databaseInstance);
844 * Getter for database layer
846 * @return $databaseInstance The database layer instance
848 public final function getDatabaseInstance () {
850 $databaseInstance = GenericRegistry::getRegistry()->getInstance('db_instance');
853 return $databaseInstance;
857 * Setter for compressor channel
859 * @param $compressorInstance An instance of CompressorChannel
862 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
863 GenericRegistry::getRegistry()->addInstance('compressor', $compressorInstance);
867 * Getter for compressor channel
869 * @return $compressorInstance The compressor channel
871 public final function getCompressorChannel () {
872 $compressorInstance = GenericRegistry::getRegistry()->getInstance('compressor');
873 return $compressorInstance;
877 * Protected getter for a manageable application helper class
879 * @return $applicationInstance An instance of a manageable application helper class
881 protected final function getApplicationInstance () {
882 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
883 return $applicationInstance;
887 * Setter for a manageable application helper class
889 * @param $applicationInstance An instance of a manageable application helper class
892 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
893 GenericRegistry::getRegistry()->addInstance('application', $applicationInstance);
897 * Private getter for language instance
899 * @return $langInstance An instance to the language sub-system
901 protected final function getLanguageInstance () {
902 $langInstance = GenericRegistry::getRegistry()->getInstance('language');
903 return $langInstance;
907 * Setter for language instance
909 * @param $langInstance An instance to the language sub-system
911 * @see LanguageSystem
913 public final function setLanguageInstance (ManageableLanguage $langInstance) {
914 GenericRegistry::getRegistry()->addInstance('language', $langInstance);
918 * Private getter for file IO instance
920 * @return $fileIoInstance An instance to the file I/O sub-system
922 protected final function getFileIoInstance () {
923 return $this->fileIoInstance;
927 * Setter for file I/O instance
929 * @param $fileIoInstance An instance to the file I/O sub-system
932 public final function setFileIoInstance (IoHandler $fileIoInstance) {
933 $this->fileIoInstance = $fileIoInstance;
937 * Protected setter for user instance
939 * @param $userInstance An instance of a user class
942 protected final function setUserInstance (ManageableAccount $userInstance) {
943 $this->userInstance = $userInstance;
947 * Getter for user instance
949 * @return $userInstance An instance of a user class
951 public final function getUserInstance () {
952 return $this->userInstance;
956 * Setter for controller instance (this surely breaks a bit the MVC patterm)
958 * @param $controllerInstance An instance of the controller
961 public final function setControllerInstance (Controller $controllerInstance) {
962 $this->controllerInstance = $controllerInstance;
966 * Getter for controller instance (this surely breaks a bit the MVC patterm)
968 * @return $controllerInstance An instance of the controller
970 public final function getControllerInstance () {
971 return $this->controllerInstance;
975 * Setter for RNG instance
977 * @param $rngInstance An instance of a random number generator (RNG)
980 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
981 $this->rngInstance = $rngInstance;
985 * Getter for RNG instance
987 * @return $rngInstance An instance of a random number generator (RNG)
989 public final function getRngInstance () {
990 return $this->rngInstance;
994 * Setter for Cryptable instance
996 * @param $cryptoInstance An instance of a Cryptable class
999 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1000 $this->cryptoInstance = $cryptoInstance;
1004 * Getter for Cryptable instance
1006 * @return $cryptoInstance An instance of a Cryptable class
1008 public final function getCryptoInstance () {
1009 return $this->cryptoInstance;
1013 * Setter for the list instance
1015 * @param $listInstance A list of Listable
1018 protected final function setListInstance (Listable $listInstance) {
1019 $this->listInstance = $listInstance;
1023 * Getter for the list instance
1025 * @return $listInstance A list of Listable
1027 protected final function getListInstance () {
1028 return $this->listInstance;
1032 * Setter for the menu instance
1034 * @param $menuInstance A RenderableMenu instance
1037 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1038 $this->menuInstance = $menuInstance;
1042 * Getter for the menu instance
1044 * @return $menuInstance A RenderableMenu instance
1046 protected final function getMenuInstance () {
1047 return $this->menuInstance;
1051 * Setter for image instance
1053 * @param $imageInstance An instance of an image
1056 public final function setImageInstance (BaseImage $imageInstance) {
1057 $this->imageInstance = $imageInstance;
1061 * Getter for image instance
1063 * @return $imageInstance An instance of an image
1065 public final function getImageInstance () {
1066 return $this->imageInstance;
1070 * Setter for stacker instance
1072 * @param $stackInstance An instance of an stacker
1075 public final function setStackInstance (Stackable $stackInstance) {
1076 $this->stackInstance = $stackInstance;
1080 * Getter for stacker instance
1082 * @return $stackInstance An instance of an stacker
1084 public final function getStackInstance () {
1085 return $this->stackInstance;
1089 * Setter for compressor instance
1091 * @param $compressorInstance An instance of an compressor
1094 public final function setCompressorInstance (Compressor $compressorInstance) {
1095 $this->compressorInstance = $compressorInstance;
1099 * Getter for compressor instance
1101 * @return $compressorInstance An instance of an compressor
1103 public final function getCompressorInstance () {
1104 return $this->compressorInstance;
1108 * Setter for Parseable instance
1110 * @param $parserInstance An instance of an Parseable
1113 public final function setParserInstance (Parseable $parserInstance) {
1114 $this->parserInstance = $parserInstance;
1118 * Getter for Parseable instance
1120 * @return $parserInstance An instance of an Parseable
1122 public final function getParserInstance () {
1123 return $this->parserInstance;
1127 * Setter for DatabaseWrapper instance
1129 * @param $wrapperInstance An instance of an DatabaseWrapper
1132 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1133 $this->wrapperInstance = $wrapperInstance;
1137 * Getter for DatabaseWrapper instance
1139 * @return $wrapperInstance An instance of an DatabaseWrapper
1141 public final function getWrapperInstance () {
1142 return $this->wrapperInstance;
1146 * Setter for socket resource
1148 * @param $socketResource A valid socket resource
1151 public final function setSocketResource ($socketResource) {
1152 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1153 $this->socketResource = $socketResource;
1157 * Getter for socket resource
1159 * @return $socketResource A valid socket resource
1161 public final function getSocketResource () {
1162 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1163 return $this->socketResource;
1167 * Setter for regular expression
1169 * @param $regularExpression A valid regular expression
1172 public final function setRegularExpression ($regularExpression) {
1173 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1174 $this->regularExpression = $regularExpression;
1178 * Getter for regular expression
1180 * @return $regularExpression A valid regular expression
1182 public final function getRegularExpression () {
1183 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1184 return $this->regularExpression;
1188 * Setter for helper instance
1190 * @param $helperInstance An instance of a helper class
1193 protected final function setHelperInstance (Helper $helperInstance) {
1194 $this->helperInstance = $helperInstance;
1198 * Getter for helper instance
1200 * @return $helperInstance An instance of a helper class
1202 public final function getHelperInstance () {
1203 return $this->helperInstance;
1207 * Getter for a InputStream instance
1209 * @param $inputStreamInstance The InputStream instance
1211 protected final function getInputStreamInstance () {
1212 return $this->inputStreamInstance;
1216 * Setter for a InputStream instance
1218 * @param $inputStreamInstance The InputStream instance
1221 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1222 $this->inputStreamInstance = $inputStreamInstance;
1226 * Getter for a OutputStream instance
1228 * @param $outputStreamInstance The OutputStream instance
1230 protected final function getOutputStreamInstance () {
1231 return $this->outputStreamInstance;
1235 * Setter for a OutputStream instance
1237 * @param $outputStreamInstance The OutputStream instance
1240 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1241 $this->outputStreamInstance = $outputStreamInstance;
1245 * Setter for handler instance
1247 * @param $handlerInstance An instance of a Handleable class
1250 protected final function setHandlerInstance (Handleable $handlerInstance) {
1251 $this->handlerInstance = $handlerInstance;
1255 * Getter for handler instance
1257 * @return $handlerInstance A Handleable instance
1259 protected final function getHandlerInstance () {
1260 return $this->handlerInstance;
1264 * Setter for visitor instance
1266 * @param $visitorInstance A Visitor instance
1269 protected final function setVisitorInstance (Visitor $visitorInstance) {
1270 $this->visitorInstance = $visitorInstance;
1274 * Getter for visitor instance
1276 * @return $visitorInstance A Visitor instance
1278 protected final function getVisitorInstance () {
1279 return $this->visitorInstance;
1283 * Setter for raw package Data
1285 * @param $packageData Raw package Data
1288 public final function setPackageData (array $packageData) {
1289 $this->packageData = $packageData;
1293 * Getter for raw package Data
1295 * @return $packageData Raw package Data
1297 public function getPackageData () {
1298 return $this->packageData;
1303 * Setter for Iterator instance
1305 * @param $iteratorInstance An instance of an Iterator
1308 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1309 $this->iteratorInstance = $iteratorInstance;
1313 * Getter for Iterator instance
1315 * @return $iteratorInstance An instance of an Iterator
1317 public final function getIteratorInstance () {
1318 return $this->iteratorInstance;
1322 * Setter for FilePointer instance
1324 * @param $pointerInstance An instance of an FilePointer class
1327 protected final function setPointerInstance (FilePointer $pointerInstance) {
1328 $this->pointerInstance = $pointerInstance;
1332 * Getter for FilePointer instance
1334 * @return $pointerInstance An instance of an FilePointer class
1336 public final function getPointerInstance () {
1337 return $this->pointerInstance;
1341 * Unsets pointer instance which triggers a call of __destruct() if the
1342 * instance is still there. This is surely not fatal on already "closed"
1343 * file pointer instances.
1345 * I don't want to mess around with above setter by giving it a default
1346 * value NULL as setter should always explicitly only set (existing) object
1347 * instances and NULL is NULL.
1351 protected final function unsetPointerInstance () {
1352 // Simply it to NULL
1353 $this->pointerInstance = NULL;
1357 * Setter for Indexable instance
1359 * @param $indexInstance An instance of an Indexable class
1362 protected final function setIndexInstance (Indexable $indexInstance) {
1363 $this->indexInstance = $indexInstance;
1367 * Getter for Indexable instance
1369 * @return $indexInstance An instance of an Indexable class
1371 public final function getIndexInstance () {
1372 return $this->indexInstance;
1376 * Setter for Block instance
1378 * @param $blockInstance An instance of an Block class
1381 protected final function setBlockInstance (Block $blockInstance) {
1382 $this->blockInstance = $blockInstance;
1386 * Getter for Block instance
1388 * @return $blockInstance An instance of an Block class
1390 public final function getBlockInstance () {
1391 return $this->blockInstance;
1395 * Setter for Minable instance
1397 * @param $minableInstance A Minable instance
1400 protected final function setMinableInstance (Minable $minableInstance) {
1401 $this->minableInstance = $minableInstance;
1405 * Getter for minable instance
1407 * @return $minableInstance A Minable instance
1409 protected final function getMinableInstance () {
1410 return $this->minableInstance;
1414 * Setter for FrameworkDirectory instance
1416 * @param $directoryInstance A FrameworkDirectory instance
1419 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1420 $this->directoryInstance = $directoryInstance;
1424 * Getter for FrameworkDirectory instance
1426 * @return $directoryInstance A FrameworkDirectory instance
1428 protected final function getDirectoryInstance () {
1429 return $this->directoryInstance;
1433 * Setter for state instance
1435 * @param $stateInstance A Stateable instance
1438 public final function setStateInstance (Stateable $stateInstance) {
1439 $this->stateInstance = $stateInstance;
1443 * Getter for state instance
1445 * @return $stateInstance A Stateable instance
1447 public final function getStateInstance () {
1448 return $this->stateInstance;
1452 * Setter for output instance
1454 * @param $outputInstance The debug output instance
1457 public final function setOutputInstance (OutputStreamer $outputInstance) {
1458 $this->outputInstance = $outputInstance;
1462 * Getter for output instance
1464 * @return $outputInstance The debug output instance
1466 public final function getOutputInstance () {
1467 return $this->outputInstance;
1471 * Setter for registry instance
1473 * @param $registryInstance An instance of a Register class
1476 protected final function setRegistryInstance (Register $registryInstance) {
1477 $this->registryInstance = $registryInstance;
1481 * Getter for registry instance
1483 * @return $registryInstance The debug registry instance
1485 public final function getRegistryInstance () {
1486 return $this->registryInstance;
1490 * Setter for call-back instance
1492 * @param $callbackInstance An instance of a FrameworkInterface class
1495 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1496 $this->callbackInstance = $callbackInstance;
1500 * Getter for call-back instance
1502 * @return $callbackInstance An instance of a FrameworkInterface class
1504 protected final function getCallbackInstance () {
1505 return $this->callbackInstance;
1509 * Setter for command name
1511 * @param $commandName Last validated command name
1514 protected final function setCommandName ($commandName) {
1515 $this->commandName = $commandName;
1519 * Getter for command name
1521 * @return $commandName Last validated command name
1523 protected final function getCommandName () {
1524 return $this->commandName;
1528 * Setter for controller name
1530 * @param $controllerName Last validated controller name
1533 protected final function setControllerName ($controllerName) {
1534 $this->controllerName = $controllerName;
1538 * Getter for controller name
1540 * @return $controllerName Last validated controller name
1542 protected final function getControllerName () {
1543 return $this->controllerName;
1547 * Checks whether an object equals this object. You should overwrite this
1548 * method to implement own equality checks
1550 * @param $objectInstance An instance of a FrameworkInterface object
1551 * @return $equals Whether both objects equals
1553 public function equals (FrameworkInterface $objectInstance) {
1556 $this->__toString() == $objectInstance->__toString()
1558 $this->hashCode() == $objectInstance->hashCode()
1561 // Return the result
1566 * Generates a generic hash code of this class. You should really overwrite
1567 * this method with your own hash code generator code. But keep KISS in mind.
1569 * @return $hashCode A generic hash code respresenting this whole class
1571 public function hashCode () {
1573 return crc32($this->__toString());
1577 * Formats computer generated price values into human-understandable formats
1578 * with thousand and decimal separators.
1580 * @param $value The in computer format value for a price
1581 * @param $currency The currency symbol (use HTML-valid characters!)
1582 * @param $decNum Number of decimals after commata
1583 * @return $price The for the current language formated price string
1584 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1585 * thousands separator
1588 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1589 // Are all required attriutes set?
1590 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1591 // Throw an exception
1592 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1596 $value = (float) $value;
1598 // Reformat the US number
1599 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1601 // Return as string...
1606 * Appends a trailing slash to a string
1608 * @param $str A string (maybe) without trailing slash
1609 * @return $str A string with an auto-appended trailing slash
1611 public final function addMissingTrailingSlash ($str) {
1612 // Is there a trailing slash?
1613 if (substr($str, -1, 1) != '/') {
1617 // Return string with trailing slash
1622 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1623 * application helper instance (ApplicationHelper by default).
1625 * @param $applicationInstance An application helper instance or
1626 * null if we shall use the default
1627 * @return $templateInstance The template engine instance
1628 * @throws NullPointerException If the discovered application
1629 * instance is still null
1631 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1632 // Is the application instance set?
1633 if (is_null($applicationInstance)) {
1634 // Get the current instance
1635 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1638 if (is_null($applicationInstance)) {
1639 // Thrown an exception
1640 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1644 // Initialize the template engine
1645 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1647 // Return the prepared instance
1648 return $templateInstance;
1652 * Debugs this instance by putting out it's full content
1654 * @param $message Optional message to show in debug output
1657 public final function debugInstance ($message = '') {
1658 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1659 restore_error_handler();
1664 // Is a message set?
1665 if (!empty($message)) {
1666 // Construct message
1667 $content = sprintf('<div class="debug_message">
1669 </div>' . PHP_EOL, $message);
1672 // Generate the output
1673 $content .= sprintf('<pre>%s</pre>',
1676 print_r($this, true)
1682 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1685 <div class="debug_content">
1689 <div class="debug_include_list">
1692 $this->__toString(),
1694 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1699 * Replaces control characters with printable output
1701 * @param $str String with control characters
1702 * @return $str Replaced string
1704 protected function replaceControlCharacters ($str) {
1707 chr(13), '[r]', str_replace(
1708 chr(10), '[n]', str_replace(
1718 * Output a partial stub message for the caller method
1720 * @param $message An optional message to display
1723 protected function partialStub ($message = '') {
1725 $stubMessage = 'Partial Stub!';
1727 // Is the extra message given?
1728 if (!empty($message)) {
1729 // Then add it as well
1730 $stubMessage .= ' Message: ' . $message;
1733 // Debug instance is there?
1734 if (!is_null($this->getDebugInstance())) {
1735 // Output stub message
1736 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1739 trigger_error($stubMessage);
1745 * Outputs a debug backtrace and stops further script execution
1747 * @param $message An optional message to output
1748 * @param $doExit Whether exit the program (true is default)
1751 public function debugBackTrace ($message = '', $doExit = true) {
1752 // Sorry, there is no other way getting this nice backtrace
1753 if (!empty($message)) {
1755 printf('Message: %s<br />' . PHP_EOL, $message);
1759 debug_print_backtrace();
1763 if ($doExit === true) {
1769 * Creates an instance of a debugger instance
1771 * @param $className Name of the class (currently unsupported)
1772 * @param $lineNumber Line number where the call was made
1773 * @return $debugInstance An instance of a debugger class
1774 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1776 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1777 // Is the instance set?
1778 if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
1779 // Init debug instance
1780 $debugInstance = NULL;
1784 // Get a debugger instance
1785 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1786 } catch (NullPointerException $e) {
1787 // Didn't work, no instance there
1788 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1791 // Empty string should be ignored and used for testing the middleware
1792 DebugMiddleware::getSelfInstance()->output('');
1794 // Set it in registry
1795 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
1797 // Get instance from registry
1798 $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
1802 return $debugInstance;
1806 * Simple output of a message with line-break
1808 * @param $message Message to output
1811 public function outputLine ($message) {
1813 print($message . PHP_EOL);
1817 * Outputs a debug message whether to debug instance (should be set!) or
1818 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1819 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1821 * @param $message Message we shall send out...
1822 * @param $doPrint Whether print or die here (default: print)
1823 * @paran $stripTags Whether to strip tags (default: false)
1826 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1827 // Set debug instance to NULL
1828 $debugInstance = NULL;
1831 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1833 // Is function partialStub/__callStatic ?
1834 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1835 // Prepend class::function:line from 3rd element
1836 $message = sprintf('[%s::%s:%d]: %s',
1837 $backtrace[2]['class'],
1838 $backtrace[2]['function'],
1839 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1843 // Prepend class::function:line from 2nd element
1844 $message = sprintf('[%s::%s:%d]: %s',
1845 $backtrace[1]['class'],
1846 $backtrace[1]['function'],
1847 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1854 // Get debug instance
1855 $debugInstance = $this->getDebugInstance();
1856 } catch (NullPointerException $e) {
1857 // The debug instance is not set (yet)
1860 // Is the debug instance there?
1861 if (is_object($debugInstance)) {
1862 // Use debug output handler
1863 $debugInstance->output($message, $stripTags);
1865 if ($doPrint === false) {
1866 // Die here if not printed
1870 // Are debug times enabled?
1871 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1873 $message = $this->getPrintableExecutionTime() . $message;
1877 if ($doPrint === true) {
1879 $this->outputLine($message);
1888 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1890 * @param $str The string, what ever it is needs to be converted
1891 * @return $className Generated class name
1893 public static final function convertToClassName ($str) {
1897 // Convert all dashes in underscores
1898 $str = self::convertDashesToUnderscores($str);
1900 // Now use that underscores to get classname parts for hungarian style
1901 foreach (explode('_', $str) as $strPart) {
1902 // Make the class name part lower case and first upper case
1903 $className .= ucfirst(strtolower($strPart));
1906 // Return class name
1911 * Converts dashes to underscores, e.g. useable for configuration entries
1913 * @param $str The string with maybe dashes inside
1914 * @return $str The converted string with no dashed, but underscores
1915 * @throws NullPointerException If $str is null
1916 * @throws InvalidArgumentException If $str is empty
1918 public static function convertDashesToUnderscores ($str) {
1920 if (is_null($str)) {
1922 throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
1923 } elseif (!is_string($str)) {
1925 throw new InvalidArgumentException(sprintf('str[]=%s is not a string', gettype($str)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
1926 } elseif ((is_string($str)) && (empty($str))) {
1928 throw new InvalidArgumentException('str is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
1932 $str = str_replace('-', '_', $str);
1934 // Return converted string
1939 * Marks up the code by adding e.g. line numbers
1941 * @param $phpCode Unmarked PHP code
1942 * @return $markedCode Marked PHP code
1944 public function markupCode ($phpCode) {
1949 $errorArray = error_get_last();
1951 // Init the code with error message
1952 if (is_array($errorArray)) {
1954 $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>',
1955 basename($errorArray['file']),
1956 $errorArray['line'],
1957 $errorArray['message'],
1962 // Add line number to the code
1963 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1965 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1967 htmlentities($code, ENT_QUOTES)
1976 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1977 * beatiful for web-based front-ends. If null is given a message id
1978 * null_timestamp will be resolved and returned.
1980 * @param $timestamp Timestamp to prepare (filter) for display
1981 * @return $readable A readable timestamp
1983 public function doFilterFormatTimestamp ($timestamp) {
1984 // Default value to return
1987 // Is the timestamp null?
1988 if (is_null($timestamp)) {
1989 // Get a message string
1990 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1992 switch ($this->getLanguageInstance()->getLanguageCode()) {
1993 case 'de': // German format is a bit different to default
1994 // Split the GMT stamp up
1995 $dateTime = explode(' ', $timestamp );
1996 $dateArray = explode('-', $dateTime[0]);
1997 $timeArray = explode(':', $dateTime[1]);
1999 // Construct the timestamp
2000 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2010 default: // Default is pass-through
2011 $readable = $timestamp;
2021 * Filter a given number into a localized number
2023 * @param $value The raw value from e.g. database
2024 * @return $localized Localized value
2026 public function doFilterFormatNumber ($value) {
2027 // Generate it from config and localize dependencies
2028 switch ($this->getLanguageInstance()->getLanguageCode()) {
2029 case 'de': // German format is a bit different to default
2030 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2033 default: // US, etc.
2034 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2043 * "Getter" for databse entry
2045 * @return $entry An array with database entries
2046 * @throws NullPointerException If the database result is not found
2047 * @throws InvalidDatabaseResultException If the database result is invalid
2049 protected final function getDatabaseEntry () {
2050 // Is there an instance?
2051 if (!$this->getResultInstance() instanceof SearchableResult) {
2052 // Throw an exception here
2053 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2057 $this->getResultInstance()->rewind();
2059 // Do we have an entry?
2060 if ($this->getResultInstance()->valid() === false) {
2061 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2062 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2066 $this->getResultInstance()->next();
2069 $entry = $this->getResultInstance()->current();
2076 * Getter for field name
2078 * @param $fieldName Field name which we shall get
2079 * @return $fieldValue Field value from the user
2080 * @throws NullPointerException If the result instance is null
2082 public final function getField ($fieldName) {
2083 // Default field value
2086 // Get result instance
2087 $resultInstance = $this->getResultInstance();
2089 // Is this instance null?
2090 if (is_null($resultInstance)) {
2091 // Then the user instance is no longer valid (expired cookies?)
2092 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2095 // Get current array
2096 $fieldArray = $resultInstance->current();
2097 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2099 // Convert dashes to underscore
2100 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2102 // Does the field exist?
2103 if ($this->isFieldSet($fieldName)) {
2105 $fieldValue = $fieldArray[$fieldName2];
2106 } elseif (defined('DEVELOPER')) {
2107 // Missing field entry, may require debugging
2108 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2110 // Missing field entry, may require debugging
2111 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2119 * Checks if given field is set
2121 * @param $fieldName Field name to check
2122 * @return $isSet Whether the given field name is set
2123 * @throws NullPointerException If the result instance is null
2125 public function isFieldSet ($fieldName) {
2126 // Get result instance
2127 $resultInstance = $this->getResultInstance();
2129 // Is this instance null?
2130 if (is_null($resultInstance)) {
2131 // Then the user instance is no longer valid (expired cookies?)
2132 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2135 // Get current array
2136 $fieldArray = $resultInstance->current();
2137 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2139 // Convert dashes to underscore
2140 $fieldName = self::convertDashesToUnderscores($fieldName);
2143 $isSet = isset($fieldArray[$fieldName]);
2150 * Flushs all pending updates to the database layer
2154 public function flushPendingUpdates () {
2155 // Get result instance
2156 $resultInstance = $this->getResultInstance();
2158 // Do we have data to update?
2159 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2160 // Get wrapper class name config entry
2161 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2163 // Create object instance
2164 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2166 // Yes, then send the whole result to the database layer
2167 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2172 * Outputs a deprecation warning to the developer.
2174 * @param $message The message we shall output to the developer
2176 * @todo Write a logging mechanism for productive mode
2178 public function deprecationWarning ($message) {
2179 // Is developer mode active?
2180 if (defined('DEVELOPER')) {
2181 // Debug instance is there?
2182 if (!is_null($this->getDebugInstance())) {
2183 // Output stub message
2184 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2187 trigger_error($message . "<br />\n");
2191 // @TODO Finish this part!
2192 $this->partialStub('Developer mode inactive. Message:' . $message);
2197 * Checks whether the given PHP extension is loaded
2199 * @param $phpExtension The PHP extension we shall check
2200 * @return $isLoaded Whether the PHP extension is loaded
2202 public final function isPhpExtensionLoaded ($phpExtension) {
2204 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2211 * "Getter" as a time() replacement but with milliseconds. You should use this
2212 * method instead of the encapsulated getimeofday() function.
2214 * @return $milliTime Timestamp with milliseconds
2216 public function getMilliTime () {
2217 // Get the time of day as float
2218 $milliTime = gettimeofday(true);
2225 * Idles (sleeps) for given milliseconds
2227 * @return $hasSlept Whether it goes fine
2229 public function idle ($milliSeconds) {
2230 // Sleep is fine by default
2233 // Idle so long with found function
2234 if (function_exists('time_sleep_until')) {
2235 // Get current time and add idle time
2236 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2238 // New PHP 5.1.0 function found, ignore errors
2239 $hasSlept = @time_sleep_until($sleepUntil);
2242 * My Sun station doesn't have that function even with latest PHP
2245 usleep($milliSeconds * 1000);
2252 * Converts a hexadecimal string, even with negative sign as first string to
2253 * a decimal number using BC functions.
2255 * This work is based on comment #86673 on php.net documentation page at:
2256 * <http://de.php.net/manual/en/function.dechex.php#86673>
2258 * @param $hex Hexadecimal string
2259 * @return $dec Decimal number
2261 protected function hex2dec ($hex) {
2262 // Convert to all lower-case
2263 $hex = strtolower($hex);
2265 // Detect sign (negative/positive numbers)
2267 if (substr($hex, 0, 1) == '-') {
2269 $hex = substr($hex, 1);
2272 // Decode the hexadecimal string into a decimal number
2274 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2275 $factor = self::$hexdec[substr($hex, $i, 1)];
2276 $dec = bcadd($dec, bcmul($factor, $e));
2279 // Return the decimal number
2280 return $sign . $dec;
2284 * Converts even very large decimal numbers, also signed, to a hexadecimal
2287 * This work is based on comment #97756 on php.net documentation page at:
2288 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2290 * @param $dec Decimal number, even with negative sign
2291 * @param $maxLength Optional maximum length of the string
2292 * @return $hex Hexadecimal string
2294 protected function dec2hex ($dec, $maxLength = 0) {
2295 // maxLength can be zero or devideable by 2
2296 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2298 // Detect sign (negative/positive numbers)
2305 // Encode the decimal number into a hexadecimal string
2308 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2310 } while ($dec >= 1);
2313 * Leading zeros are required for hex-decimal "numbers". In some
2314 * situations more leading zeros are wanted, so check for both
2317 if ($maxLength > 0) {
2318 // Prepend more zeros
2319 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2320 } elseif ((strlen($hex) % 2) != 0) {
2321 // Only make string's length dividable by 2
2325 // Return the hexadecimal string
2326 return $sign . $hex;
2330 * Converts a ASCII string (0 to 255) into a decimal number.
2332 * @param $asc The ASCII string to be converted
2333 * @return $dec Decimal number
2335 protected function asc2dec ($asc) {
2336 // Convert it into a hexadecimal number
2337 $hex = bin2hex($asc);
2339 // And back into a decimal number
2340 $dec = $this->hex2dec($hex);
2347 * Converts a decimal number into an ASCII string.
2349 * @param $dec Decimal number
2350 * @return $asc An ASCII string
2352 protected function dec2asc ($dec) {
2353 // First convert the number into a hexadecimal string
2354 $hex = $this->dec2hex($dec);
2356 // Then convert it into the ASCII string
2357 $asc = $this->hex2asc($hex);
2364 * Converts a hexadecimal number into an ASCII string. Negative numbers
2367 * @param $hex Hexadecimal string
2368 * @return $asc An ASCII string
2370 protected function hex2asc ($hex) {
2371 // Check for length, it must be devideable by 2
2372 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2373 assert((strlen($hex) % 2) == 0);
2377 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2378 // Get the decimal number of the chunk
2379 $part = hexdec(substr($hex, $idx, 2));
2381 // Add it to the final string
2385 // Return the final string
2390 * Checks whether the given encoded data was encoded with Base64
2392 * @param $encodedData Encoded data we shall check
2393 * @return $isBase64 Whether the encoded data is Base64
2395 protected function isBase64Encoded ($encodedData) {
2397 $isBase64 = (@base64_decode($encodedData, true) !== false);
2404 * Gets a cache key from Criteria instance
2406 * @param $criteriaInstance An instance of a Criteria class
2407 * @param $onlyKeys Only use these keys for a cache key
2408 * @return $cacheKey A cache key suitable for lookup/storage purposes
2410 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2412 $cacheKey = sprintf('%s@%s',
2413 $this->__toString(),
2414 $criteriaInstance->getCacheKey($onlyKeys)
2418 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2423 * Getter for startup time in miliseconds
2425 * @return $startupTime Startup time in miliseconds
2427 protected function getStartupTime () {
2428 return self::$startupTime;
2432 * "Getter" for a printable currently execution time in nice braces
2434 * @return $executionTime Current execution time in nice braces
2436 protected function getPrintableExecutionTime () {
2437 // Caculate the execution time
2438 $executionTime = microtime(true) - $this->getStartupTime();
2440 // Pack it in nice braces
2441 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2444 return $executionTime;
2448 * Hashes a given string with a simple but stronger hash function (no salt)
2449 * and hex-encode it.
2451 * @param $str The string to be hashed
2452 * @return $hash The hash from string $str
2454 public static final function hash ($str) {
2455 // Hash given string with (better secure) hasher
2456 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2463 * "Getter" for length of hash() output. This will be "cached" to speed up
2466 * @return $length Length of hash() output
2468 public static final function getHashLength () {
2470 if (is_null(self::$hashLength)) {
2471 // No, then hash a string and save its length.
2472 self::$hashLength = strlen(self::hash('abc123'));
2476 return self::$hashLength;
2480 * Checks whether the given number is really a number (only chars 0-9).
2482 * @param $num A string consisting only chars between 0 and 9
2483 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2484 * @param $assertMismatch Whether to assert mismatches
2485 * @return $ret The (hopefully) secured numbered value
2487 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2488 // Filter all numbers out
2489 $ret = preg_replace('/[^0123456789]/', '', $num);
2492 if ($castValue === true) {
2493 // Cast to biggest numeric type
2494 $ret = (double) $ret;
2497 // Assert only if requested
2498 if ($assertMismatch === true) {
2499 // Has the whole value changed?
2500 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2508 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2510 * @param $num A string consisting only chars between 0 and 9
2511 * @param $assertMismatch Whether to assert mismatches
2512 * @return $ret The (hopefully) secured hext-numbered value
2514 public function hexval ($num, $assertMismatch = false) {
2515 // Filter all numbers out
2516 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2518 // Assert only if requested
2519 if ($assertMismatch === true) {
2520 // Has the whole value changed?
2521 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2529 * Determines if an element is set in the generic array
2531 * @param $keyGroup Main group for the key
2532 * @param $subGroup Sub group for the key
2533 * @param $key Key to check
2534 * @param $element Element to check
2535 * @return $isset Whether the given key is set
2537 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2539 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2542 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2548 * Determines if a key is set in the generic array
2550 * @param $keyGroup Main group for the key
2551 * @param $subGroup Sub group for the key
2552 * @param $key Key to check
2553 * @return $isset Whether the given key is set
2555 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2557 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2560 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2568 * Determines if a group is set in the generic array
2570 * @param $keyGroup Main group
2571 * @param $subGroup Sub group
2572 * @return $isset Whether the given group is set
2574 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2576 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2579 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2586 * Getter for sub key group
2588 * @param $keyGroup Main key group
2589 * @param $subGroup Sub key group
2590 * @return $array An array with all array elements
2592 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2594 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2595 // No, then abort here
2596 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2601 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2604 return $this->genericArray[$keyGroup][$subGroup];
2608 * Unsets a given key in generic array
2610 * @param $keyGroup Main group for the key
2611 * @param $subGroup Sub group for the key
2612 * @param $key Key to unset
2615 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2617 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2620 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2624 * Unsets a given element in generic array
2626 * @param $keyGroup Main group for the key
2627 * @param $subGroup Sub group for the key
2628 * @param $key Key to unset
2629 * @param $element Element to unset
2632 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2634 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2637 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2641 * Append a string to a given generic array key
2643 * @param $keyGroup Main group for the key
2644 * @param $subGroup Sub group for the key
2645 * @param $key Key to unset
2646 * @param $value Value to add/append
2649 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2651 //* 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);
2653 // Is it already there?
2654 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2656 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2659 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2664 * Append a string to a given generic array element
2666 * @param $keyGroup Main group for the key
2667 * @param $subGroup Sub group for the key
2668 * @param $key Key to unset
2669 * @param $element Element to check
2670 * @param $value Value to add/append
2673 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2675 //* 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);
2677 // Is it already there?
2678 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2680 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2683 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2688 * Sets a string in a given generic array element
2690 * @param $keyGroup Main group for the key
2691 * @param $subGroup Sub group for the key
2692 * @param $key Key to unset
2693 * @param $element Element to check
2694 * @param $value Value to add/append
2697 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2699 //* 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);
2702 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2706 * Initializes given generic array group
2708 * @param $keyGroup Main group for the key
2709 * @param $subGroup Sub group for the key
2710 * @param $key Key to use
2711 * @param $forceInit Optionally force initialization
2714 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2716 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2718 // Is it already set?
2719 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2720 // Already initialized
2721 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2726 $this->genericArray[$keyGroup][$subGroup] = array();
2730 * Initializes given generic array key
2732 * @param $keyGroup Main group for the key
2733 * @param $subGroup Sub group for the key
2734 * @param $key Key to use
2735 * @param $forceInit Optionally force initialization
2738 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2740 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2742 // Is it already set?
2743 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2744 // Already initialized
2745 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2750 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2754 * Initializes given generic array element
2756 * @param $keyGroup Main group for the key
2757 * @param $subGroup Sub group for the key
2758 * @param $key Key to use
2759 * @param $element Element to use
2760 * @param $forceInit Optionally force initialization
2763 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2765 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2767 // Is it already set?
2768 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2769 // Already initialized
2770 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2775 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2779 * Pushes an element to a generic key
2781 * @param $keyGroup Main group for the key
2782 * @param $subGroup Sub group for the key
2783 * @param $key Key to use
2784 * @param $value Value to add/append
2785 * @return $count Number of array elements
2787 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2789 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2792 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2794 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2798 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2801 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2802 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2807 * Pushes an element to a generic array element
2809 * @param $keyGroup Main group for the key
2810 * @param $subGroup Sub group for the key
2811 * @param $key Key to use
2812 * @param $element Element to check
2813 * @param $value Value to add/append
2814 * @return $count Number of array elements
2816 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2818 //* 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));
2821 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2823 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2827 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2830 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2831 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2836 * Pops an element from a generic group
2838 * @param $keyGroup Main group for the key
2839 * @param $subGroup Sub group for the key
2840 * @param $key Key to unset
2841 * @return $value Last "popped" value
2843 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2845 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2848 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2850 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2855 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2858 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2859 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2864 * Shifts an element from a generic group
2866 * @param $keyGroup Main group for the key
2867 * @param $subGroup Sub group for the key
2868 * @param $key Key to unset
2869 * @return $value Last "popped" value
2871 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2873 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2876 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2878 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2883 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2886 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2887 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2892 * Count generic array group
2894 * @param $keyGroup Main group for the key
2895 * @return $count Count of given group
2897 protected final function countGenericArray ($keyGroup) {
2899 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2902 if (!isset($this->genericArray[$keyGroup])) {
2904 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2909 $count = count($this->genericArray[$keyGroup]);
2912 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2919 * Count generic array sub group
2921 * @param $keyGroup Main group for the key
2922 * @param $subGroup Sub group for the key
2923 * @return $count Count of given group
2925 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2927 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2930 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2932 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2937 $count = count($this->genericArray[$keyGroup][$subGroup]);
2940 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2947 * Count generic array elements
2949 * @param $keyGroup Main group for the key
2950 * @param $subGroup Sub group for the key
2951 * @para $key Key to count
2952 * @return $count Count of given key
2954 protected final function countGenericArrayElements ($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 . ' not found.');
2963 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2965 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2970 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2973 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2980 * Getter for whole generic group array
2982 * @param $keyGroup Key group to get
2983 * @return $array Whole generic array group
2985 protected final function getGenericArray ($keyGroup) {
2987 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2990 if (!isset($this->genericArray[$keyGroup])) {
2992 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2997 return $this->genericArray[$keyGroup];
3001 * Setter for generic array key
3003 * @param $keyGroup Key group to get
3004 * @param $subGroup Sub group for the key
3005 * @param $key Key to unset
3006 * @param $value Mixed value from generic array element
3009 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3011 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3014 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3018 * Getter for generic array key
3020 * @param $keyGroup Key group to get
3021 * @param $subGroup Sub group for the key
3022 * @param $key Key to unset
3023 * @return $value Mixed value from generic array element
3025 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3027 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3030 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3032 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3037 return $this->genericArray[$keyGroup][$subGroup][$key];
3041 * Sets a value in given generic array key/element
3043 * @param $keyGroup Main group for the key
3044 * @param $subGroup Sub group for the key
3045 * @param $key Key to set
3046 * @param $element Element to set
3047 * @param $value Value to set
3050 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3052 //* 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));
3055 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3059 * Getter for generic array element
3061 * @param $keyGroup Key group to get
3062 * @param $subGroup Sub group for the key
3063 * @param $key Key to look for
3064 * @param $element Element to look for
3065 * @return $value Mixed value from generic array element
3067 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3069 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3072 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3074 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3079 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3083 * Checks if a given sub group is valid (array)
3085 * @param $keyGroup Key group to get
3086 * @param $subGroup Sub group for the key
3087 * @return $isValid Whether given sub group is valid
3089 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3091 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3094 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3101 * Checks if a given key is valid (array)
3103 * @param $keyGroup Key group to get
3104 * @param $subGroup Sub group for the key
3105 * @param $key Key to check
3106 * @return $isValid Whether given sub group is valid
3108 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3110 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3113 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3120 * Initializes the web output instance
3124 protected function initWebOutputInstance () {
3125 // Get application instance
3126 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
3128 // Init web output instance
3129 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3132 $this->setWebOutputInstance($outputInstance);
3136 * Translates boolean true to 'Y' and false to 'N'
3138 * @param $boolean Boolean value
3139 * @return $translated Translated boolean value
3141 public static final function translateBooleanToYesNo ($boolean) {
3142 // Make sure it is really boolean
3143 assert(is_bool($boolean));
3146 $translated = ($boolean === true) ? 'Y' : 'N';
3148 // ... and return it
3153 * Encodes raw data (almost any type) by "serializing" it and then pack it
3154 * into a "binary format".
3156 * @param $rawData Raw data (almost any type)
3157 * @return $encoded Encoded data
3159 protected function encodeData ($rawData) {
3160 // Make sure no objects or resources pass through
3161 assert(!is_object($rawData));
3162 assert(!is_resource($rawData));
3164 // First "serialize" it (json_encode() is faster than serialize())
3165 $encoded = $this->packString(json_encode($rawData));
3172 * Pack a string into a "binary format". Please execuse me that this is
3173 * widely undocumented. :-(
3175 * @param $str Unpacked string
3176 * @return $packed Packed string
3177 * @todo Improve documentation
3179 protected function packString ($str) {
3181 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3183 // First compress the string (gzcompress is okay)
3184 $str = gzcompress($str);
3189 // And start the "encoding" loop
3190 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3192 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3193 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3195 if (($idx + $i) <= strlen($str)) {
3196 $ord = ord(substr($str, ($idx + $i), 1));
3198 $add = $ord * pow(256, $factor);
3202 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3206 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3207 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3209 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3210 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3216 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3221 * Creates a full-qualified file name (FQFN) for given file name by adding
3222 * a configured temporary file path to it.
3224 * @param $infoInstance An instance of a SplFileInfo class
3225 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
3226 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3227 * @throws FileIoException If the file cannot be written
3229 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
3231 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
3233 // Is the path writeable?
3234 if (!is_writable($basePath)) {
3235 // Path is write-protected
3236 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3240 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
3243 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
3245 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
3249 return $tempInstance;
3253 * "Getter" for a printable state name
3255 * @return $stateName Name of the node's state in a printable format
3257 public final function getPrintableState () {
3258 // Default is 'null'
3259 $stateName = 'null';
3261 // Get the state instance
3262 $stateInstance = $this->getStateInstance();
3264 // Is it an instance of Stateable?
3265 if ($stateInstance instanceof Stateable) {
3266 // Then use that state name
3267 $stateName = $stateInstance->getStateName();