3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Compressor\Compressor;
7 use CoreFramework\Configuration\FrameworkConfiguration;
8 use CoreFramework\Connection\Database\DatabaseConnection;
9 use CoreFramework\Controller\Controller;
10 use CoreFramework\Criteria\Criteria;
11 use CoreFramework\Criteria\Local\LocalSearchCriteria;
12 use CoreFramework\Criteria\Local\LocalUpdateCriteria;
13 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
14 use CoreFramework\Factory\ObjectFactory;
15 use CoreFramework\Filesystem\Block;
16 use CoreFramework\Filesystem\FilePointer;
17 use CoreFramework\Filesystem\FrameworkDirectory;
18 use CoreFramework\Generic\FrameworkInterface;
19 use CoreFramework\Generic\NullPointerException;
20 use CoreFramework\Handler\Stream\IoHandler;
21 use CoreFramework\Loader\ClassLoader;
22 use CoreFramework\Manager\ManageableApplication;
23 use CoreFramework\Middleware\Compressor\CompressorChannel;
24 use CoreFramework\Middleware\Debug\DebugMiddleware;
25 use CoreFramework\Parser\Parseable;
26 use CoreFramework\Registry\Register;
27 use CoreFramework\Registry\Registry;
28 use CoreFramework\Request\Requestable;
29 use CoreFramework\Resolver\Resolver;
30 use CoreFramework\Result\Database\CachedDatabaseResult;
31 use CoreFramework\Result\Search\SearchableResult;
32 use CoreFramework\Response\Responseable;
33 use CoreFramework\Stream\Output\OutputStreamer;
34 use CoreFramework\Template\CompileableTemplate;
35 use CoreFramework\User\ManageableAccount;
36 use CoreFramework\Wrapper\Database\DatabaseWrapper;
43 * The simulator system class is the super class of all other classes. This
44 * class handles saving of games etc.
46 * @author Roland Haeder <webmaster@shipsimu.org>
48 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
49 * @license GNU GPL 3.0 or any newer version
50 * @link http://www.shipsimu.org
52 * This program is free software: you can redistribute it and/or modify
53 * it under the terms of the GNU General Public License as published by
54 * the Free Software Foundation, either version 3 of the License, or
55 * (at your option) any later version.
57 * This program is distributed in the hope that it will be useful,
58 * but WITHOUT ANY WARRANTY; without even the implied warranty of
59 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
60 * GNU General Public License for more details.
62 * You should have received a copy of the GNU General Public License
63 * along with this program. If not, see <http://www.gnu.org/licenses/>.
65 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
67 * Length of output from hash()
69 private static $hashLength = NULL;
74 private $realClass = 'BaseFrameworkSystem';
77 * Instance of a Requestable class
79 private $requestInstance = NULL;
82 * Instance of a Responseable class
84 private $responseInstance = NULL;
87 * Search criteria instance
89 private $searchInstance = NULL;
92 * Update criteria instance
94 private $updateInstance = NULL;
97 * The file I/O instance for the template loader
99 private $fileIoInstance = NULL;
104 private $resolverInstance = NULL;
107 * Template engine instance
109 private $templateInstance = NULL;
112 * Database result instance
114 private $resultInstance = NULL;
117 * Instance for user class
119 private $userInstance = NULL;
122 * A controller instance
124 private $controllerInstance = NULL;
129 private $rngInstance = NULL;
132 * Instance of a crypto helper
134 private $cryptoInstance = NULL;
137 * Instance of an Iterator class
139 private $iteratorInstance = NULL;
142 * Instance of the list
144 private $listInstance = NULL;
149 private $menuInstance = NULL;
152 * Instance of the image
154 private $imageInstance = NULL;
157 * Instance of the stacker
159 private $stackInstance = NULL;
162 * A Compressor instance
164 private $compressorInstance = NULL;
167 * A Parseable instance
169 private $parserInstance = NULL;
172 * A HandleableProtocol instance
174 private $protocolInstance = NULL;
177 * A database wrapper instance
179 private $databaseInstance = NULL;
182 * A helper instance for the form
184 private $helperInstance = NULL;
187 * An instance of a Source class
189 private $sourceInstance = NULL;
192 * An instance of a UrlSource class
194 private $urlSourceInstance = NULL;
197 * An instance of a InputStream class
199 private $inputStreamInstance = NULL;
202 * An instance of a OutputStream class
204 private $outputStreamInstance = NULL;
207 * Networkable handler instance
209 private $handlerInstance = NULL;
212 * Visitor handler instance
214 private $visitorInstance = NULL;
219 private $dhtInstance = NULL;
222 * An instance of a database wrapper class
224 private $wrapperInstance = NULL;
227 * An instance of a file I/O pointer class (not handler)
229 private $pointerInstance = NULL;
232 * An instance of an Indexable class
234 private $indexInstance = NULL;
237 * An instance of a Block class
239 private $blockInstance = NULL;
244 private $minableInstance = NULL;
247 * A FrameworkDirectory instance
249 private $directoryInstance = NULL;
254 private $listenerInstance = NULL;
257 * An instance of a communicator
259 private $communicatorInstance = NULL;
262 * The concrete output instance
264 private $outputInstance = NULL;
269 private $stateInstance = NULL;
272 * Thousands separator
274 private $thousands = '.'; // German
279 private $decimals = ','; // German
284 private $socketResource = FALSE;
287 * Regular expression to use for validation
289 private $regularExpression = '';
294 private $packageData = array();
299 private $genericArray = array();
304 private $commandName = '';
309 private $controllerName = '';
312 * Name of used protocol
314 private $protocolName = 'invalid';
317 * Array with bitmasks and such for pack/unpack methods to support both
318 * 32-bit and 64-bit systems
320 private $packingData = array(
323 'left' => 0xffff0000,
324 'right' => 0x0000ffff,
330 'left' => 0xffffffff00000000,
331 'right' => 0x00000000ffffffff,
338 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
340 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
342 private $archArrayElement = FALSE;
344 /***********************
345 * Exception codes.... *
346 ***********************/
348 // @todo Try to clean these constants up
349 const EXCEPTION_IS_NULL_POINTER = 0x001;
350 const EXCEPTION_IS_NO_OBJECT = 0x002;
351 const EXCEPTION_IS_NO_ARRAY = 0x003;
352 const EXCEPTION_MISSING_METHOD = 0x004;
353 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
354 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
355 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
356 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
357 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
358 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
359 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
360 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
361 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
362 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
363 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
364 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
365 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
366 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
367 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
368 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
369 const EXCEPTION_PATH_NOT_FOUND = 0x015;
370 const EXCEPTION_INVALID_PATH_NAME = 0x016;
371 const EXCEPTION_READ_PROTECED_PATH = 0x017;
372 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
373 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
374 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
375 const EXCEPTION_INVALID_RESOURCE = 0x01b;
376 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
377 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
378 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
379 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
380 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
381 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
382 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
383 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
384 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
385 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
386 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
387 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
388 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
389 const EXCEPTION_INVALID_STRING = 0x029;
390 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
391 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
392 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
393 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
394 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
395 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
396 const EXCEPTION_MISSING_ELEMENT = 0x030;
397 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
398 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
399 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
400 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
401 const EXCEPTION_FATAL_ERROR = 0x035;
402 const EXCEPTION_FILE_NOT_FOUND = 0x036;
403 const EXCEPTION_ASSERTION_FAILED = 0x037;
404 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
405 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
406 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
407 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
408 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
409 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
412 * Hexadecimal->Decimal translation array
414 private static $hexdec = array(
434 * Decimal->hexadecimal translation array
436 private static $dechex = array(
456 * Startup time in miliseconds
458 private static $startupTime = 0;
461 * Protected super constructor
463 * @param $className Name of the class
466 protected function __construct ($className) {
468 $this->setRealClass($className);
470 // Set configuration instance if no registry ...
471 if (!$this instanceof Register) {
472 // ... because registries doesn't need to be configured
473 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
476 // Is the startup time set? (0 cannot be TRUE anymore)
477 if (self::$startupTime == 0) {
479 self::$startupTime = microtime(TRUE);
483 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
487 * Destructor for all classes. You should not call this method on your own.
491 public function __destruct () {
492 // Flush any updated entries to the database
493 $this->flushPendingUpdates();
495 // Is this object already destroyed?
496 if ($this->__toString() != 'DestructedObject') {
497 // Destroy all informations about this class but keep some text about it alive
498 $this->setRealClass('DestructedObject');
499 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
500 // Already destructed object
501 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
506 // Do not call this twice
507 trigger_error(__METHOD__ . ': Called twice.');
513 * The __call() method where all non-implemented methods end up
515 * @param $methodName Name of the missing method
516 * @args $args Arguments passed to the method
519 public final function __call ($methodName, $args) {
520 return self::__callStatic($methodName, $args);
524 * The __callStatic() method where all non-implemented static methods end up
526 * @param $methodName Name of the missing method
527 * @args $args Arguments passed to the method
530 public static final function __callStatic ($methodName, $args) {
532 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
534 // Init argument string
537 // Is it NULL, empty or an array?
538 if (is_null($args)) {
540 $argsString = 'NULL';
541 } elseif (is_array($args)) {
545 // Some arguments are there
546 foreach ($args as $arg) {
547 // Add data about the argument
548 $argsString .= gettype($arg) . ':';
551 // Found a NULL argument
552 $argsString .= 'NULL';
553 } elseif (is_string($arg)) {
554 // Add length for strings
555 $argsString .= strlen($arg);
556 } elseif ((is_int($arg)) || (is_float($arg))) {
559 } elseif (is_array($arg)) {
560 // .. or size if array
561 $argsString .= count($arg);
562 } elseif (is_object($arg)) {
564 $reflection = new ReflectionClass($arg);
566 // Is an other object, maybe no __toString() available
567 $argsString .= $reflection->getName();
568 } elseif ($arg === TRUE) {
569 // ... is boolean 'TRUE'
570 $argsString .= 'TRUE';
571 } elseif ($arg === FALSE) {
572 // ... is boolean 'FALSE'
573 $argsString .= 'FALSE';
576 // Comma for next one
581 if (substr($argsString, -2, 1) == ',') {
582 $argsString = substr($argsString, 0, -2);
588 // Invalid arguments!
589 $argsString = '!INVALID:' . gettype($args) . '!';
592 // Output stub message
593 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
594 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
604 * Getter for $realClass
606 * @return $realClass The name of the real class (not BaseFrameworkSystem)
608 public function __toString () {
609 return $this->realClass;
613 * Magic method to catch setting of missing but set class fields/attributes
615 * @param $name Name of the field/attribute
616 * @param $value Value to store
619 public final function __set ($name, $value) {
620 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
623 print_r($value, TRUE)
628 * Magic method to catch getting of missing fields/attributes
630 * @param $name Name of the field/attribute
633 public final function __get ($name) {
634 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
640 * Magic method to catch unsetting of missing fields/attributes
642 * @param $name Name of the field/attribute
645 public final function __unset ($name) {
646 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
652 * Magic method to catch object serialization
654 * @return $unsupported Unsupported method
655 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
657 public final function __sleep () {
658 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
662 * Magic method to catch object deserialization
664 * @return $unsupported Unsupported method
665 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
667 public final function __wakeup () {
668 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
672 * Magic method to catch calls when an object instance is called
674 * @return $unsupported Unsupported method
675 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
677 public final function __invoke () {
678 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
682 * Setter for the real class name
684 * @param $realClass Class name (string)
687 public final function setRealClass ($realClass) {
689 $this->realClass = (string) $realClass;
693 * Setter for database result instance
695 * @param $resultInstance An instance of a database result class
697 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
699 protected final function setResultInstance (SearchableResult $resultInstance) {
700 $this->resultInstance = $resultInstance;
704 * Getter for database result instance
706 * @return $resultInstance An instance of a database result class
708 public final function getResultInstance () {
709 return $this->resultInstance;
713 * Setter for template engine instances
715 * @param $templateInstance An instance of a template engine class
718 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
719 $this->templateInstance = $templateInstance;
723 * Getter for template engine instances
725 * @return $templateInstance An instance of a template engine class
727 protected final function getTemplateInstance () {
728 return $this->templateInstance;
732 * Setter for search instance
734 * @param $searchInstance Searchable criteria instance
737 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
738 $this->searchInstance = $searchInstance;
742 * Getter for search instance
744 * @return $searchInstance Searchable criteria instance
746 public final function getSearchInstance () {
747 return $this->searchInstance;
751 * Setter for update instance
753 * @param $updateInstance An instance of a LocalUpdateCriteria clase
756 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
757 $this->updateInstance = $updateInstance;
761 * Getter for update instance
763 * @return $updateInstance Updateable criteria instance
765 public final function getUpdateInstance () {
766 return $this->updateInstance;
770 * Setter for resolver instance
772 * @param $resolverInstance Instance of a command resolver class
775 public final function setResolverInstance (Resolver $resolverInstance) {
776 $this->resolverInstance = $resolverInstance;
780 * Getter for resolver instance
782 * @return $resolverInstance Instance of a command resolver class
784 public final function getResolverInstance () {
785 return $this->resolverInstance;
789 * Setter for language instance
791 * @param $configInstance The configuration instance which shall
792 * be FrameworkConfiguration
795 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
796 Registry::getRegistry()->addInstance('config', $configInstance);
800 * Getter for configuration instance
802 * @return $configInstance Configuration instance
804 public final function getConfigInstance () {
805 $configInstance = Registry::getRegistry()->getInstance('config');
806 return $configInstance;
810 * Setter for debug instance
812 * @param $debugInstance The instance for debug output class
815 public final function setDebugInstance (DebugMiddleware $debugInstance) {
816 Registry::getRegistry()->addInstance('debug', $debugInstance);
820 * Getter for debug instance
822 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
824 public final function getDebugInstance () {
825 // Get debug instance
826 $debugInstance = Registry::getRegistry()->getInstance('debug');
829 return $debugInstance;
833 * Setter for web output instance
835 * @param $webInstance The instance for web output class
838 public final function setWebOutputInstance (OutputStreamer $webInstance) {
839 Registry::getRegistry()->addInstance('web_output', $webInstance);
843 * Getter for web output instance
845 * @return $webOutputInstance - Instance to class WebOutput
847 public final function getWebOutputInstance () {
848 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
849 return $webOutputInstance;
853 * Setter for database instance
855 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
858 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
859 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
863 * Getter for database layer
865 * @return $databaseInstance The database layer instance
867 public final function getDatabaseInstance () {
869 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
872 return $databaseInstance;
876 * Setter for compressor channel
878 * @param $compressorInstance An instance of CompressorChannel
881 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
882 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
886 * Getter for compressor channel
888 * @return $compressorInstance The compressor channel
890 public final function getCompressorChannel () {
891 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
892 return $compressorInstance;
896 * Protected getter for a manageable application helper class
898 * @return $applicationInstance An instance of a manageable application helper class
900 protected final function getApplicationInstance () {
901 $applicationInstance = Registry::getRegistry()->getInstance('application');
902 return $applicationInstance;
906 * Setter for a manageable application helper class
908 * @param $applicationInstance An instance of a manageable application helper class
911 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
912 Registry::getRegistry()->addInstance('application', $applicationInstance);
916 * Setter for request instance
918 * @param $requestInstance An instance of a Requestable class
921 public final function setRequestInstance (Requestable $requestInstance) {
922 $this->requestInstance = $requestInstance;
926 * Getter for request instance
928 * @return $requestInstance An instance of a Requestable class
930 public final function getRequestInstance () {
931 return $this->requestInstance;
935 * Setter for response instance
937 * @param $responseInstance An instance of a Responseable class
940 public final function setResponseInstance (Responseable $responseInstance) {
941 $this->responseInstance = $responseInstance;
945 * Getter for response instance
947 * @return $responseInstance An instance of a Responseable class
949 public final function getResponseInstance () {
950 return $this->responseInstance;
954 * Private getter for language instance
956 * @return $langInstance An instance to the language sub-system
958 protected final function getLanguageInstance () {
959 $langInstance = Registry::getRegistry()->getInstance('language');
960 return $langInstance;
964 * Setter for language instance
966 * @param $langInstance An instance to the language sub-system
968 * @see LanguageSystem
970 public final function setLanguageInstance (ManageableLanguage $langInstance) {
971 Registry::getRegistry()->addInstance('language', $langInstance);
975 * Private getter for file IO instance
977 * @return $fileIoInstance An instance to the file I/O sub-system
979 protected final function getFileIoInstance () {
980 return $this->fileIoInstance;
984 * Setter for file I/O instance
986 * @param $fileIoInstance An instance to the file I/O sub-system
989 public final function setFileIoInstance (IoHandler $fileIoInstance) {
990 $this->fileIoInstance = $fileIoInstance;
994 * Protected setter for user instance
996 * @param $userInstance An instance of a user class
999 protected final function setUserInstance (ManageableAccount $userInstance) {
1000 $this->userInstance = $userInstance;
1004 * Getter for user instance
1006 * @return $userInstance An instance of a user class
1008 public final function getUserInstance () {
1009 return $this->userInstance;
1013 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1015 * @param $controllerInstance An instance of the controller
1018 public final function setControllerInstance (Controller $controllerInstance) {
1019 $this->controllerInstance = $controllerInstance;
1023 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1025 * @return $controllerInstance An instance of the controller
1027 public final function getControllerInstance () {
1028 return $this->controllerInstance;
1032 * Setter for RNG instance
1034 * @param $rngInstance An instance of a random number generator (RNG)
1037 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1038 $this->rngInstance = $rngInstance;
1042 * Getter for RNG instance
1044 * @return $rngInstance An instance of a random number generator (RNG)
1046 public final function getRngInstance () {
1047 return $this->rngInstance;
1051 * Setter for Cryptable instance
1053 * @param $cryptoInstance An instance of a Cryptable class
1056 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1057 $this->cryptoInstance = $cryptoInstance;
1061 * Getter for Cryptable instance
1063 * @return $cryptoInstance An instance of a Cryptable class
1065 public final function getCryptoInstance () {
1066 return $this->cryptoInstance;
1070 * Setter for the list instance
1072 * @param $listInstance A list of Listable
1075 protected final function setListInstance (Listable $listInstance) {
1076 $this->listInstance = $listInstance;
1080 * Getter for the list instance
1082 * @return $listInstance A list of Listable
1084 protected final function getListInstance () {
1085 return $this->listInstance;
1089 * Setter for the menu instance
1091 * @param $menuInstance A RenderableMenu instance
1094 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1095 $this->menuInstance = $menuInstance;
1099 * Getter for the menu instance
1101 * @return $menuInstance A RenderableMenu instance
1103 protected final function getMenuInstance () {
1104 return $this->menuInstance;
1108 * Setter for image instance
1110 * @param $imageInstance An instance of an image
1113 public final function setImageInstance (BaseImage $imageInstance) {
1114 $this->imageInstance = $imageInstance;
1118 * Getter for image instance
1120 * @return $imageInstance An instance of an image
1122 public final function getImageInstance () {
1123 return $this->imageInstance;
1127 * Setter for stacker instance
1129 * @param $stackInstance An instance of an stacker
1132 public final function setStackInstance (Stackable $stackInstance) {
1133 $this->stackInstance = $stackInstance;
1137 * Getter for stacker instance
1139 * @return $stackInstance An instance of an stacker
1141 public final function getStackInstance () {
1142 return $this->stackInstance;
1146 * Setter for compressor instance
1148 * @param $compressorInstance An instance of an compressor
1151 public final function setCompressorInstance (Compressor $compressorInstance) {
1152 $this->compressorInstance = $compressorInstance;
1156 * Getter for compressor instance
1158 * @return $compressorInstance An instance of an compressor
1160 public final function getCompressorInstance () {
1161 return $this->compressorInstance;
1165 * Setter for Parseable instance
1167 * @param $parserInstance An instance of an Parseable
1170 public final function setParserInstance (Parseable $parserInstance) {
1171 $this->parserInstance = $parserInstance;
1175 * Getter for Parseable instance
1177 * @return $parserInstance An instance of an Parseable
1179 public final function getParserInstance () {
1180 return $this->parserInstance;
1184 * Setter for HandleableProtocol instance
1186 * @param $protocolInstance An instance of an HandleableProtocol
1189 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1190 $this->protocolInstance = $protocolInstance;
1194 * Getter for HandleableProtocol instance
1196 * @return $protocolInstance An instance of an HandleableProtocol
1198 public final function getProtocolInstance () {
1199 return $this->protocolInstance;
1203 * Setter for DatabaseWrapper instance
1205 * @param $wrapperInstance An instance of an DatabaseWrapper
1208 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1209 $this->wrapperInstance = $wrapperInstance;
1213 * Getter for DatabaseWrapper instance
1215 * @return $wrapperInstance An instance of an DatabaseWrapper
1217 public final function getWrapperInstance () {
1218 return $this->wrapperInstance;
1222 * Setter for socket resource
1224 * @param $socketResource A valid socket resource
1227 public final function setSocketResource ($socketResource) {
1228 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1229 $this->socketResource = $socketResource;
1233 * Getter for socket resource
1235 * @return $socketResource A valid socket resource
1237 public final function getSocketResource () {
1238 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1239 return $this->socketResource;
1243 * Setter for regular expression
1245 * @param $regularExpression A valid regular expression
1248 public final function setRegularExpression ($regularExpression) {
1249 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1250 $this->regularExpression = $regularExpression;
1254 * Getter for regular expression
1256 * @return $regularExpression A valid regular expression
1258 public final function getRegularExpression () {
1259 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1260 return $this->regularExpression;
1264 * Setter for helper instance
1266 * @param $helperInstance An instance of a helper class
1269 protected final function setHelperInstance (Helper $helperInstance) {
1270 $this->helperInstance = $helperInstance;
1274 * Getter for helper instance
1276 * @return $helperInstance An instance of a helper class
1278 public final function getHelperInstance () {
1279 return $this->helperInstance;
1283 * Setter for a Source instance
1285 * @param $sourceInstance An instance of a Source class
1288 protected final function setSourceInstance (Source $sourceInstance) {
1289 $this->sourceInstance = $sourceInstance;
1293 * Getter for a Source instance
1295 * @return $sourceInstance An instance of a Source class
1297 protected final function getSourceInstance () {
1298 return $this->sourceInstance;
1302 * Setter for a UrlSource instance
1304 * @param $sourceInstance An instance of a UrlSource class
1307 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1308 $this->urlSourceInstance = $urlSourceInstance;
1312 * Getter for a UrlSource instance
1314 * @return $urlSourceInstance An instance of a UrlSource class
1316 protected final function getUrlSourceInstance () {
1317 return $this->urlSourceInstance;
1321 * Getter for a InputStream instance
1323 * @param $inputStreamInstance The InputStream instance
1325 protected final function getInputStreamInstance () {
1326 return $this->inputStreamInstance;
1330 * Setter for a InputStream instance
1332 * @param $inputStreamInstance The InputStream instance
1335 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1336 $this->inputStreamInstance = $inputStreamInstance;
1340 * Getter for a OutputStream instance
1342 * @param $outputStreamInstance The OutputStream instance
1344 protected final function getOutputStreamInstance () {
1345 return $this->outputStreamInstance;
1349 * Setter for a OutputStream instance
1351 * @param $outputStreamInstance The OutputStream instance
1354 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1355 $this->outputStreamInstance = $outputStreamInstance;
1359 * Setter for handler instance
1361 * @param $handlerInstance An instance of a Handleable class
1364 protected final function setHandlerInstance (Handleable $handlerInstance) {
1365 $this->handlerInstance = $handlerInstance;
1369 * Getter for handler instance
1371 * @return $handlerInstance A Networkable instance
1373 protected final function getHandlerInstance () {
1374 return $this->handlerInstance;
1378 * Setter for visitor instance
1380 * @param $visitorInstance A Visitor instance
1383 protected final function setVisitorInstance (Visitor $visitorInstance) {
1384 $this->visitorInstance = $visitorInstance;
1388 * Getter for visitor instance
1390 * @return $visitorInstance A Visitor instance
1392 protected final function getVisitorInstance () {
1393 return $this->visitorInstance;
1397 * Setter for DHT instance
1399 * @param $dhtInstance A Distributable instance
1402 protected final function setDhtInstance (Distributable $dhtInstance) {
1403 $this->dhtInstance = $dhtInstance;
1407 * Getter for DHT instance
1409 * @return $dhtInstance A Distributable instance
1411 protected final function getDhtInstance () {
1412 return $this->dhtInstance;
1416 * Setter for raw package Data
1418 * @param $packageData Raw package Data
1421 public final function setPackageData (array $packageData) {
1422 $this->packageData = $packageData;
1426 * Getter for raw package Data
1428 * @return $packageData Raw package Data
1430 public function getPackageData () {
1431 return $this->packageData;
1436 * Setter for Iterator instance
1438 * @param $iteratorInstance An instance of an Iterator
1441 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1442 $this->iteratorInstance = $iteratorInstance;
1446 * Getter for Iterator instance
1448 * @return $iteratorInstance An instance of an Iterator
1450 public final function getIteratorInstance () {
1451 return $this->iteratorInstance;
1455 * Setter for FilePointer instance
1457 * @param $pointerInstance An instance of an FilePointer class
1460 protected final function setPointerInstance (FilePointer $pointerInstance) {
1461 $this->pointerInstance = $pointerInstance;
1465 * Getter for FilePointer instance
1467 * @return $pointerInstance An instance of an FilePointer class
1469 public final function getPointerInstance () {
1470 return $this->pointerInstance;
1474 * Unsets pointer instance which triggers a call of __destruct() if the
1475 * instance is still there. This is surely not fatal on already "closed"
1476 * file pointer instances.
1478 * I don't want to mess around with above setter by giving it a default
1479 * value NULL as setter should always explicitly only set (existing) object
1480 * instances and NULL is NULL.
1484 protected final function unsetPointerInstance () {
1485 // Simply it to NULL
1486 $this->pointerInstance = NULL;
1490 * Setter for Indexable instance
1492 * @param $indexInstance An instance of an Indexable class
1495 protected final function setIndexInstance (Indexable $indexInstance) {
1496 $this->indexInstance = $indexInstance;
1500 * Getter for Indexable instance
1502 * @return $indexInstance An instance of an Indexable class
1504 public final function getIndexInstance () {
1505 return $this->indexInstance;
1509 * Setter for Block instance
1511 * @param $blockInstance An instance of an Block class
1514 protected final function setBlockInstance (Block $blockInstance) {
1515 $this->blockInstance = $blockInstance;
1519 * Getter for Block instance
1521 * @return $blockInstance An instance of an Block class
1523 public final function getBlockInstance () {
1524 return $this->blockInstance;
1528 * Setter for Minable instance
1530 * @param $minableInstance A Minable instance
1533 protected final function setMinableInstance (Minable $minableInstance) {
1534 $this->minableInstance = $minableInstance;
1538 * Getter for minable instance
1540 * @return $minableInstance A Minable instance
1542 protected final function getMinableInstance () {
1543 return $this->minableInstance;
1547 * Setter for FrameworkDirectory instance
1549 * @param $directoryInstance A FrameworkDirectory instance
1552 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1553 $this->directoryInstance = $directoryInstance;
1557 * Getter for FrameworkDirectory instance
1559 * @return $directoryInstance A FrameworkDirectory instance
1561 protected final function getDirectoryInstance () {
1562 return $this->directoryInstance;
1566 * Setter for listener instance
1568 * @param $listenerInstance A Listenable instance
1571 protected final function setListenerInstance (Listenable $listenerInstance) {
1572 $this->listenerInstance = $listenerInstance;
1576 * Getter for listener instance
1578 * @return $listenerInstance A Listenable instance
1580 protected final function getListenerInstance () {
1581 return $this->listenerInstance;
1585 * Getter for communicator instance
1587 * @return $communicatorInstance An instance of a Communicator class
1589 public final function getCommunicatorInstance () {
1590 return $this->communicatorInstance;
1594 * Setter for communicator instance
1596 * @param $communicatorInstance An instance of a Communicator class
1599 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1600 $this->communicatorInstance = $communicatorInstance;
1604 * Setter for state instance
1606 * @param $stateInstance A Stateable instance
1609 public final function setStateInstance (Stateable $stateInstance) {
1610 $this->stateInstance = $stateInstance;
1614 * Getter for state instance
1616 * @return $stateInstance A Stateable instance
1618 public final function getStateInstance () {
1619 return $this->stateInstance;
1623 * Setter for output instance
1625 * @param $outputInstance The debug output instance
1628 public final function setOutputInstance (OutputStreamer $outputInstance) {
1629 $this->outputInstance = $outputInstance;
1633 * Getter for output instance
1635 * @return $outputInstance The debug output instance
1637 public final function getOutputInstance () {
1638 return $this->outputInstance;
1642 * Setter for command name
1644 * @param $commandName Last validated command name
1647 protected final function setCommandName ($commandName) {
1648 $this->commandName = $commandName;
1652 * Getter for command name
1654 * @return $commandName Last validated command name
1656 protected final function getCommandName () {
1657 return $this->commandName;
1661 * Setter for controller name
1663 * @param $controllerName Last validated controller name
1666 protected final function setControllerName ($controllerName) {
1667 $this->controllerName = $controllerName;
1671 * Getter for controller name
1673 * @return $controllerName Last validated controller name
1675 protected final function getControllerName () {
1676 return $this->controllerName;
1680 * Getter for protocol name
1682 * @return $protocolName Name of used protocol
1684 public final function getProtocolName () {
1685 return $this->protocolName;
1689 * Setter for protocol name
1691 * @param $protocolName Name of used protocol
1694 protected final function setProtocolName ($protocolName) {
1695 $this->protocolName = $protocolName;
1699 * Checks whether an object equals this object. You should overwrite this
1700 * method to implement own equality checks
1702 * @param $objectInstance An instance of a FrameworkInterface object
1703 * @return $equals Whether both objects equals
1705 public function equals (FrameworkInterface $objectInstance) {
1708 $this->__toString() == $objectInstance->__toString()
1710 $this->hashCode() == $objectInstance->hashCode()
1713 // Return the result
1718 * Generates a generic hash code of this class. You should really overwrite
1719 * this method with your own hash code generator code. But keep KISS in mind.
1721 * @return $hashCode A generic hash code respresenting this whole class
1723 public function hashCode () {
1725 return crc32($this->__toString());
1729 * Formats computer generated price values into human-understandable formats
1730 * with thousand and decimal separators.
1732 * @param $value The in computer format value for a price
1733 * @param $currency The currency symbol (use HTML-valid characters!)
1734 * @param $decNum Number of decimals after commata
1735 * @return $price The for the current language formated price string
1736 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1737 * thousands separator
1740 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1741 // Are all required attriutes set?
1742 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1743 // Throw an exception
1744 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1748 $value = (float) $value;
1750 // Reformat the US number
1751 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1753 // Return as string...
1758 * Appends a trailing slash to a string
1760 * @param $str A string (maybe) without trailing slash
1761 * @return $str A string with an auto-appended trailing slash
1763 public final function addMissingTrailingSlash ($str) {
1764 // Is there a trailing slash?
1765 if (substr($str, -1, 1) != '/') {
1769 // Return string with trailing slash
1774 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1775 * application helper instance (ApplicationHelper by default).
1777 * @param $applicationInstance An application helper instance or
1778 * null if we shall use the default
1779 * @return $templateInstance The template engine instance
1780 * @throws NullPointerException If the discovered application
1781 * instance is still null
1783 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1784 // Is the application instance set?
1785 if (is_null($applicationInstance)) {
1786 // Get the current instance
1787 $applicationInstance = $this->getApplicationInstance();
1790 if (is_null($applicationInstance)) {
1791 // Thrown an exception
1792 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1796 // Initialize the template engine
1797 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1799 // Return the prepared instance
1800 return $templateInstance;
1804 * Debugs this instance by putting out it's full content
1806 * @param $message Optional message to show in debug output
1809 public final function debugInstance ($message = '') {
1810 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1811 restore_error_handler();
1816 // Is a message set?
1817 if (!empty($message)) {
1818 // Construct message
1819 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1822 // Generate the output
1823 $content .= sprintf('<pre>%s</pre>',
1826 print_r($this, TRUE)
1832 ApplicationEntryPoint::app_exit(sprintf('<div class="debug_header">%s debug output:</div><div class="debug_content">%s</div>Loaded includes: <div class="debug_include_list">%s</div>',
1833 $this->__toString(),
1835 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1840 * Replaces control characters with printable output
1842 * @param $str String with control characters
1843 * @return $str Replaced string
1845 protected function replaceControlCharacters ($str) {
1848 chr(13), '[r]', str_replace(
1849 chr(10), '[n]', str_replace(
1859 * Output a partial stub message for the caller method
1861 * @param $message An optional message to display
1864 protected function partialStub ($message = '') {
1865 // Get the backtrace
1866 $backtrace = debug_backtrace();
1868 // Generate the class::method string
1869 $methodName = 'UnknownClass->unknownMethod';
1870 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1871 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1874 // Construct the full message
1875 $stubMessage = sprintf('[%s:] Partial stub!',
1879 // Is the extra message given?
1880 if (!empty($message)) {
1881 // Then add it as well
1882 $stubMessage .= ' Message: ' . $message;
1885 // Debug instance is there?
1886 if (!is_null($this->getDebugInstance())) {
1887 // Output stub message
1888 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1891 trigger_error($stubMessage);
1897 * Outputs a debug backtrace and stops further script execution
1899 * @param $message An optional message to output
1900 * @param $doExit Whether exit the program (TRUE is default)
1903 public function debugBackTrace ($message = '', $doExit = TRUE) {
1904 // Sorry, there is no other way getting this nice backtrace
1905 if (!empty($message)) {
1907 printf('Message: %s<br />' . PHP_EOL, $message);
1911 debug_print_backtrace();
1915 if ($doExit === TRUE) {
1921 * Creates an instance of a debugger instance
1923 * @param $className Name of the class (currently unsupported)
1924 * @param $lineNumber Line number where the call was made
1925 * @return $debugInstance An instance of a debugger class
1926 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1928 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1929 // Is the instance set?
1930 if (!Registry::getRegistry()->instanceExists('debug')) {
1931 // Init debug instance
1932 $debugInstance = NULL;
1936 // Get a debugger instance
1937 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1938 } catch (NullPointerException $e) {
1939 // Didn't work, no instance there
1940 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1943 // Empty string should be ignored and used for testing the middleware
1944 DebugMiddleware::getSelfInstance()->output('');
1946 // Set it in its own class. This will set it in the registry
1947 $debugInstance->setDebugInstance($debugInstance);
1949 // Get instance from registry
1950 $debugInstance = Registry::getRegistry()->getDebugInstance();
1954 return $debugInstance;
1958 * Simple output of a message with line-break
1960 * @param $message Message to output
1963 public function outputLine ($message) {
1965 print($message . PHP_EOL);
1969 * Outputs a debug message whether to debug instance (should be set!) or
1970 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1971 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1973 * @param $message Message we shall send out...
1974 * @param $doPrint Whether print or die here (default: print)
1975 * @paran $stripTags Whether to strip tags (default: FALSE)
1978 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1979 // Set debug instance to NULL
1980 $debugInstance = NULL;
1984 // Get debug instance
1985 $debugInstance = $this->getDebugInstance();
1986 } catch (NullPointerException $e) {
1987 // The debug instance is not set (yet)
1990 // Is the debug instance there?
1991 if (is_object($debugInstance)) {
1992 // Use debug output handler
1993 $debugInstance->output($message, $stripTags);
1995 if ($doPrint === FALSE) {
1996 // Die here if not printed
2000 // Are debug times enabled?
2001 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
2003 $message = $this->getPrintableExecutionTime() . $message;
2007 if ($doPrint === TRUE) {
2009 $this->outputLine($message);
2018 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2020 * @param $str The string, what ever it is needs to be converted
2021 * @return $className Generated class name
2023 public static final function convertToClassName ($str) {
2027 // Convert all dashes in underscores
2028 $str = self::convertDashesToUnderscores($str);
2030 // Now use that underscores to get classname parts for hungarian style
2031 foreach (explode('_', $str) as $strPart) {
2032 // Make the class name part lower case and first upper case
2033 $className .= ucfirst(strtolower($strPart));
2036 // Return class name
2041 * Converts dashes to underscores, e.g. useable for configuration entries
2043 * @param $str The string with maybe dashes inside
2044 * @return $str The converted string with no dashed, but underscores
2046 public static final function convertDashesToUnderscores ($str) {
2048 $str = str_replace('-', '_', $str);
2050 // Return converted string
2055 * Marks up the code by adding e.g. line numbers
2057 * @param $phpCode Unmarked PHP code
2058 * @return $markedCode Marked PHP code
2060 public function markupCode ($phpCode) {
2065 $errorArray = error_get_last();
2067 // Init the code with error message
2068 if (is_array($errorArray)) {
2070 $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>',
2071 basename($errorArray['file']),
2072 $errorArray['line'],
2073 $errorArray['message'],
2078 // Add line number to the code
2079 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2081 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2083 htmlentities($code, ENT_QUOTES)
2092 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2093 * beatiful for web-based front-ends. If null is given a message id
2094 * null_timestamp will be resolved and returned.
2096 * @param $timestamp Timestamp to prepare (filter) for display
2097 * @return $readable A readable timestamp
2099 public function doFilterFormatTimestamp ($timestamp) {
2100 // Default value to return
2103 // Is the timestamp null?
2104 if (is_null($timestamp)) {
2105 // Get a message string
2106 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2108 switch ($this->getLanguageInstance()->getLanguageCode()) {
2109 case 'de': // German format is a bit different to default
2110 // Split the GMT stamp up
2111 $dateTime = explode(' ', $timestamp );
2112 $dateArray = explode('-', $dateTime[0]);
2113 $timeArray = explode(':', $dateTime[1]);
2115 // Construct the timestamp
2116 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2126 default: // Default is pass-through
2127 $readable = $timestamp;
2137 * Filter a given number into a localized number
2139 * @param $value The raw value from e.g. database
2140 * @return $localized Localized value
2142 public function doFilterFormatNumber ($value) {
2143 // Generate it from config and localize dependencies
2144 switch ($this->getLanguageInstance()->getLanguageCode()) {
2145 case 'de': // German format is a bit different to default
2146 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2149 default: // US, etc.
2150 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2159 * "Getter" for databse entry
2161 * @return $entry An array with database entries
2162 * @throws NullPointerException If the database result is not found
2163 * @throws InvalidDatabaseResultException If the database result is invalid
2165 protected final function getDatabaseEntry () {
2166 // Is there an instance?
2167 if (!$this->getResultInstance() instanceof SearchableResult) {
2168 // Throw an exception here
2169 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2173 $this->getResultInstance()->rewind();
2175 // Do we have an entry?
2176 if ($this->getResultInstance()->valid() === FALSE) {
2177 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2178 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2182 $this->getResultInstance()->next();
2185 $entry = $this->getResultInstance()->current();
2192 * Getter for field name
2194 * @param $fieldName Field name which we shall get
2195 * @return $fieldValue Field value from the user
2196 * @throws NullPointerException If the result instance is null
2198 public final function getField ($fieldName) {
2199 // Default field value
2202 // Get result instance
2203 $resultInstance = $this->getResultInstance();
2205 // Is this instance null?
2206 if (is_null($resultInstance)) {
2207 // Then the user instance is no longer valid (expired cookies?)
2208 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2211 // Get current array
2212 $fieldArray = $resultInstance->current();
2213 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2215 // Convert dashes to underscore
2216 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2218 // Does the field exist?
2219 if ($this->isFieldSet($fieldName)) {
2221 $fieldValue = $fieldArray[$fieldName2];
2222 } elseif (defined('DEVELOPER')) {
2223 // Missing field entry, may require debugging
2224 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2226 // Missing field entry, may require debugging
2227 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2235 * Checks if given field is set
2237 * @param $fieldName Field name to check
2238 * @return $isSet Whether the given field name is set
2239 * @throws NullPointerException If the result instance is null
2241 public function isFieldSet ($fieldName) {
2242 // Get result instance
2243 $resultInstance = $this->getResultInstance();
2245 // Is this instance null?
2246 if (is_null($resultInstance)) {
2247 // Then the user instance is no longer valid (expired cookies?)
2248 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2251 // Get current array
2252 $fieldArray = $resultInstance->current();
2253 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2255 // Convert dashes to underscore
2256 $fieldName = self::convertDashesToUnderscores($fieldName);
2259 $isSet = isset($fieldArray[$fieldName]);
2266 * Flushs all pending updates to the database layer
2270 public function flushPendingUpdates () {
2271 // Get result instance
2272 $resultInstance = $this->getResultInstance();
2274 // Do we have data to update?
2275 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2276 // Get wrapper class name config entry
2277 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2279 // Create object instance
2280 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2282 // Yes, then send the whole result to the database layer
2283 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2288 * Outputs a deprecation warning to the developer.
2290 * @param $message The message we shall output to the developer
2292 * @todo Write a logging mechanism for productive mode
2294 public function deprecationWarning ($message) {
2295 // Is developer mode active?
2296 if (defined('DEVELOPER')) {
2297 // Debug instance is there?
2298 if (!is_null($this->getDebugInstance())) {
2299 // Output stub message
2300 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2303 trigger_error($message . "<br />\n");
2307 // @TODO Finish this part!
2308 $this->partialStub('Developer mode inactive. Message:' . $message);
2313 * Checks whether the given PHP extension is loaded
2315 * @param $phpExtension The PHP extension we shall check
2316 * @return $isLoaded Whether the PHP extension is loaded
2318 public final function isPhpExtensionLoaded ($phpExtension) {
2320 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2327 * "Getter" as a time() replacement but with milliseconds. You should use this
2328 * method instead of the encapsulated getimeofday() function.
2330 * @return $milliTime Timestamp with milliseconds
2332 public function getMilliTime () {
2333 // Get the time of day as float
2334 $milliTime = gettimeofday(TRUE);
2341 * Idles (sleeps) for given milliseconds
2343 * @return $hasSlept Whether it goes fine
2345 public function idle ($milliSeconds) {
2346 // Sleep is fine by default
2349 // Idle so long with found function
2350 if (function_exists('time_sleep_until')) {
2351 // Get current time and add idle time
2352 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2354 // New PHP 5.1.0 function found, ignore errors
2355 $hasSlept = @time_sleep_until($sleepUntil);
2358 * My Sun station doesn't have that function even with latest PHP
2361 usleep($milliSeconds * 1000);
2368 * Converts a hexadecimal string, even with negative sign as first string to
2369 * a decimal number using BC functions.
2371 * This work is based on comment #86673 on php.net documentation page at:
2372 * <http://de.php.net/manual/en/function.dechex.php#86673>
2374 * @param $hex Hexadecimal string
2375 * @return $dec Decimal number
2377 protected function hex2dec ($hex) {
2378 // Convert to all lower-case
2379 $hex = strtolower($hex);
2381 // Detect sign (negative/positive numbers)
2383 if (substr($hex, 0, 1) == '-') {
2385 $hex = substr($hex, 1);
2388 // Decode the hexadecimal string into a decimal number
2390 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2391 $factor = self::$hexdec[substr($hex, $i, 1)];
2392 $dec = bcadd($dec, bcmul($factor, $e));
2395 // Return the decimal number
2396 return $sign . $dec;
2400 * Converts even very large decimal numbers, also signed, to a hexadecimal
2403 * This work is based on comment #97756 on php.net documentation page at:
2404 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2406 * @param $dec Decimal number, even with negative sign
2407 * @param $maxLength Optional maximum length of the string
2408 * @return $hex Hexadecimal string
2410 protected function dec2hex ($dec, $maxLength = 0) {
2411 // maxLength can be zero or devideable by 2
2412 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2414 // Detect sign (negative/positive numbers)
2421 // Encode the decimal number into a hexadecimal string
2424 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2426 } while ($dec >= 1);
2429 * Leading zeros are required for hex-decimal "numbers". In some
2430 * situations more leading zeros are wanted, so check for both
2433 if ($maxLength > 0) {
2434 // Prepend more zeros
2435 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2436 } elseif ((strlen($hex) % 2) != 0) {
2437 // Only make string's length dividable by 2
2441 // Return the hexadecimal string
2442 return $sign . $hex;
2446 * Converts a ASCII string (0 to 255) into a decimal number.
2448 * @param $asc The ASCII string to be converted
2449 * @return $dec Decimal number
2451 protected function asc2dec ($asc) {
2452 // Convert it into a hexadecimal number
2453 $hex = bin2hex($asc);
2455 // And back into a decimal number
2456 $dec = $this->hex2dec($hex);
2463 * Converts a decimal number into an ASCII string.
2465 * @param $dec Decimal number
2466 * @return $asc An ASCII string
2468 protected function dec2asc ($dec) {
2469 // First convert the number into a hexadecimal string
2470 $hex = $this->dec2hex($dec);
2472 // Then convert it into the ASCII string
2473 $asc = $this->hex2asc($hex);
2480 * Converts a hexadecimal number into an ASCII string. Negative numbers
2483 * @param $hex Hexadecimal string
2484 * @return $asc An ASCII string
2486 protected function hex2asc ($hex) {
2487 // Check for length, it must be devideable by 2
2488 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2489 assert((strlen($hex) % 2) == 0);
2493 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2494 // Get the decimal number of the chunk
2495 $part = hexdec(substr($hex, $idx, 2));
2497 // Add it to the final string
2501 // Return the final string
2506 * Checks whether the given encoded data was encoded with Base64
2508 * @param $encodedData Encoded data we shall check
2509 * @return $isBase64 Whether the encoded data is Base64
2511 protected function isBase64Encoded ($encodedData) {
2513 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2520 * "Getter" to get response/request type from analysis of the system.
2522 * @return $responseType Analyzed response type
2524 protected static function getResponseTypeFromSystem () {
2525 // Default is console
2526 $responseType = 'console';
2528 // Is 'HTTP_HOST' set?
2529 if (isset($_SERVER['HTTP_HOST'])) {
2531 * Then it is a HTML response/request as RSS and so on may be
2532 * transfered over HTTP as well.
2534 $responseType = 'html';
2538 return $responseType;
2542 * Gets a cache key from Criteria instance
2544 * @param $criteriaInstance An instance of a Criteria class
2545 * @param $onlyKeys Only use these keys for a cache key
2546 * @return $cacheKey A cache key suitable for lookup/storage purposes
2548 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2550 $cacheKey = sprintf('%s@%s',
2551 $this->__toString(),
2552 $criteriaInstance->getCacheKey($onlyKeys)
2556 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2561 * Getter for startup time in miliseconds
2563 * @return $startupTime Startup time in miliseconds
2565 protected function getStartupTime () {
2566 return self::$startupTime;
2570 * "Getter" for a printable currently execution time in nice braces
2572 * @return $executionTime Current execution time in nice braces
2574 protected function getPrintableExecutionTime () {
2575 // Caculate the execution time
2576 $executionTime = microtime(TRUE) - $this->getStartupTime();
2578 // Pack it in nice braces
2579 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2582 return $executionTime;
2586 * Hashes a given string with a simple but stronger hash function (no salt)
2587 * and hex-encode it.
2589 * @param $str The string to be hashed
2590 * @return $hash The hash from string $str
2592 public static final function hash ($str) {
2593 // Hash given string with (better secure) hasher
2594 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2601 * "Getter" for length of hash() output. This will be "cached" to speed up
2604 * @return $length Length of hash() output
2606 public static final function getHashLength () {
2608 if (is_null(self::$hashLength)) {
2609 // No, then hash a string and save its length.
2610 self::$hashLength = strlen(self::hash('abc123'));
2614 return self::$hashLength;
2618 * Checks whether the given number is really a number (only chars 0-9).
2620 * @param $num A string consisting only chars between 0 and 9
2621 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2622 * @param $assertMismatch Whether to assert mismatches
2623 * @return $ret The (hopefully) secured numbered value
2625 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2626 // Filter all numbers out
2627 $ret = preg_replace('/[^0123456789]/', '', $num);
2630 if ($castValue === TRUE) {
2631 // Cast to biggest numeric type
2632 $ret = (double) $ret;
2635 // Assert only if requested
2636 if ($assertMismatch === TRUE) {
2637 // Has the whole value changed?
2638 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2646 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2648 * @param $num A string consisting only chars between 0 and 9
2649 * @param $assertMismatch Whether to assert mismatches
2650 * @return $ret The (hopefully) secured hext-numbered value
2652 public function hexval ($num, $assertMismatch = FALSE) {
2653 // Filter all numbers out
2654 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2656 // Assert only if requested
2657 if ($assertMismatch === TRUE) {
2658 // Has the whole value changed?
2659 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2667 * Checks whether start/end marker are set
2669 * @param $data Data to be checked
2670 * @return $isset Whether start/end marker are set
2672 public final function ifStartEndMarkersSet ($data) {
2674 $isset = ((substr($data, 0, strlen(BaseRawDataHandler::STREAM_START_MARKER)) == BaseRawDataHandler::STREAM_START_MARKER) && (substr($data, -1 * strlen(BaseRawDataHandler::STREAM_END_MARKER), strlen(BaseRawDataHandler::STREAM_END_MARKER)) == BaseRawDataHandler::STREAM_END_MARKER));
2676 // ... and return it
2681 * Determines if an element is set in the generic array
2683 * @param $keyGroup Main group for the key
2684 * @param $subGroup Sub group for the key
2685 * @param $key Key to check
2686 * @param $element Element to check
2687 * @return $isset Whether the given key is set
2689 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2691 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2694 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2700 * Determines if a key is set in the generic array
2702 * @param $keyGroup Main group for the key
2703 * @param $subGroup Sub group for the key
2704 * @param $key Key to check
2705 * @return $isset Whether the given key is set
2707 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2709 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2712 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2720 * Determines if a group is set in the generic array
2722 * @param $keyGroup Main group
2723 * @param $subGroup Sub group
2724 * @return $isset Whether the given group is set
2726 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2728 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2731 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2738 * Getter for sub key group
2740 * @param $keyGroup Main key group
2741 * @param $subGroup Sub key group
2742 * @return $array An array with all array elements
2744 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2746 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2747 // No, then abort here
2748 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2753 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2756 return $this->genericArray[$keyGroup][$subGroup];
2760 * Unsets a given key in generic array
2762 * @param $keyGroup Main group for the key
2763 * @param $subGroup Sub group for the key
2764 * @param $key Key to unset
2767 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2769 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2772 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2776 * Unsets a given element in generic array
2778 * @param $keyGroup Main group for the key
2779 * @param $subGroup Sub group for the key
2780 * @param $key Key to unset
2781 * @param $element Element to unset
2784 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2786 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2789 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2793 * Append a string to a given generic array key
2795 * @param $keyGroup Main group for the key
2796 * @param $subGroup Sub group for the key
2797 * @param $key Key to unset
2798 * @param $value Value to add/append
2801 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2803 //* 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);
2805 // Is it already there?
2806 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2808 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2811 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2816 * Append a string to a given generic array element
2818 * @param $keyGroup Main group for the key
2819 * @param $subGroup Sub group for the key
2820 * @param $key Key to unset
2821 * @param $element Element to check
2822 * @param $value Value to add/append
2825 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2827 //* 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);
2829 // Is it already there?
2830 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2832 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2835 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2840 * Sets a string in a given generic array element
2842 * @param $keyGroup Main group for the key
2843 * @param $subGroup Sub group for the key
2844 * @param $key Key to unset
2845 * @param $element Element to check
2846 * @param $value Value to add/append
2849 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2851 //* 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);
2854 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2858 * Initializes given generic array group
2860 * @param $keyGroup Main group for the key
2861 * @param $subGroup Sub group for the key
2862 * @param $key Key to use
2863 * @param $forceInit Optionally force initialization
2866 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2868 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2870 // Is it already set?
2871 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2872 // Already initialized
2873 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2878 $this->genericArray[$keyGroup][$subGroup] = array();
2882 * Initializes given generic array key
2884 * @param $keyGroup Main group for the key
2885 * @param $subGroup Sub group for the key
2886 * @param $key Key to use
2887 * @param $forceInit Optionally force initialization
2890 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2892 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2894 // Is it already set?
2895 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2896 // Already initialized
2897 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2902 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2906 * Initializes given generic array element
2908 * @param $keyGroup Main group for the key
2909 * @param $subGroup Sub group for the key
2910 * @param $key Key to use
2911 * @param $element Element to use
2912 * @param $forceInit Optionally force initialization
2915 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2917 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2919 // Is it already set?
2920 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2921 // Already initialized
2922 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2927 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2931 * Pushes an element to a generic key
2933 * @param $keyGroup Main group for the key
2934 * @param $subGroup Sub group for the key
2935 * @param $key Key to use
2936 * @param $value Value to add/append
2937 * @return $count Number of array elements
2939 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2941 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2944 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2946 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2950 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2953 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2954 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2959 * Pushes an element to a generic array element
2961 * @param $keyGroup Main group for the key
2962 * @param $subGroup Sub group for the key
2963 * @param $key Key to use
2964 * @param $element Element to check
2965 * @param $value Value to add/append
2966 * @return $count Number of array elements
2968 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2970 //* 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));
2973 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2975 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2979 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2982 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2983 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2988 * Pops an element from a generic group
2990 * @param $keyGroup Main group for the key
2991 * @param $subGroup Sub group for the key
2992 * @param $key Key to unset
2993 * @return $value Last "popped" value
2995 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2997 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3000 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3002 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3007 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
3010 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3011 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3016 * Shifts an element from a generic group
3018 * @param $keyGroup Main group for the key
3019 * @param $subGroup Sub group for the key
3020 * @param $key Key to unset
3021 * @return $value Last "popped" value
3023 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3025 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3028 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3030 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3035 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3038 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3039 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3044 * Count generic array group
3046 * @param $keyGroup Main group for the key
3047 * @return $count Count of given group
3049 protected final function countGenericArray ($keyGroup) {
3051 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3054 if (!isset($this->genericArray[$keyGroup])) {
3056 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3061 $count = count($this->genericArray[$keyGroup]);
3064 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3071 * Count generic array sub group
3073 * @param $keyGroup Main group for the key
3074 * @param $subGroup Sub group for the key
3075 * @return $count Count of given group
3077 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3079 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3082 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3084 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3089 $count = count($this->genericArray[$keyGroup][$subGroup]);
3092 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3099 * Count generic array elements
3101 * @param $keyGroup Main group for the key
3102 * @param $subGroup Sub group for the key
3103 * @para $key Key to count
3104 * @return $count Count of given key
3106 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3108 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3111 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3113 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3115 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3117 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3122 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3125 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3132 * Getter for whole generic group array
3134 * @param $keyGroup Key group to get
3135 * @return $array Whole generic array group
3137 protected final function getGenericArray ($keyGroup) {
3139 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3142 if (!isset($this->genericArray[$keyGroup])) {
3144 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3149 return $this->genericArray[$keyGroup];
3153 * Setter for generic array key
3155 * @param $keyGroup Key group to get
3156 * @param $subGroup Sub group for the key
3157 * @param $key Key to unset
3158 * @param $value Mixed value from generic array element
3161 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3163 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3166 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3170 * Getter for generic array key
3172 * @param $keyGroup Key group to get
3173 * @param $subGroup Sub group for the key
3174 * @param $key Key to unset
3175 * @return $value Mixed value from generic array element
3177 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3179 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3182 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3184 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3189 return $this->genericArray[$keyGroup][$subGroup][$key];
3193 * Sets a value in given generic array key/element
3195 * @param $keyGroup Main group for the key
3196 * @param $subGroup Sub group for the key
3197 * @param $key Key to set
3198 * @param $element Element to set
3199 * @param $value Value to set
3202 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3204 //* 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));
3207 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3211 * Getter for generic array element
3213 * @param $keyGroup Key group to get
3214 * @param $subGroup Sub group for the key
3215 * @param $key Key to look for
3216 * @param $element Element to look for
3217 * @return $value Mixed value from generic array element
3219 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3221 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3224 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3226 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3231 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3235 * Checks if a given sub group is valid (array)
3237 * @param $keyGroup Key group to get
3238 * @param $subGroup Sub group for the key
3239 * @return $isValid Whether given sub group is valid
3241 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3243 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3246 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3253 * Checks if a given key is valid (array)
3255 * @param $keyGroup Key group to get
3256 * @param $subGroup Sub group for the key
3257 * @param $key Key to check
3258 * @return $isValid Whether given sub group is valid
3260 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3262 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3265 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3272 * Initializes the web output instance
3276 protected function initWebOutputInstance () {
3277 // Get application instance
3278 $applicationInstance = Registry::getRegistry()->getInstance('app');
3280 // Is this a response instance?
3281 if ($this instanceof Responseable) {
3282 // Then set it in application instance
3283 $applicationInstance->setResponseInstance($this);
3286 // Init web output instance
3287 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3290 $this->setWebOutputInstance($outputInstance);
3294 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3296 * @param $boolean Boolean value
3297 * @return $translated Translated boolean value
3299 public static final function translateBooleanToYesNo ($boolean) {
3300 // Make sure it is really boolean
3301 assert(is_bool($boolean));
3304 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3306 // ... and return it
3311 * Encodes raw data (almost any type) by "serializing" it and then pack it
3312 * into a "binary format".
3314 * @param $rawData Raw data (almost any type)
3315 * @return $encoded Encoded data
3317 protected function encodeData ($rawData) {
3318 // Make sure no objects or resources pass through
3319 assert(!is_object($rawData));
3320 assert(!is_resource($rawData));
3322 // First "serialize" it (json_encode() is faster than serialize())
3323 $encoded = $this->packString(json_encode($rawData));
3330 * Pack a string into a "binary format". Please execuse me that this is
3331 * widely undocumented. :-(
3333 * @param $str Unpacked string
3334 * @return $packed Packed string
3335 * @todo Improve documentation
3337 protected function packString ($str) {
3339 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3341 // First compress the string (gzcompress is okay)
3342 $str = gzcompress($str);
3347 // And start the "encoding" loop
3348 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3350 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3351 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3353 if (($idx + $i) <= strlen($str)) {
3354 $ord = ord(substr($str, ($idx + $i), 1));
3356 $add = $ord * pow(256, $factor);
3360 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3364 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3365 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3367 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3368 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3374 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3379 * Checks whether the given file/path is in open_basedir(). This does not
3380 * gurantee that the file is actually readable and/or writeable. If you need
3381 * such gurantee then please use isReadableFile() instead.
3383 * @param $filePathName Name of the file/path to be checked
3384 * @return $isReachable Whether it is within open_basedir()
3386 protected static function isReachableFilePath ($filePathName) {
3387 // Is not reachable by default
3388 $isReachable = FALSE;
3390 // Get open_basedir parameter
3391 $openBaseDir = ini_get('open_basedir');
3394 if (!empty($openBaseDir)) {
3395 // Check all entries
3396 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3397 // Check on existence
3398 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3400 $isReachable = TRUE;
3404 // If open_basedir is not set, all is allowed
3405 $isReachable = TRUE;
3409 return $isReachable;
3413 * Checks whether the give file is within open_basedir() (done by
3414 * isReachableFilePath()), is actually a file and is readable.
3416 * @param $fileName Name of the file to be checked
3417 * @return $isReadable Whether the file is readable (and therefor exists)
3419 public static function isReadableFile ($fileName) {
3420 // Default is not readable
3421 $isReadable = FALSE;
3423 // Is within parameters, so check if it is a file and readable
3424 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3431 * Creates a full-qualified file name (FQFN) for given file name by adding
3432 * a configured temporary file path to it.
3434 * @param $fileName Name for temporary file
3435 * @return $fqfn Full-qualified file name
3436 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3437 * @throws FileIoException If the file cannot be written
3439 protected static function createTempPathForFile ($fileName) {
3441 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3443 // Is the path writeable?
3444 if (!is_writable($basePath)) {
3445 // Path is write-protected
3446 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3450 $fqfn = $basePath . '/' . $fileName;
3453 if (!self::isReachableFilePath($fqfn)) {
3455 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3463 * "Getter" for a printable state name
3465 * @return $stateName Name of the node's state in a printable format
3467 public final function getPrintableState () {
3468 // Default is 'null'
3469 $stateName = 'null';
3471 // Get the state instance
3472 $stateInstance = $this->getStateInstance();
3474 // Is it an instance of Stateable?
3475 if ($stateInstance instanceof Stateable) {
3476 // Then use that state name
3477 $stateName = $stateInstance->getStateName();
3485 * Handles socket error for given socket resource and peer data. This method
3486 * validates $socketResource if it is a valid resource (see is_resource())
3487 * but assumes valid data in array $recipientData, except that
3488 * count($recipientData) is always 2.
3490 * @param $method Value of __METHOD__ from calling method
3491 * @param $line Value of __LINE__ from calling method
3492 * @param $socketResource A valid socket resource
3493 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3495 * @throws InvalidSocketException If $socketResource is no socket resource
3496 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3497 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3499 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3500 // This method handles only socket resources
3501 if (!is_resource($socketResource)) {
3502 // No resource, abort here
3503 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3506 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3507 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3508 assert(isset($socketData[0]));
3509 assert(isset($socketData[1]));
3511 // Get error code for first validation (0 is not an error)
3512 $errorCode = socket_last_error($socketResource);
3514 // If the error code is zero, someone called this method without an error
3515 if ($errorCode == 0) {
3516 // No error detected (or previously cleared outside this method)
3517 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3520 // Get handler (method) name
3521 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3523 // Call-back the error handler method
3524 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3526 // Finally clear the error because it has been handled
3527 socket_clear_error($socketResource);