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\Template\CompileableTemplate;
50 use Org\Mxchange\CoreFramework\User\ManageableAccount;
51 use Org\Mxchange\CoreFramework\Visitor\Visitor;
55 use \InvalidArgumentException;
61 * The simulator system class is the super class of all other classes. This
62 * class handles saving of games etc.
64 * @author Roland Haeder <webmaster@shipsimu.org>
66 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
67 * @license GNU GPL 3.0 or any newer version
68 * @link http://www.shipsimu.org
70 * This program is free software: you can redistribute it and/or modify
71 * it under the terms of the GNU General Public License as published by
72 * the Free Software Foundation, either version 3 of the License, or
73 * (at your option) any later version.
75 * This program is distributed in the hope that it will be useful,
76 * but WITHOUT ANY WARRANTY; without even the implied warranty of
77 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
78 * GNU General Public License for more details.
80 * You should have received a copy of the GNU General Public License
81 * along with this program. If not, see <http://www.gnu.org/licenses/>.
83 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
85 * Length of output from hash()
87 private static $hashLength = NULL;
92 private $realClass = 'BaseFrameworkSystem';
95 * Search criteria instance
97 private $searchInstance = NULL;
100 * Update criteria instance
102 private $updateInstance = NULL;
105 * The file I/O instance for the template loader
107 private $fileIoInstance = NULL;
112 private $resolverInstance = NULL;
115 * Template engine instance
117 private $templateInstance = NULL;
120 * Database result instance
122 private $resultInstance = NULL;
125 * Instance for user class
127 private $userInstance = NULL;
130 * A controller instance
132 private $controllerInstance = NULL;
137 private $rngInstance = NULL;
140 * Instance of a crypto helper
142 private $cryptoInstance = NULL;
145 * Instance of an Iterator class
147 private $iteratorInstance = NULL;
150 * Instance of the list
152 private $listInstance = NULL;
157 private $menuInstance = NULL;
160 * Instance of the image
162 private $imageInstance = NULL;
165 * Instance of the stacker
167 private $stackInstance = NULL;
170 * A Compressor instance
172 private $compressorInstance = NULL;
175 * A Parseable instance
177 private $parserInstance = NULL;
180 * A database wrapper instance
182 private $databaseInstance = NULL;
185 * A helper instance for the form
187 private $helperInstance = NULL;
190 * An instance of a InputStream class
192 private $inputStreamInstance = NULL;
195 * An instance of a OutputStream class
197 private $outputStreamInstance = NULL;
202 private $handlerInstance = NULL;
205 * Visitor handler instance
207 private $visitorInstance = NULL;
210 * An instance of a database wrapper class
212 private $wrapperInstance = NULL;
215 * An instance of a file I/O pointer class (not handler)
217 private $pointerInstance = NULL;
220 * An instance of an Indexable class
222 private $indexInstance = NULL;
225 * An instance of a Block class
227 private $blockInstance = NULL;
232 private $minableInstance = NULL;
235 * A FrameworkDirectory instance
237 private $directoryInstance = NULL;
240 * The concrete output instance
242 private $outputInstance = NULL;
247 private $stateInstance = NULL;
250 * Registry instance (implementing Register)
252 private $registryInstance = NULL;
257 private $callbackInstance = NULL;
260 * Thousands separator
262 private $thousands = '.'; // German
267 private $decimals = ','; // German
272 private $socketResource = false;
275 * Regular expression to use for validation
277 private $regularExpression = '';
282 private $packageData = array();
287 private $genericArray = array();
292 private $commandName = '';
297 private $controllerName = '';
300 * Array with bitmasks and such for pack/unpack methods to support both
301 * 32-bit and 64-bit systems
303 private $packingData = array(
306 'left' => 0xffff0000,
307 'right' => 0x0000ffff,
313 'left' => 0xffffffff00000000,
314 'right' => 0x00000000ffffffff,
321 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
323 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
325 private $archArrayElement = false;
327 /***********************
328 * Exception codes.... *
329 ***********************/
331 // @todo Try to clean these constants up
332 const EXCEPTION_IS_NULL_POINTER = 0x001;
333 const EXCEPTION_IS_NO_OBJECT = 0x002;
334 const EXCEPTION_IS_NO_ARRAY = 0x003;
335 const EXCEPTION_MISSING_METHOD = 0x004;
336 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
337 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
338 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
339 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
340 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
341 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
342 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
343 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
344 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
345 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
346 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
347 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
348 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
349 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
350 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
351 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
352 const EXCEPTION_PATH_NOT_FOUND = 0x015;
353 const EXCEPTION_INVALID_PATH_NAME = 0x016;
354 const EXCEPTION_READ_PROTECED_PATH = 0x017;
355 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
356 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
357 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
358 const EXCEPTION_INVALID_RESOURCE = 0x01b;
359 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
360 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
361 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
362 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
363 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
364 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
365 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
366 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
367 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
368 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
369 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
370 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
371 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
372 const EXCEPTION_INVALID_STRING = 0x029;
373 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
374 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
375 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
376 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
377 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
378 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
379 const EXCEPTION_MISSING_ELEMENT = 0x030;
380 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
381 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
382 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
383 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
384 const EXCEPTION_FATAL_ERROR = 0x035;
385 const EXCEPTION_FILE_NOT_FOUND = 0x036;
386 const EXCEPTION_ASSERTION_FAILED = 0x037;
387 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
388 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
389 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
390 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
391 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
392 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
393 const EXCEPTION_INVALID_SOCKET = 0x03e;
396 * Hexadecimal->Decimal translation array
398 private static $hexdec = array(
418 * Decimal->hexadecimal translation array
420 private static $dechex = array(
440 * Startup time in miliseconds
442 private static $startupTime = 0;
445 * Protected super constructor
447 * @param $className Name of the class
450 protected function __construct ($className) {
452 $this->setRealClass($className);
454 // Set configuration instance if no registry ...
455 if (!$this instanceof Register) {
456 // ... because registries doesn't need to be configured
457 $this->setConfigInstance(FrameworkBootstrap::getConfigurationInstance());
460 // Is the startup time set? (0 cannot be true anymore)
461 if (self::$startupTime == 0) {
463 self::$startupTime = microtime(true);
467 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
471 * Destructor for all classes. You should not call this method on your own.
475 public function __destruct () {
476 // Flush any updated entries to the database
477 $this->flushPendingUpdates();
479 // Is this object already destroyed?
480 if ($this->__toString() != 'DestructedObject') {
481 // Destroy all informations about this class but keep some text about it alive
482 $this->setRealClass('DestructedObject');
483 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
484 // Already destructed object
485 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
489 // Do not call this twice
490 trigger_error(__METHOD__ . ': Called twice.');
496 * The __call() method where all non-implemented methods end up
498 * @param $methodName Name of the missing method
499 * @args $args Arguments passed to the method
502 public final function __call ($methodName, $args) {
503 return self::__callStatic($methodName, $args);
507 * The __callStatic() method where all non-implemented static methods end up
509 * @param $methodName Name of the missing method
510 * @args $args Arguments passed to the method
513 public static final function __callStatic ($methodName, $args) {
515 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
517 // Init argument string
520 // Is it NULL, empty or an array?
521 if (is_null($args)) {
523 $argsString = 'NULL';
524 } elseif (is_array($args)) {
528 // Some arguments are there
529 foreach ($args as $arg) {
530 // Add data about the argument
531 $argsString .= gettype($arg) . ':';
534 // Found a NULL argument
535 $argsString .= 'NULL';
536 } elseif (is_string($arg)) {
537 // Add length for strings
538 $argsString .= strlen($arg);
539 } elseif ((is_int($arg)) || (is_float($arg))) {
542 } elseif (is_array($arg)) {
543 // .. or size if array
544 $argsString .= count($arg);
545 } elseif (is_object($arg)) {
547 $reflection = new ReflectionClass($arg);
549 // Is an other object, maybe no __toString() available
550 $argsString .= $reflection->getName();
551 } elseif ($arg === true) {
552 // ... is boolean 'true'
553 $argsString .= 'true';
554 } elseif ($arg === false) {
555 // ... is boolean 'false'
556 $argsString .= 'false';
559 // Comma for next one
564 if (substr($argsString, -2, 1) == ',') {
565 $argsString = substr($argsString, 0, -2);
571 // Invalid arguments!
572 $argsString = '!INVALID:' . gettype($args) . '!';
575 // Output stub message
576 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
577 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
587 * Getter for $realClass
589 * @return $realClass The name of the real class (not BaseFrameworkSystem)
591 public function __toString () {
592 return $this->realClass;
596 * Magic method to catch setting of missing but set class fields/attributes
598 * @param $name Name of the field/attribute
599 * @param $value Value to store
602 public final function __set ($name, $value) {
603 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
606 print_r($value, true)
611 * Magic method to catch getting of missing fields/attributes
613 * @param $name Name of the field/attribute
616 public final function __get ($name) {
617 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
623 * Magic method to catch unsetting of missing fields/attributes
625 * @param $name Name of the field/attribute
628 public final function __unset ($name) {
629 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
635 * Magic method to catch object serialization
637 * @return $unsupported Unsupported method
638 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
640 public final function __sleep () {
641 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
645 * Magic method to catch object deserialization
647 * @return $unsupported Unsupported method
648 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
650 public final function __wakeup () {
651 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
655 * Magic method to catch calls when an object instance is called
657 * @return $unsupported Unsupported method
658 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
660 public final function __invoke () {
661 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
665 * Setter for the real class name
667 * @param $realClass Class name (string)
670 public final function setRealClass ($realClass) {
672 $this->realClass = (string) $realClass;
676 * Setter for database result instance
678 * @param $resultInstance An instance of a database result class
680 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
682 protected final function setResultInstance (SearchableResult $resultInstance) {
683 $this->resultInstance = $resultInstance;
687 * Getter for database result instance
689 * @return $resultInstance An instance of a database result class
691 public final function getResultInstance () {
692 return $this->resultInstance;
696 * Setter for template engine instances
698 * @param $templateInstance An instance of a template engine class
701 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
702 $this->templateInstance = $templateInstance;
706 * Getter for template engine instances
708 * @return $templateInstance An instance of a template engine class
710 protected final function getTemplateInstance () {
711 return $this->templateInstance;
715 * Setter for search instance
717 * @param $searchInstance Searchable criteria instance
720 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
721 $this->searchInstance = $searchInstance;
725 * Getter for search instance
727 * @return $searchInstance Searchable criteria instance
729 public final function getSearchInstance () {
730 return $this->searchInstance;
734 * Setter for update instance
736 * @param $updateInstance An instance of a LocalUpdateCriteria clase
739 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
740 $this->updateInstance = $updateInstance;
744 * Getter for update instance
746 * @return $updateInstance Updateable criteria instance
748 public final function getUpdateInstance () {
749 return $this->updateInstance;
753 * Setter for resolver instance
755 * @param $resolverInstance Instance of a command resolver class
758 public final function setResolverInstance (Resolver $resolverInstance) {
759 $this->resolverInstance = $resolverInstance;
763 * Getter for resolver instance
765 * @return $resolverInstance Instance of a command resolver class
767 public final function getResolverInstance () {
768 return $this->resolverInstance;
772 * Setter for language instance
774 * @param $configInstance The configuration instance which shall
775 * be FrameworkConfiguration
778 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
779 GenericRegistry::getRegistry()->addInstance('config', $configInstance);
783 * Getter for configuration instance
785 * @return $configInstance Configuration instance
787 public final function getConfigInstance () {
788 $configInstance = GenericRegistry::getRegistry()->getInstance('config');
789 return $configInstance;
793 * Setter for debug instance
795 * @param $debugInstance The instance for debug output class
798 public final function setDebugInstance (DebugMiddleware $debugInstance) {
799 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
803 * Getter for debug instance
805 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
807 public final function getDebugInstance () {
808 // Get debug instance
809 $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
812 return $debugInstance;
816 * Setter for web output instance
818 * @param $webInstance The instance for web output class
821 public final function setWebOutputInstance (OutputStreamer $webInstance) {
822 GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
826 * Getter for web output instance
828 * @return $webOutputInstance - Instance to class WebOutput
830 public final function getWebOutputInstance () {
831 $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
832 return $webOutputInstance;
836 * Setter for database instance
838 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
841 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
842 GenericRegistry::getRegistry()->addInstance('db_instance', $databaseInstance);
846 * Getter for database layer
848 * @return $databaseInstance The database layer instance
850 public final function getDatabaseInstance () {
852 $databaseInstance = GenericRegistry::getRegistry()->getInstance('db_instance');
855 return $databaseInstance;
859 * Setter for compressor channel
861 * @param $compressorInstance An instance of CompressorChannel
864 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
865 GenericRegistry::getRegistry()->addInstance('compressor', $compressorInstance);
869 * Getter for compressor channel
871 * @return $compressorInstance The compressor channel
873 public final function getCompressorChannel () {
874 $compressorInstance = GenericRegistry::getRegistry()->getInstance('compressor');
875 return $compressorInstance;
879 * Protected getter for a manageable application helper class
881 * @return $applicationInstance An instance of a manageable application helper class
883 protected final function getApplicationInstance () {
884 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
885 return $applicationInstance;
889 * Setter for a manageable application helper class
891 * @param $applicationInstance An instance of a manageable application helper class
894 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
895 GenericRegistry::getRegistry()->addInstance('application', $applicationInstance);
899 * Private getter for language instance
901 * @return $langInstance An instance to the language sub-system
903 protected final function getLanguageInstance () {
904 $langInstance = GenericRegistry::getRegistry()->getInstance('language');
905 return $langInstance;
909 * Setter for language instance
911 * @param $langInstance An instance to the language sub-system
913 * @see LanguageSystem
915 public final function setLanguageInstance (ManageableLanguage $langInstance) {
916 GenericRegistry::getRegistry()->addInstance('language', $langInstance);
920 * Private getter for file IO instance
922 * @return $fileIoInstance An instance to the file I/O sub-system
924 protected final function getFileIoInstance () {
925 return $this->fileIoInstance;
929 * Setter for file I/O instance
931 * @param $fileIoInstance An instance to the file I/O sub-system
934 public final function setFileIoInstance (IoHandler $fileIoInstance) {
935 $this->fileIoInstance = $fileIoInstance;
939 * Protected setter for user instance
941 * @param $userInstance An instance of a user class
944 protected final function setUserInstance (ManageableAccount $userInstance) {
945 $this->userInstance = $userInstance;
949 * Getter for user instance
951 * @return $userInstance An instance of a user class
953 public final function getUserInstance () {
954 return $this->userInstance;
958 * Setter for controller instance (this surely breaks a bit the MVC patterm)
960 * @param $controllerInstance An instance of the controller
963 public final function setControllerInstance (Controller $controllerInstance) {
964 $this->controllerInstance = $controllerInstance;
968 * Getter for controller instance (this surely breaks a bit the MVC patterm)
970 * @return $controllerInstance An instance of the controller
972 public final function getControllerInstance () {
973 return $this->controllerInstance;
977 * Setter for RNG instance
979 * @param $rngInstance An instance of a random number generator (RNG)
982 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
983 $this->rngInstance = $rngInstance;
987 * Getter for RNG instance
989 * @return $rngInstance An instance of a random number generator (RNG)
991 public final function getRngInstance () {
992 return $this->rngInstance;
996 * Setter for Cryptable instance
998 * @param $cryptoInstance An instance of a Cryptable class
1001 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1002 $this->cryptoInstance = $cryptoInstance;
1006 * Getter for Cryptable instance
1008 * @return $cryptoInstance An instance of a Cryptable class
1010 public final function getCryptoInstance () {
1011 return $this->cryptoInstance;
1015 * Setter for the list instance
1017 * @param $listInstance A list of Listable
1020 protected final function setListInstance (Listable $listInstance) {
1021 $this->listInstance = $listInstance;
1025 * Getter for the list instance
1027 * @return $listInstance A list of Listable
1029 protected final function getListInstance () {
1030 return $this->listInstance;
1034 * Setter for the menu instance
1036 * @param $menuInstance A RenderableMenu instance
1039 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1040 $this->menuInstance = $menuInstance;
1044 * Getter for the menu instance
1046 * @return $menuInstance A RenderableMenu instance
1048 protected final function getMenuInstance () {
1049 return $this->menuInstance;
1053 * Setter for image instance
1055 * @param $imageInstance An instance of an image
1058 public final function setImageInstance (BaseImage $imageInstance) {
1059 $this->imageInstance = $imageInstance;
1063 * Getter for image instance
1065 * @return $imageInstance An instance of an image
1067 public final function getImageInstance () {
1068 return $this->imageInstance;
1072 * Setter for stacker instance
1074 * @param $stackInstance An instance of an stacker
1077 public final function setStackInstance (Stackable $stackInstance) {
1078 $this->stackInstance = $stackInstance;
1082 * Getter for stacker instance
1084 * @return $stackInstance An instance of an stacker
1086 public final function getStackInstance () {
1087 return $this->stackInstance;
1091 * Setter for compressor instance
1093 * @param $compressorInstance An instance of an compressor
1096 public final function setCompressorInstance (Compressor $compressorInstance) {
1097 $this->compressorInstance = $compressorInstance;
1101 * Getter for compressor instance
1103 * @return $compressorInstance An instance of an compressor
1105 public final function getCompressorInstance () {
1106 return $this->compressorInstance;
1110 * Setter for Parseable instance
1112 * @param $parserInstance An instance of an Parseable
1115 public final function setParserInstance (Parseable $parserInstance) {
1116 $this->parserInstance = $parserInstance;
1120 * Getter for Parseable instance
1122 * @return $parserInstance An instance of an Parseable
1124 public final function getParserInstance () {
1125 return $this->parserInstance;
1129 * Setter for DatabaseWrapper instance
1131 * @param $wrapperInstance An instance of an DatabaseWrapper
1134 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1135 $this->wrapperInstance = $wrapperInstance;
1139 * Getter for DatabaseWrapper instance
1141 * @return $wrapperInstance An instance of an DatabaseWrapper
1143 public final function getWrapperInstance () {
1144 return $this->wrapperInstance;
1148 * Setter for socket resource
1150 * @param $socketResource A valid socket resource
1153 public final function setSocketResource ($socketResource) {
1154 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1155 $this->socketResource = $socketResource;
1159 * Getter for socket resource
1161 * @return $socketResource A valid socket resource
1163 public final function getSocketResource () {
1164 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1165 return $this->socketResource;
1169 * Setter for regular expression
1171 * @param $regularExpression A valid regular expression
1174 public final function setRegularExpression ($regularExpression) {
1175 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1176 $this->regularExpression = $regularExpression;
1180 * Getter for regular expression
1182 * @return $regularExpression A valid regular expression
1184 public final function getRegularExpression () {
1185 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1186 return $this->regularExpression;
1190 * Setter for helper instance
1192 * @param $helperInstance An instance of a helper class
1195 protected final function setHelperInstance (Helper $helperInstance) {
1196 $this->helperInstance = $helperInstance;
1200 * Getter for helper instance
1202 * @return $helperInstance An instance of a helper class
1204 public final function getHelperInstance () {
1205 return $this->helperInstance;
1209 * Getter for a InputStream instance
1211 * @param $inputStreamInstance The InputStream instance
1213 protected final function getInputStreamInstance () {
1214 return $this->inputStreamInstance;
1218 * Setter for a InputStream instance
1220 * @param $inputStreamInstance The InputStream instance
1223 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1224 $this->inputStreamInstance = $inputStreamInstance;
1228 * Getter for a OutputStream instance
1230 * @param $outputStreamInstance The OutputStream instance
1232 protected final function getOutputStreamInstance () {
1233 return $this->outputStreamInstance;
1237 * Setter for a OutputStream instance
1239 * @param $outputStreamInstance The OutputStream instance
1242 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1243 $this->outputStreamInstance = $outputStreamInstance;
1247 * Setter for handler instance
1249 * @param $handlerInstance An instance of a Handleable class
1252 protected final function setHandlerInstance (Handleable $handlerInstance) {
1253 $this->handlerInstance = $handlerInstance;
1257 * Getter for handler instance
1259 * @return $handlerInstance A Handleable instance
1261 protected final function getHandlerInstance () {
1262 return $this->handlerInstance;
1266 * Setter for visitor instance
1268 * @param $visitorInstance A Visitor instance
1271 protected final function setVisitorInstance (Visitor $visitorInstance) {
1272 $this->visitorInstance = $visitorInstance;
1276 * Getter for visitor instance
1278 * @return $visitorInstance A Visitor instance
1280 protected final function getVisitorInstance () {
1281 return $this->visitorInstance;
1285 * Setter for raw package Data
1287 * @param $packageData Raw package Data
1290 public final function setPackageData (array $packageData) {
1291 $this->packageData = $packageData;
1295 * Getter for raw package Data
1297 * @return $packageData Raw package Data
1299 public function getPackageData () {
1300 return $this->packageData;
1305 * Setter for Iterator instance
1307 * @param $iteratorInstance An instance of an Iterator
1310 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1311 $this->iteratorInstance = $iteratorInstance;
1315 * Getter for Iterator instance
1317 * @return $iteratorInstance An instance of an Iterator
1319 public final function getIteratorInstance () {
1320 return $this->iteratorInstance;
1324 * Setter for FilePointer instance
1326 * @param $pointerInstance An instance of an FilePointer class
1329 protected final function setPointerInstance (FilePointer $pointerInstance) {
1330 $this->pointerInstance = $pointerInstance;
1334 * Getter for FilePointer instance
1336 * @return $pointerInstance An instance of an FilePointer class
1338 public final function getPointerInstance () {
1339 return $this->pointerInstance;
1343 * Unsets pointer instance which triggers a call of __destruct() if the
1344 * instance is still there. This is surely not fatal on already "closed"
1345 * file pointer instances.
1347 * I don't want to mess around with above setter by giving it a default
1348 * value NULL as setter should always explicitly only set (existing) object
1349 * instances and NULL is NULL.
1353 protected final function unsetPointerInstance () {
1354 // Simply it to NULL
1355 $this->pointerInstance = NULL;
1359 * Setter for Indexable instance
1361 * @param $indexInstance An instance of an Indexable class
1364 protected final function setIndexInstance (Indexable $indexInstance) {
1365 $this->indexInstance = $indexInstance;
1369 * Getter for Indexable instance
1371 * @return $indexInstance An instance of an Indexable class
1373 public final function getIndexInstance () {
1374 return $this->indexInstance;
1378 * Setter for Block instance
1380 * @param $blockInstance An instance of an Block class
1383 protected final function setBlockInstance (Block $blockInstance) {
1384 $this->blockInstance = $blockInstance;
1388 * Getter for Block instance
1390 * @return $blockInstance An instance of an Block class
1392 public final function getBlockInstance () {
1393 return $this->blockInstance;
1397 * Setter for Minable instance
1399 * @param $minableInstance A Minable instance
1402 protected final function setMinableInstance (Minable $minableInstance) {
1403 $this->minableInstance = $minableInstance;
1407 * Getter for minable instance
1409 * @return $minableInstance A Minable instance
1411 protected final function getMinableInstance () {
1412 return $this->minableInstance;
1416 * Setter for FrameworkDirectory instance
1418 * @param $directoryInstance A FrameworkDirectory instance
1421 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1422 $this->directoryInstance = $directoryInstance;
1426 * Getter for FrameworkDirectory instance
1428 * @return $directoryInstance A FrameworkDirectory instance
1430 protected final function getDirectoryInstance () {
1431 return $this->directoryInstance;
1435 * Setter for state instance
1437 * @param $stateInstance A Stateable instance
1440 public final function setStateInstance (Stateable $stateInstance) {
1441 $this->stateInstance = $stateInstance;
1445 * Getter for state instance
1447 * @return $stateInstance A Stateable instance
1449 public final function getStateInstance () {
1450 return $this->stateInstance;
1454 * Setter for output instance
1456 * @param $outputInstance The debug output instance
1459 public final function setOutputInstance (OutputStreamer $outputInstance) {
1460 $this->outputInstance = $outputInstance;
1464 * Getter for output instance
1466 * @return $outputInstance The debug output instance
1468 public final function getOutputInstance () {
1469 return $this->outputInstance;
1473 * Setter for registry instance
1475 * @param $registryInstance An instance of a Register class
1478 protected final function setRegistryInstance (Register $registryInstance) {
1479 $this->registryInstance = $registryInstance;
1483 * Getter for registry instance
1485 * @return $registryInstance The debug registry instance
1487 public final function getRegistryInstance () {
1488 return $this->registryInstance;
1492 * Setter for call-back instance
1494 * @param $callbackInstance An instance of a FrameworkInterface class
1497 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1498 $this->callbackInstance = $callbackInstance;
1502 * Getter for call-back instance
1504 * @return $callbackInstance An instance of a FrameworkInterface class
1506 protected final function getCallbackInstance () {
1507 return $this->callbackInstance;
1511 * Setter for command name
1513 * @param $commandName Last validated command name
1516 protected final function setCommandName ($commandName) {
1517 $this->commandName = $commandName;
1521 * Getter for command name
1523 * @return $commandName Last validated command name
1525 protected final function getCommandName () {
1526 return $this->commandName;
1530 * Setter for controller name
1532 * @param $controllerName Last validated controller name
1535 protected final function setControllerName ($controllerName) {
1536 $this->controllerName = $controllerName;
1540 * Getter for controller name
1542 * @return $controllerName Last validated controller name
1544 protected final function getControllerName () {
1545 return $this->controllerName;
1549 * Checks whether an object equals this object. You should overwrite this
1550 * method to implement own equality checks
1552 * @param $objectInstance An instance of a FrameworkInterface object
1553 * @return $equals Whether both objects equals
1555 public function equals (FrameworkInterface $objectInstance) {
1558 $this->__toString() == $objectInstance->__toString()
1560 $this->hashCode() == $objectInstance->hashCode()
1563 // Return the result
1568 * Generates a generic hash code of this class. You should really overwrite
1569 * this method with your own hash code generator code. But keep KISS in mind.
1571 * @return $hashCode A generic hash code respresenting this whole class
1573 public function hashCode () {
1575 return crc32($this->__toString());
1579 * Formats computer generated price values into human-understandable formats
1580 * with thousand and decimal separators.
1582 * @param $value The in computer format value for a price
1583 * @param $currency The currency symbol (use HTML-valid characters!)
1584 * @param $decNum Number of decimals after commata
1585 * @return $price The for the current language formated price string
1586 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1587 * thousands separator
1590 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1591 // Are all required attriutes set?
1592 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1593 // Throw an exception
1594 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1598 $value = (float) $value;
1600 // Reformat the US number
1601 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1603 // Return as string...
1608 * Appends a trailing slash to a string
1610 * @param $str A string (maybe) without trailing slash
1611 * @return $str A string with an auto-appended trailing slash
1613 public final function addMissingTrailingSlash ($str) {
1614 // Is there a trailing slash?
1615 if (substr($str, -1, 1) != '/') {
1619 // Return string with trailing slash
1624 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1625 * application helper instance (ApplicationHelper by default).
1627 * @param $applicationInstance An application helper instance or
1628 * null if we shall use the default
1629 * @return $templateInstance The template engine instance
1630 * @throws NullPointerException If the discovered application
1631 * instance is still null
1633 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1634 // Is the application instance set?
1635 if (is_null($applicationInstance)) {
1636 // Get the current instance
1637 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1640 if (is_null($applicationInstance)) {
1641 // Thrown an exception
1642 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1646 // Initialize the template engine
1647 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1649 // Return the prepared instance
1650 return $templateInstance;
1654 * Debugs this instance by putting out it's full content
1656 * @param $message Optional message to show in debug output
1659 public final function debugInstance ($message = '') {
1660 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1661 restore_error_handler();
1666 // Is a message set?
1667 if (!empty($message)) {
1668 // Construct message
1669 $content = sprintf('<div class="debug_message">
1671 </div>' . PHP_EOL, $message);
1674 // Generate the output
1675 $content .= sprintf('<pre>%s</pre>',
1678 print_r($this, true)
1684 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1687 <div class="debug_content">
1691 <div class="debug_include_list">
1694 $this->__toString(),
1696 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1701 * Replaces control characters with printable output
1703 * @param $str String with control characters
1704 * @return $str Replaced string
1706 protected function replaceControlCharacters ($str) {
1709 chr(13), '[r]', str_replace(
1710 chr(10), '[n]', str_replace(
1720 * Output a partial stub message for the caller method
1722 * @param $message An optional message to display
1725 protected function partialStub ($message = '') {
1727 $stubMessage = 'Partial Stub!';
1729 // Is the extra message given?
1730 if (!empty($message)) {
1731 // Then add it as well
1732 $stubMessage .= ' Message: ' . $message;
1735 // Debug instance is there?
1736 if (!is_null($this->getDebugInstance())) {
1737 // Output stub message
1738 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1741 trigger_error($stubMessage);
1747 * Outputs a debug backtrace and stops further script execution
1749 * @param $message An optional message to output
1750 * @param $doExit Whether exit the program (true is default)
1753 public function debugBackTrace ($message = '', $doExit = true) {
1754 // Sorry, there is no other way getting this nice backtrace
1755 if (!empty($message)) {
1757 printf('Message: %s<br />' . PHP_EOL, $message);
1761 debug_print_backtrace();
1765 if ($doExit === true) {
1771 * Creates an instance of a debugger instance
1773 * @param $className Name of the class (currently unsupported)
1774 * @param $lineNumber Line number where the call was made
1775 * @return $debugInstance An instance of a debugger class
1776 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1778 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1779 // Is the instance set?
1780 if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
1781 // Init debug instance
1782 $debugInstance = NULL;
1786 // Get a debugger instance
1787 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1788 } catch (NullPointerException $e) {
1789 // Didn't work, no instance there
1790 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1793 // Empty string should be ignored and used for testing the middleware
1794 DebugMiddleware::getSelfInstance()->output('');
1796 // Set it in registry
1797 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
1799 // Get instance from registry
1800 $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
1804 return $debugInstance;
1808 * Simple output of a message with line-break
1810 * @param $message Message to output
1813 public function outputLine ($message) {
1815 print($message . PHP_EOL);
1819 * Outputs a debug message whether to debug instance (should be set!) or
1820 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1821 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1823 * @param $message Message we shall send out...
1824 * @param $doPrint Whether print or die here (default: print)
1825 * @paran $stripTags Whether to strip tags (default: false)
1828 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1829 // Set debug instance to NULL
1830 $debugInstance = NULL;
1833 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1835 // Is function partialStub/__callStatic ?
1836 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1837 // Prepend class::function:line from 3rd element
1838 $message = sprintf('[%s::%s:%d]: %s',
1839 $backtrace[2]['class'],
1840 $backtrace[2]['function'],
1841 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1845 // Prepend class::function:line from 2nd element
1846 $message = sprintf('[%s::%s:%d]: %s',
1847 $backtrace[1]['class'],
1848 $backtrace[1]['function'],
1849 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1856 // Get debug instance
1857 $debugInstance = $this->getDebugInstance();
1858 } catch (NullPointerException $e) {
1859 // The debug instance is not set (yet)
1862 // Is the debug instance there?
1863 if (is_object($debugInstance)) {
1864 // Use debug output handler
1865 $debugInstance->output($message, $stripTags);
1867 if ($doPrint === false) {
1868 // Die here if not printed
1872 // Are debug times enabled?
1873 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1875 $message = $this->getPrintableExecutionTime() . $message;
1879 if ($doPrint === true) {
1881 $this->outputLine($message);
1890 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1892 * @param $str The string, what ever it is needs to be converted
1893 * @return $className Generated class name
1895 public static final function convertToClassName ($str) {
1899 // Convert all dashes in underscores
1900 $str = self::convertDashesToUnderscores($str);
1902 // Now use that underscores to get classname parts for hungarian style
1903 foreach (explode('_', $str) as $strPart) {
1904 // Make the class name part lower case and first upper case
1905 $className .= ucfirst(strtolower($strPart));
1908 // Return class name
1913 * Converts dashes to underscores, e.g. useable for configuration entries
1915 * @param $str The string with maybe dashes inside
1916 * @return $str The converted string with no dashed, but underscores
1917 * @throws NullPointerException If $str is null
1918 * @throws InvalidArgumentException If $str is empty
1920 public static function convertDashesToUnderscores ($str) {
1922 if (is_null($str)) {
1924 throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
1925 } elseif (!is_string($str)) {
1927 throw new InvalidArgumentException(sprintf('str[]=%s is not a string', gettype($str)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
1928 } elseif ((is_string($str)) && (empty($str))) {
1930 throw new InvalidArgumentException('str is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
1934 $str = str_replace('-', '_', $str);
1936 // Return converted string
1941 * Marks up the code by adding e.g. line numbers
1943 * @param $phpCode Unmarked PHP code
1944 * @return $markedCode Marked PHP code
1946 public function markupCode ($phpCode) {
1951 $errorArray = error_get_last();
1953 // Init the code with error message
1954 if (is_array($errorArray)) {
1956 $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>',
1957 basename($errorArray['file']),
1958 $errorArray['line'],
1959 $errorArray['message'],
1964 // Add line number to the code
1965 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1967 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1969 htmlentities($code, ENT_QUOTES)
1978 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1979 * beatiful for web-based front-ends. If null is given a message id
1980 * null_timestamp will be resolved and returned.
1982 * @param $timestamp Timestamp to prepare (filter) for display
1983 * @return $readable A readable timestamp
1985 public function doFilterFormatTimestamp ($timestamp) {
1986 // Default value to return
1989 // Is the timestamp null?
1990 if (is_null($timestamp)) {
1991 // Get a message string
1992 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1994 switch ($this->getLanguageInstance()->getLanguageCode()) {
1995 case 'de': // German format is a bit different to default
1996 // Split the GMT stamp up
1997 $dateTime = explode(' ', $timestamp );
1998 $dateArray = explode('-', $dateTime[0]);
1999 $timeArray = explode(':', $dateTime[1]);
2001 // Construct the timestamp
2002 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2012 default: // Default is pass-through
2013 $readable = $timestamp;
2023 * Filter a given number into a localized number
2025 * @param $value The raw value from e.g. database
2026 * @return $localized Localized value
2028 public function doFilterFormatNumber ($value) {
2029 // Generate it from config and localize dependencies
2030 switch ($this->getLanguageInstance()->getLanguageCode()) {
2031 case 'de': // German format is a bit different to default
2032 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2035 default: // US, etc.
2036 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2045 * "Getter" for databse entry
2047 * @return $entry An array with database entries
2048 * @throws NullPointerException If the database result is not found
2049 * @throws InvalidDatabaseResultException If the database result is invalid
2051 protected final function getDatabaseEntry () {
2052 // Is there an instance?
2053 if (!$this->getResultInstance() instanceof SearchableResult) {
2054 // Throw an exception here
2055 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2059 $this->getResultInstance()->rewind();
2061 // Do we have an entry?
2062 if ($this->getResultInstance()->valid() === false) {
2063 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2064 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2068 $this->getResultInstance()->next();
2071 $entry = $this->getResultInstance()->current();
2078 * Getter for field name
2080 * @param $fieldName Field name which we shall get
2081 * @return $fieldValue Field value from the user
2082 * @throws NullPointerException If the result instance is null
2084 public final function getField ($fieldName) {
2085 // Default field value
2088 // Get result instance
2089 $resultInstance = $this->getResultInstance();
2091 // Is this instance null?
2092 if (is_null($resultInstance)) {
2093 // Then the user instance is no longer valid (expired cookies?)
2094 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2097 // Get current array
2098 $fieldArray = $resultInstance->current();
2099 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2101 // Convert dashes to underscore
2102 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2104 // Does the field exist?
2105 if ($this->isFieldSet($fieldName)) {
2107 $fieldValue = $fieldArray[$fieldName2];
2108 } elseif (defined('DEVELOPER')) {
2109 // Missing field entry, may require debugging
2110 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2112 // Missing field entry, may require debugging
2113 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2121 * Checks if given field is set
2123 * @param $fieldName Field name to check
2124 * @return $isSet Whether the given field name is set
2125 * @throws NullPointerException If the result instance is null
2127 public function isFieldSet ($fieldName) {
2128 // Get result instance
2129 $resultInstance = $this->getResultInstance();
2131 // Is this instance null?
2132 if (is_null($resultInstance)) {
2133 // Then the user instance is no longer valid (expired cookies?)
2134 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2137 // Get current array
2138 $fieldArray = $resultInstance->current();
2139 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2141 // Convert dashes to underscore
2142 $fieldName = self::convertDashesToUnderscores($fieldName);
2145 $isSet = isset($fieldArray[$fieldName]);
2152 * Flushs all pending updates to the database layer
2156 public function flushPendingUpdates () {
2157 // Get result instance
2158 $resultInstance = $this->getResultInstance();
2160 // Do we have data to update?
2161 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2162 // Get wrapper class name config entry
2163 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2165 // Create object instance
2166 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2168 // Yes, then send the whole result to the database layer
2169 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2174 * Outputs a deprecation warning to the developer.
2176 * @param $message The message we shall output to the developer
2178 * @todo Write a logging mechanism for productive mode
2180 public function deprecationWarning ($message) {
2181 // Is developer mode active?
2182 if (defined('DEVELOPER')) {
2183 // Debug instance is there?
2184 if (!is_null($this->getDebugInstance())) {
2185 // Output stub message
2186 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2189 trigger_error($message . "<br />\n");
2193 // @TODO Finish this part!
2194 $this->partialStub('Developer mode inactive. Message:' . $message);
2199 * Checks whether the given PHP extension is loaded
2201 * @param $phpExtension The PHP extension we shall check
2202 * @return $isLoaded Whether the PHP extension is loaded
2204 public final function isPhpExtensionLoaded ($phpExtension) {
2206 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2213 * "Getter" as a time() replacement but with milliseconds. You should use this
2214 * method instead of the encapsulated getimeofday() function.
2216 * @return $milliTime Timestamp with milliseconds
2218 public function getMilliTime () {
2219 // Get the time of day as float
2220 $milliTime = gettimeofday(true);
2227 * Idles (sleeps) for given milliseconds
2229 * @return $hasSlept Whether it goes fine
2231 public function idle ($milliSeconds) {
2232 // Sleep is fine by default
2235 // Idle so long with found function
2236 if (function_exists('time_sleep_until')) {
2237 // Get current time and add idle time
2238 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2240 // New PHP 5.1.0 function found, ignore errors
2241 $hasSlept = @time_sleep_until($sleepUntil);
2244 * My Sun station doesn't have that function even with latest PHP
2247 usleep($milliSeconds * 1000);
2254 * Converts a hexadecimal string, even with negative sign as first string to
2255 * a decimal number using BC functions.
2257 * This work is based on comment #86673 on php.net documentation page at:
2258 * <http://de.php.net/manual/en/function.dechex.php#86673>
2260 * @param $hex Hexadecimal string
2261 * @return $dec Decimal number
2263 protected function hex2dec ($hex) {
2264 // Convert to all lower-case
2265 $hex = strtolower($hex);
2267 // Detect sign (negative/positive numbers)
2269 if (substr($hex, 0, 1) == '-') {
2271 $hex = substr($hex, 1);
2274 // Decode the hexadecimal string into a decimal number
2276 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2277 $factor = self::$hexdec[substr($hex, $i, 1)];
2278 $dec = bcadd($dec, bcmul($factor, $e));
2281 // Return the decimal number
2282 return $sign . $dec;
2286 * Converts even very large decimal numbers, also signed, to a hexadecimal
2289 * This work is based on comment #97756 on php.net documentation page at:
2290 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2292 * @param $dec Decimal number, even with negative sign
2293 * @param $maxLength Optional maximum length of the string
2294 * @return $hex Hexadecimal string
2296 protected function dec2hex ($dec, $maxLength = 0) {
2297 // maxLength can be zero or devideable by 2
2298 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2300 // Detect sign (negative/positive numbers)
2307 // Encode the decimal number into a hexadecimal string
2310 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2312 } while ($dec >= 1);
2315 * Leading zeros are required for hex-decimal "numbers". In some
2316 * situations more leading zeros are wanted, so check for both
2319 if ($maxLength > 0) {
2320 // Prepend more zeros
2321 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2322 } elseif ((strlen($hex) % 2) != 0) {
2323 // Only make string's length dividable by 2
2327 // Return the hexadecimal string
2328 return $sign . $hex;
2332 * Converts a ASCII string (0 to 255) into a decimal number.
2334 * @param $asc The ASCII string to be converted
2335 * @return $dec Decimal number
2337 protected function asc2dec ($asc) {
2338 // Convert it into a hexadecimal number
2339 $hex = bin2hex($asc);
2341 // And back into a decimal number
2342 $dec = $this->hex2dec($hex);
2349 * Converts a decimal number into an ASCII string.
2351 * @param $dec Decimal number
2352 * @return $asc An ASCII string
2354 protected function dec2asc ($dec) {
2355 // First convert the number into a hexadecimal string
2356 $hex = $this->dec2hex($dec);
2358 // Then convert it into the ASCII string
2359 $asc = $this->hex2asc($hex);
2366 * Converts a hexadecimal number into an ASCII string. Negative numbers
2369 * @param $hex Hexadecimal string
2370 * @return $asc An ASCII string
2372 protected function hex2asc ($hex) {
2373 // Check for length, it must be devideable by 2
2374 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2375 assert((strlen($hex) % 2) == 0);
2379 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2380 // Get the decimal number of the chunk
2381 $part = hexdec(substr($hex, $idx, 2));
2383 // Add it to the final string
2387 // Return the final string
2392 * Checks whether the given encoded data was encoded with Base64
2394 * @param $encodedData Encoded data we shall check
2395 * @return $isBase64 Whether the encoded data is Base64
2397 protected function isBase64Encoded ($encodedData) {
2399 $isBase64 = (@base64_decode($encodedData, true) !== false);
2406 * Gets a cache key from Criteria instance
2408 * @param $criteriaInstance An instance of a Criteria class
2409 * @param $onlyKeys Only use these keys for a cache key
2410 * @return $cacheKey A cache key suitable for lookup/storage purposes
2412 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2414 $cacheKey = sprintf('%s@%s',
2415 $this->__toString(),
2416 $criteriaInstance->getCacheKey($onlyKeys)
2420 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2425 * Getter for startup time in miliseconds
2427 * @return $startupTime Startup time in miliseconds
2429 protected function getStartupTime () {
2430 return self::$startupTime;
2434 * "Getter" for a printable currently execution time in nice braces
2436 * @return $executionTime Current execution time in nice braces
2438 protected function getPrintableExecutionTime () {
2439 // Caculate the execution time
2440 $executionTime = microtime(true) - $this->getStartupTime();
2442 // Pack it in nice braces
2443 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2446 return $executionTime;
2450 * Hashes a given string with a simple but stronger hash function (no salt)
2451 * and hex-encode it.
2453 * @param $str The string to be hashed
2454 * @return $hash The hash from string $str
2456 public static final function hash ($str) {
2457 // Hash given string with (better secure) hasher
2458 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2465 * "Getter" for length of hash() output. This will be "cached" to speed up
2468 * @return $length Length of hash() output
2470 public static final function getHashLength () {
2472 if (is_null(self::$hashLength)) {
2473 // No, then hash a string and save its length.
2474 self::$hashLength = strlen(self::hash('abc123'));
2478 return self::$hashLength;
2482 * Checks whether the given number is really a number (only chars 0-9).
2484 * @param $num A string consisting only chars between 0 and 9
2485 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2486 * @param $assertMismatch Whether to assert mismatches
2487 * @return $ret The (hopefully) secured numbered value
2489 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2490 // Filter all numbers out
2491 $ret = preg_replace('/[^0123456789]/', '', $num);
2494 if ($castValue === true) {
2495 // Cast to biggest numeric type
2496 $ret = (double) $ret;
2499 // Assert only if requested
2500 if ($assertMismatch === true) {
2501 // Has the whole value changed?
2502 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2510 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2512 * @param $num A string consisting only chars between 0 and 9
2513 * @param $assertMismatch Whether to assert mismatches
2514 * @return $ret The (hopefully) secured hext-numbered value
2516 public function hexval ($num, $assertMismatch = false) {
2517 // Filter all numbers out
2518 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2520 // Assert only if requested
2521 if ($assertMismatch === true) {
2522 // Has the whole value changed?
2523 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2531 * Determines if an element is set in the generic array
2533 * @param $keyGroup Main group for the key
2534 * @param $subGroup Sub group for the key
2535 * @param $key Key to check
2536 * @param $element Element to check
2537 * @return $isset Whether the given key is set
2539 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2541 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2544 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2550 * Determines if a key is set in the generic array
2552 * @param $keyGroup Main group for the key
2553 * @param $subGroup Sub group for the key
2554 * @param $key Key to check
2555 * @return $isset Whether the given key is set
2557 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2559 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2562 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2570 * Determines if a group is set in the generic array
2572 * @param $keyGroup Main group
2573 * @param $subGroup Sub group
2574 * @return $isset Whether the given group is set
2576 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2578 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2581 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2588 * Getter for sub key group
2590 * @param $keyGroup Main key group
2591 * @param $subGroup Sub key group
2592 * @return $array An array with all array elements
2594 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2596 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2597 // No, then abort here
2598 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2603 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2606 return $this->genericArray[$keyGroup][$subGroup];
2610 * Unsets a given key in generic array
2612 * @param $keyGroup Main group for the key
2613 * @param $subGroup Sub group for the key
2614 * @param $key Key to unset
2617 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2619 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2622 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2626 * Unsets a given element in generic array
2628 * @param $keyGroup Main group for the key
2629 * @param $subGroup Sub group for the key
2630 * @param $key Key to unset
2631 * @param $element Element to unset
2634 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2636 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2639 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2643 * Append a string to a given generic array key
2645 * @param $keyGroup Main group for the key
2646 * @param $subGroup Sub group for the key
2647 * @param $key Key to unset
2648 * @param $value Value to add/append
2651 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2653 //* 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);
2655 // Is it already there?
2656 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2658 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2661 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2666 * Append a string to a given generic array element
2668 * @param $keyGroup Main group for the key
2669 * @param $subGroup Sub group for the key
2670 * @param $key Key to unset
2671 * @param $element Element to check
2672 * @param $value Value to add/append
2675 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2677 //* 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);
2679 // Is it already there?
2680 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2682 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2685 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2690 * Sets a string in a given generic array element
2692 * @param $keyGroup Main group for the key
2693 * @param $subGroup Sub group for the key
2694 * @param $key Key to unset
2695 * @param $element Element to check
2696 * @param $value Value to add/append
2699 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2701 //* 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);
2704 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2708 * Initializes given generic array group
2710 * @param $keyGroup Main group for the key
2711 * @param $subGroup Sub group for the key
2712 * @param $key Key to use
2713 * @param $forceInit Optionally force initialization
2716 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2718 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2720 // Is it already set?
2721 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2722 // Already initialized
2723 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2728 $this->genericArray[$keyGroup][$subGroup] = array();
2732 * Initializes given generic array key
2734 * @param $keyGroup Main group for the key
2735 * @param $subGroup Sub group for the key
2736 * @param $key Key to use
2737 * @param $forceInit Optionally force initialization
2740 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2742 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2744 // Is it already set?
2745 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2746 // Already initialized
2747 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2752 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2756 * Initializes given generic array element
2758 * @param $keyGroup Main group for the key
2759 * @param $subGroup Sub group for the key
2760 * @param $key Key to use
2761 * @param $element Element to use
2762 * @param $forceInit Optionally force initialization
2765 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2767 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2769 // Is it already set?
2770 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2771 // Already initialized
2772 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2777 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2781 * Pushes an element to a generic key
2783 * @param $keyGroup Main group for the key
2784 * @param $subGroup Sub group for the key
2785 * @param $key Key to use
2786 * @param $value Value to add/append
2787 * @return $count Number of array elements
2789 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2791 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2794 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2796 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2800 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2803 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2804 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2809 * Pushes an element to a generic array element
2811 * @param $keyGroup Main group for the key
2812 * @param $subGroup Sub group for the key
2813 * @param $key Key to use
2814 * @param $element Element to check
2815 * @param $value Value to add/append
2816 * @return $count Number of array elements
2818 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2820 //* 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));
2823 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2825 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2829 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2832 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2833 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2838 * Pops an element from a generic group
2840 * @param $keyGroup Main group for the key
2841 * @param $subGroup Sub group for the key
2842 * @param $key Key to unset
2843 * @return $value Last "popped" value
2845 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2847 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2850 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2852 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2857 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2860 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2861 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2866 * Shifts an element from a generic group
2868 * @param $keyGroup Main group for the key
2869 * @param $subGroup Sub group for the key
2870 * @param $key Key to unset
2871 * @return $value Last "popped" value
2873 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2875 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2878 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2880 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2885 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2888 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2889 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2894 * Count generic array group
2896 * @param $keyGroup Main group for the key
2897 * @return $count Count of given group
2899 protected final function countGenericArray ($keyGroup) {
2901 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2904 if (!isset($this->genericArray[$keyGroup])) {
2906 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2911 $count = count($this->genericArray[$keyGroup]);
2914 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2921 * Count generic array sub group
2923 * @param $keyGroup Main group for the key
2924 * @param $subGroup Sub group for the key
2925 * @return $count Count of given group
2927 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2929 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2932 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2934 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2939 $count = count($this->genericArray[$keyGroup][$subGroup]);
2942 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2949 * Count generic array elements
2951 * @param $keyGroup Main group for the key
2952 * @param $subGroup Sub group for the key
2953 * @para $key Key to count
2954 * @return $count Count of given key
2956 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2958 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2961 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2963 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2965 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2967 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2972 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2975 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2982 * Getter for whole generic group array
2984 * @param $keyGroup Key group to get
2985 * @return $array Whole generic array group
2987 protected final function getGenericArray ($keyGroup) {
2989 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2992 if (!isset($this->genericArray[$keyGroup])) {
2994 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2999 return $this->genericArray[$keyGroup];
3003 * Setter for generic array key
3005 * @param $keyGroup Key group to get
3006 * @param $subGroup Sub group for the key
3007 * @param $key Key to unset
3008 * @param $value Mixed value from generic array element
3011 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3013 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3016 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3020 * Getter for generic array key
3022 * @param $keyGroup Key group to get
3023 * @param $subGroup Sub group for the key
3024 * @param $key Key to unset
3025 * @return $value Mixed value from generic array element
3027 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3029 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3032 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3034 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3039 return $this->genericArray[$keyGroup][$subGroup][$key];
3043 * Sets a value in given generic array key/element
3045 * @param $keyGroup Main group for the key
3046 * @param $subGroup Sub group for the key
3047 * @param $key Key to set
3048 * @param $element Element to set
3049 * @param $value Value to set
3052 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3054 //* 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));
3057 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3061 * Getter for generic array element
3063 * @param $keyGroup Key group to get
3064 * @param $subGroup Sub group for the key
3065 * @param $key Key to look for
3066 * @param $element Element to look for
3067 * @return $value Mixed value from generic array element
3069 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3071 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3074 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3076 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3081 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3085 * Checks if a given sub group is valid (array)
3087 * @param $keyGroup Key group to get
3088 * @param $subGroup Sub group for the key
3089 * @return $isValid Whether given sub group is valid
3091 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3093 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3096 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3103 * Checks if a given key is valid (array)
3105 * @param $keyGroup Key group to get
3106 * @param $subGroup Sub group for the key
3107 * @param $key Key to check
3108 * @return $isValid Whether given sub group is valid
3110 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3112 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3115 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3122 * Initializes the web output instance
3126 protected function initWebOutputInstance () {
3127 // Get application instance
3128 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
3130 // Init web output instance
3131 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3134 $this->setWebOutputInstance($outputInstance);
3138 * Translates boolean true to 'Y' and false to 'N'
3140 * @param $boolean Boolean value
3141 * @return $translated Translated boolean value
3143 public static final function translateBooleanToYesNo ($boolean) {
3144 // Make sure it is really boolean
3145 assert(is_bool($boolean));
3148 $translated = ($boolean === true) ? 'Y' : 'N';
3150 // ... and return it
3155 * Encodes raw data (almost any type) by "serializing" it and then pack it
3156 * into a "binary format".
3158 * @param $rawData Raw data (almost any type)
3159 * @return $encoded Encoded data
3161 protected function encodeData ($rawData) {
3162 // Make sure no objects or resources pass through
3163 assert(!is_object($rawData));
3164 assert(!is_resource($rawData));
3166 // First "serialize" it (json_encode() is faster than serialize())
3167 $encoded = $this->packString(json_encode($rawData));
3174 * Pack a string into a "binary format". Please execuse me that this is
3175 * widely undocumented. :-(
3177 * @param $str Unpacked string
3178 * @return $packed Packed string
3179 * @todo Improve documentation
3181 protected function packString ($str) {
3183 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3185 // First compress the string (gzcompress is okay)
3186 $str = gzcompress($str);
3191 // And start the "encoding" loop
3192 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3194 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3195 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3197 if (($idx + $i) <= strlen($str)) {
3198 $ord = ord(substr($str, ($idx + $i), 1));
3200 $add = $ord * pow(256, $factor);
3204 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3208 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3209 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3211 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3212 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3218 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3223 * Creates a full-qualified file name (FQFN) for given file name by adding
3224 * a configured temporary file path to it.
3226 * @param $infoInstance An instance of a SplFileInfo class
3227 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
3228 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3229 * @throws FileIoException If the file cannot be written
3231 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
3233 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
3235 // Is the path writeable?
3236 if (!is_writable($basePath)) {
3237 // Path is write-protected
3238 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3242 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
3245 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
3247 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
3251 return $tempInstance;
3255 * "Getter" for a printable state name
3257 * @return $stateName Name of the node's state in a printable format
3259 public final function getPrintableState () {
3260 // Default is 'null'
3261 $stateName = 'null';
3263 // Get the state instance
3264 $stateInstance = $this->getStateInstance();
3266 // Is it an instance of Stateable?
3267 if ($stateInstance instanceof Stateable) {
3268 // Then use that state name
3269 $stateName = $stateInstance->getStateName();