3 * The simulator system class is the super class of all other classes. This
4 * class handles saving of games etc.
6 * @author Roland Haeder <webmaster@shipsimu.org>
8 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2013 Core Developer Team
9 * @license GNU GPL 3.0 or any newer version
10 * @link http://www.shipsimu.org
12 * This program is free software: you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation, either version 3 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
29 private $realClass = 'BaseFrameworkSystem';
32 * Instance of a request class
34 private $requestInstance = NULL;
37 * Instance of a response class
39 private $responseInstance = NULL;
42 * Search criteria instance
44 private $searchInstance = NULL;
47 * Update criteria instance
49 private $updateInstance = NULL;
52 * The file I/O instance for the template loader
54 private $fileIoInstance = NULL;
59 private $resolverInstance = NULL;
62 * Template engine instance
64 private $templateInstance = NULL;
67 * Database result instance
69 private $resultInstance = NULL;
72 * Instance for user class
74 private $userInstance = NULL;
77 * A controller instance
79 private $controllerInstance = NULL;
84 private $rngInstance = NULL;
87 * Instance of a crypto helper
89 private $cryptoInstance = NULL;
92 * Instance of an Iterator class
94 private $iteratorInstance = NULL;
97 * Instance of the list
99 private $listInstance = NULL;
104 private $menuInstance = NULL;
107 * Instance of the image
109 private $imageInstance = NULL;
112 * Instance of the stacker
114 private $stackerInstance = NULL;
117 * A Compressor instance
119 private $compressorInstance = NULL;
122 * A Parseable instance
124 private $parserInstance = NULL;
127 * A ProtocolHandler instance
129 private $protocolInstance = NULL;
132 * A database wrapper instance
134 private $databaseInstance = NULL;
137 * A helper instance for the form
139 private $helperInstance = NULL;
142 * An instance of a Sourceable class
144 private $sourceInstance = NULL;
147 * An instance of a InputStreamable class
149 private $inputStreamInstance = NULL;
152 * An instance of a OutputStreamable class
154 private $outputStreamInstance = NULL;
157 * Networkable handler instance
159 private $handlerInstance = NULL;
162 * Visitor handler instance
164 private $visitorInstance = NULL;
169 private $dhtInstance = NULL;
172 * An instance of a database wrapper class
174 private $wrapperInstance = NULL;
177 * An instance of a file I/O pointer class (not handler)
179 private $pointerInstance = NULL;
182 * Thousands separator
184 private $thousands = '.'; // German
189 private $decimals = ','; // German
194 private $socketResource = FALSE;
199 private $packageData = array();
204 private $genericArray = array();
206 /***********************
207 * Exception codes.... *
208 ***********************/
210 // @todo Try to clean these constants up
211 const EXCEPTION_IS_NULL_POINTER = 0x001;
212 const EXCEPTION_IS_NO_OBJECT = 0x002;
213 const EXCEPTION_IS_NO_ARRAY = 0x003;
214 const EXCEPTION_MISSING_METHOD = 0x004;
215 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
216 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
217 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
218 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
219 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
220 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
221 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
222 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
223 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
224 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
225 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
226 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
227 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
228 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
229 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
230 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
231 const EXCEPTION_PATH_NOT_FOUND = 0x015;
232 const EXCEPTION_INVALID_PATH_NAME = 0x016;
233 const EXCEPTION_READ_PROTECED_PATH = 0x017;
234 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
235 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
236 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
237 const EXCEPTION_INVALID_RESOURCE = 0x01b;
238 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
239 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
240 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
241 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
242 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
243 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
244 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
245 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
246 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
247 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
248 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
249 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
250 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
251 const EXCEPTION_INVALID_STRING = 0x029;
252 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
253 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
254 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
255 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
256 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
257 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
258 const EXCEPTION_MISSING_ELEMENT = 0x030;
259 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
260 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
261 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
262 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
263 const EXCEPTION_FATAL_ERROR = 0x035;
264 const EXCEPTION_FILE_NOT_FOUND = 0x036;
265 const EXCEPTION_ASSERTION_FAILED = 0x037;
266 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
267 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
268 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03a;
271 * Hexadecimal->Decimal translation array
273 private static $hexdec = array(
293 * Decimal->hexadecimal translation array
295 private static $dechex = array(
315 * Startup time in miliseconds
317 private static $startupTime = 0;
320 * Protected super constructor
322 * @param $className Name of the class
325 protected function __construct ($className) {
327 $this->setRealClass($className);
329 // Set configuration instance if no registry ...
330 if (!$this instanceof Register) {
331 // ... because registries doesn't need to be configured
332 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
335 // Is the startup time set? (0 cannot be TRUE anymore)
336 if (self::$startupTime == 0) {
338 self::$startupTime = microtime(TRUE);
343 * Destructor for all classes
347 public function __destruct () {
348 // Flush any updated entries to the database
349 $this->flushPendingUpdates();
351 // Is this object already destroyed?
352 if ($this->__toString() != 'DestructedObject') {
353 // Destroy all informations about this class but keep some text about it alive
354 $this->setRealClass('DestructedObject');
355 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
356 // Already destructed object
357 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
362 // Do not call this twice
363 trigger_error(__METHOD__ . ': Called twice.');
369 * The __call() method where all non-implemented methods end up
371 * @param $methodName Name of the missing method
372 * @args $args Arguments passed to the method
375 public final function __call ($methodName, $args) {
376 return self::__callStatic($methodName, $args);
380 * The __callStatic() method where all non-implemented static methods end up
382 * @param $methodName Name of the missing method
383 * @args $args Arguments passed to the method
386 public static final function __callStatic ($methodName, $args) {
387 // Init argument string
390 // Is it empty or an array?
393 $argsString = 'NULL';
394 } elseif (is_array($args)) {
395 // Some arguments are there
396 foreach ($args as $arg) {
397 // Add the value itself if not array. This prevents 'array to string conversion' message
398 if (is_array($arg)) {
399 $argsString .= 'Array';
404 // Add data about the argument
405 $argsString .= ' (' . gettype($arg);
407 if (is_string($arg)) {
408 // Add length for strings
409 $argsString .= ', ' . strlen($arg);
410 } elseif (is_array($arg)) {
411 // .. or size if array
412 $argsString .= ', ' . count($arg);
413 } elseif ($arg === TRUE) {
414 // ... is boolean 'TRUE'
415 $argsString .= ', TRUE';
416 } elseif ($arg === FALSE) {
417 // ... is boolean 'FALSE'
418 $argsString .= ', FALSE';
422 $argsString .= '), ';
426 if (substr($argsString, -2, 1) == ',') {
427 $argsString = substr($argsString, 0, -2);
430 // Invalid arguments!
431 $argsString = '!INVALID:' . gettype($args) . '!';
434 // Output stub message
435 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
436 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
446 * Getter for $realClass
448 * @return $realClass The name of the real class (not BaseFrameworkSystem)
450 public function __toString () {
451 return $this->realClass;
455 * Magic function to catch setting of missing but set class fields/attributes
457 * @param $name Name of the field/attribute
458 * @param $value Value to store
461 public final function __set ($name, $value) {
462 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
470 * Magic function to catch getting of missing fields/attributes
472 * @param $name Name of the field/attribute
475 public final function __get ($name) {
476 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
482 * Magic function to catch unsetting of missing fields/attributes
484 * @param $name Name of the field/attribute
487 public final function __unset ($name) {
488 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
494 * Setter for the real class name
496 * @param $realClass Class name (string)
499 public final function setRealClass ($realClass) {
501 $this->realClass = (string) $realClass;
505 * Setter for database result instance
507 * @param $resultInstance An instance of a database result class
509 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
511 protected final function setResultInstance (SearchableResult $resultInstance) {
512 $this->resultInstance = $resultInstance;
516 * Getter for database result instance
518 * @return $resultInstance An instance of a database result class
520 public final function getResultInstance () {
521 return $this->resultInstance;
525 * Setter for template engine instances
527 * @param $templateInstance An instance of a template engine class
530 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
531 $this->templateInstance = $templateInstance;
535 * Getter for template engine instances
537 * @return $templateInstance An instance of a template engine class
539 protected final function getTemplateInstance () {
540 return $this->templateInstance;
544 * Setter for search instance
546 * @param $searchInstance Searchable criteria instance
549 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
550 $this->searchInstance = $searchInstance;
554 * Getter for search instance
556 * @return $searchInstance Searchable criteria instance
558 public final function getSearchInstance () {
559 return $this->searchInstance;
563 * Setter for update instance
565 * @param $updateInstance Searchable criteria instance
568 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
569 $this->updateInstance = $updateInstance;
573 * Getter for update instance
575 * @return $updateInstance Updateable criteria instance
577 public final function getUpdateInstance () {
578 return $this->updateInstance;
582 * Setter for resolver instance
584 * @param $resolverInstance Instance of a command resolver class
587 public final function setResolverInstance (Resolver $resolverInstance) {
588 $this->resolverInstance = $resolverInstance;
592 * Getter for resolver instance
594 * @return $resolverInstance Instance of a command resolver class
596 public final function getResolverInstance () {
597 return $this->resolverInstance;
601 * Setter for language instance
603 * @param $configInstance The configuration instance which shall
604 * be FrameworkConfiguration
607 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
608 Registry::getRegistry()->addInstance('config', $configInstance);
612 * Getter for configuration instance
614 * @return $configInstance Configuration instance
616 public final function getConfigInstance () {
617 $configInstance = Registry::getRegistry()->getInstance('config');
618 return $configInstance;
622 * Setter for debug instance
624 * @param $debugInstance The instance for debug output class
627 public final function setDebugInstance (DebugMiddleware $debugInstance) {
628 Registry::getRegistry()->addInstance('debug', $debugInstance);
632 * Getter for debug instance
634 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
636 public final function getDebugInstance () {
637 // Get debug instance
638 $debugInstance = Registry::getRegistry()->getInstance('debug');
641 return $debugInstance;
645 * Setter for web output instance
647 * @param $webInstance The instance for web output class
650 public final function setWebOutputInstance (OutputStreamer $webInstance) {
651 Registry::getRegistry()->addInstance('web_output', $webInstance);
655 * Getter for web output instance
657 * @return $webOutputInstance - Instance to class WebOutput
659 public final function getWebOutputInstance () {
660 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
661 return $webOutputInstance;
665 * Setter for database instance
667 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
670 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
671 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
675 * Getter for database layer
677 * @return $databaseInstance The database layer instance
679 public final function getDatabaseInstance () {
681 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
684 return $databaseInstance;
688 * Setter for compressor channel
690 * @param $compressorInstance An instance of CompressorChannel
693 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
694 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
698 * Getter for compressor channel
700 * @return $compressorInstance The compressor channel
702 public final function getCompressorChannel () {
703 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
704 return $compressorInstance;
708 * Protected getter for a manageable application helper class
710 * @return $applicationInstance An instance of a manageable application helper class
712 protected final function getApplicationInstance () {
713 $applicationInstance = Registry::getRegistry()->getInstance('application');
714 return $applicationInstance;
718 * Setter for a manageable application helper class
720 * @param $applicationInstance An instance of a manageable application helper class
723 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
724 Registry::getRegistry()->addInstance('application', $applicationInstance);
728 * Setter for request instance
730 * @param $requestInstance An instance of a Requestable class
733 public final function setRequestInstance (Requestable $requestInstance) {
734 $this->requestInstance = $requestInstance;
738 * Getter for request instance
740 * @return $requestInstance An instance of a Requestable class
742 public final function getRequestInstance () {
743 return $this->requestInstance;
747 * Setter for response instance
749 * @param $responseInstance An instance of a Responseable class
752 public final function setResponseInstance (Responseable $responseInstance) {
753 $this->responseInstance = $responseInstance;
757 * Getter for response instance
759 * @return $responseInstance An instance of a Responseable class
761 public final function getResponseInstance () {
762 return $this->responseInstance;
766 * Private getter for language instance
768 * @return $langInstance An instance to the language sub-system
770 protected final function getLanguageInstance () {
771 $langInstance = Registry::getRegistry()->getInstance('language');
772 return $langInstance;
776 * Setter for language instance
778 * @param $langInstance An instance to the language sub-system
780 * @see LanguageSystem
782 public final function setLanguageInstance (ManageableLanguage $langInstance) {
783 Registry::getRegistry()->addInstance('language', $langInstance);
787 * Private getter for file IO instance
789 * @return $fileIoInstance An instance to the file I/O sub-system
791 protected final function getFileIoInstance () {
792 return $this->fileIoInstance;
796 * Setter for file I/O instance
798 * @param $fileIoInstance An instance to the file I/O sub-system
801 public final function setFileIoInstance (IoHandler $fileIoInstance) {
802 $this->fileIoInstance = $fileIoInstance;
806 * Protected setter for user instance
808 * @param $userInstance An instance of a user class
811 protected final function setUserInstance (ManageableAccount $userInstance) {
812 $this->userInstance = $userInstance;
816 * Getter for user instance
818 * @return $userInstance An instance of a user class
820 public final function getUserInstance () {
821 return $this->userInstance;
825 * Setter for controller instance (this surely breaks a bit the MVC patterm)
827 * @param $controllerInstance An instance of the controller
830 public final function setControllerInstance (Controller $controllerInstance) {
831 $this->controllerInstance = $controllerInstance;
835 * Getter for controller instance (this surely breaks a bit the MVC patterm)
837 * @return $controllerInstance An instance of the controller
839 public final function getControllerInstance () {
840 return $this->controllerInstance;
844 * Setter for RNG instance
846 * @param $rngInstance An instance of a random number generator (RNG)
849 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
850 $this->rngInstance = $rngInstance;
854 * Getter for RNG instance
856 * @return $rngInstance An instance of a random number generator (RNG)
858 public final function getRngInstance () {
859 return $this->rngInstance;
863 * Setter for Cryptable instance
865 * @param $cryptoInstance An instance of a Cryptable class
868 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
869 $this->cryptoInstance = $cryptoInstance;
873 * Getter for Cryptable instance
875 * @return $cryptoInstance An instance of a Cryptable class
877 public final function getCryptoInstance () {
878 return $this->cryptoInstance;
882 * Setter for the list instance
884 * @param $listInstance A list of Listable
887 protected final function setListInstance (Listable $listInstance) {
888 $this->listInstance = $listInstance;
892 * Getter for the list instance
894 * @return $listInstance A list of Listable
896 protected final function getListInstance () {
897 return $this->listInstance;
901 * Setter for the menu instance
903 * @param $menuInstance A RenderableMenu instance
906 protected final function setMenuInstance (RenderableMenu $menuInstance) {
907 $this->menuInstance = $menuInstance;
911 * Getter for the menu instance
913 * @return $menuInstance A RenderableMenu instance
915 protected final function getMenuInstance () {
916 return $this->menuInstance;
920 * Setter for image instance
922 * @param $imageInstance An instance of an image
925 public final function setImageInstance (BaseImage $imageInstance) {
926 $this->imageInstance = $imageInstance;
930 * Getter for image instance
932 * @return $imageInstance An instance of an image
934 public final function getImageInstance () {
935 return $this->imageInstance;
939 * Setter for stacker instance
941 * @param $stackerInstance An instance of an stacker
944 public final function setStackerInstance (Stackable $stackerInstance) {
945 $this->stackerInstance = $stackerInstance;
949 * Getter for stacker instance
951 * @return $stackerInstance An instance of an stacker
953 public final function getStackerInstance () {
954 return $this->stackerInstance;
958 * Setter for compressor instance
960 * @param $compressorInstance An instance of an compressor
963 public final function setCompressorInstance (Compressor $compressorInstance) {
964 $this->compressorInstance = $compressorInstance;
968 * Getter for compressor instance
970 * @return $compressorInstance An instance of an compressor
972 public final function getCompressorInstance () {
973 return $this->compressorInstance;
977 * Setter for Parseable instance
979 * @param $parserInstance An instance of an Parseable
982 public final function setParserInstance (Parseable $parserInstance) {
983 $this->parserInstance = $parserInstance;
987 * Getter for Parseable instance
989 * @return $parserInstance An instance of an Parseable
991 public final function getParserInstance () {
992 return $this->parserInstance;
996 * Setter for ProtocolHandler instance
998 * @param $protocolInstance An instance of an ProtocolHandler
1001 public final function setProtocolInstance (ProtocolHandler $protocolInstance = NULL) {
1002 $this->protocolInstance = $protocolInstance;
1006 * Getter for ProtocolHandler instance
1008 * @return $protocolInstance An instance of an ProtocolHandler
1010 public final function getProtocolInstance () {
1011 return $this->protocolInstance;
1015 * Setter for DatabaseWrapper instance
1017 * @param $wrapperInstance An instance of an DatabaseWrapper
1020 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1021 $this->wrapperInstance = $wrapperInstance;
1025 * Getter for DatabaseWrapper instance
1027 * @return $wrapperInstance An instance of an DatabaseWrapper
1029 public final function getWrapperInstance () {
1030 return $this->wrapperInstance;
1034 * Setter for socket resource
1036 * @param $socketResource A valid socket resource
1039 public final function setSocketResource ($socketResource) {
1040 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1041 $this->socketResource = $socketResource;
1045 * Getter for socket resource
1047 * @return $socketResource A valid socket resource
1049 public final function getSocketResource () {
1050 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1051 return $this->socketResource;
1055 * Setter for helper instance
1057 * @param $helperInstance An instance of a helper class
1060 protected final function setHelperInstance (Helper $helperInstance) {
1061 $this->helperInstance = $helperInstance;
1065 * Getter for helper instance
1067 * @return $helperInstance An instance of a helper class
1069 public final function getHelperInstance () {
1070 return $this->helperInstance;
1074 * Setter for a Sourceable instance
1076 * @param $sourceInstance The Sourceable instance
1079 protected final function setSourceInstance (Sourceable $sourceInstance) {
1080 $this->sourceInstance = $sourceInstance;
1084 * Getter for a Sourceable instance
1086 * @return $sourceInstance The Sourceable instance
1088 protected final function getSourceInstance () {
1089 return $this->sourceInstance;
1093 * Getter for a InputStreamable instance
1095 * @param $inputStreamInstance The InputStreamable instance
1097 protected final function getInputStreamInstance () {
1098 return $this->inputStreamInstance;
1102 * Setter for a InputStreamable instance
1104 * @param $inputStreamInstance The InputStreamable instance
1107 protected final function setInputStreamInstance (InputStreamable $inputStreamInstance) {
1108 $this->inputStreamInstance = $inputStreamInstance;
1112 * Getter for a OutputStreamable instance
1114 * @param $outputStreamInstance The OutputStreamable instance
1116 protected final function getOutputStreamInstance () {
1117 return $this->outputStreamInstance;
1121 * Setter for a OutputStreamable instance
1123 * @param $outputStreamInstance The OutputStreamable instance
1126 protected final function setOutputStreamInstance (OutputStreamable $outputStreamInstance) {
1127 $this->outputStreamInstance = $outputStreamInstance;
1131 * Setter for handler instance
1133 * @param $handlerInstance An instance of a Handleable class
1136 protected final function setHandlerInstance (Handleable $handlerInstance) {
1137 $this->handlerInstance = $handlerInstance;
1141 * Getter for handler instance
1143 * @return $handlerInstance A Networkable instance
1145 protected final function getHandlerInstance () {
1146 return $this->handlerInstance;
1150 * Setter for visitor instance
1152 * @param $visitorInstance A Visitor instance
1155 protected final function setVisitorInstance (Visitor $visitorInstance) {
1156 $this->visitorInstance = $visitorInstance;
1160 * Getter for visitor instance
1162 * @return $visitorInstance A Visitor instance
1164 protected final function getVisitorInstance () {
1165 return $this->visitorInstance;
1169 * Setter for DHT instance
1171 * @param $dhtInstance A Distributable instance
1174 protected final function setDhtInstance (Distributable $dhtInstance) {
1175 $this->dhtInstance = $dhtInstance;
1179 * Getter for DHT instance
1181 * @return $dhtInstance A Distributable instance
1183 protected final function getDhtInstance () {
1184 return $this->dhtInstance;
1188 * Setter for raw package Data
1190 * @param $packageData Raw package Data
1193 public final function setPackageData (array $packageData) {
1194 $this->packageData = $packageData;
1198 * Getter for raw package Data
1200 * @return $packageData Raw package Data
1202 public function getPackageData () {
1203 return $this->packageData;
1208 * Setter for Iterator instance
1210 * @param $iteratorInstance An instance of an Iterator
1213 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1214 $this->iteratorInstance = $iteratorInstance;
1218 * Getter for Iterator instance
1220 * @return $iteratorInstance An instance of an Iterator
1222 public final function getIteratorInstance () {
1223 return $this->iteratorInstance;
1227 * Setter for InputOutputPointer instance
1229 * @param $pointerInstance An instance of an InputOutputPointer
1232 protected final function setPointerInstance (InputOutputPointer $pointerInstance) {
1233 $this->pointerInstance = $pointerInstance;
1237 * Getter for InputOutputPointer instance
1239 * @return $pointerInstance An instance of an InputOutputPointer
1241 public final function getPointerInstance () {
1242 return $this->pointerInstance;
1246 * Checks whether an object equals this object. You should overwrite this
1247 * method to implement own equality checks
1249 * @param $objectInstance An instance of a FrameworkInterface object
1250 * @return $equals Whether both objects equals
1252 public function equals (FrameworkInterface $objectInstance) {
1255 $this->__toString() == $objectInstance->__toString()
1257 $this->hashCode() == $objectInstance->hashCode()
1260 // Return the result
1265 * Generates a generic hash code of this class. You should really overwrite
1266 * this method with your own hash code generator code. But keep KISS in mind.
1268 * @return $hashCode A generic hash code respresenting this whole class
1270 public function hashCode () {
1272 return crc32($this->__toString());
1276 * Formats computer generated price values into human-understandable formats
1277 * with thousand and decimal separators.
1279 * @param $value The in computer format value for a price
1280 * @param $currency The currency symbol (use HTML-valid characters!)
1281 * @param $decNum Number of decimals after commata
1282 * @return $price The for the current language formated price string
1283 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1284 * thousands separator
1287 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1288 // Are all required attriutes set?
1289 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1290 // Throw an exception
1291 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1295 $value = (float) $value;
1297 // Reformat the US number
1298 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1300 // Return as string...
1305 * Appends a trailing slash to a string
1307 * @param $str A string (maybe) without trailing slash
1308 * @return $str A string with an auto-appended trailing slash
1310 public final function addMissingTrailingSlash ($str) {
1311 // Is there a trailing slash?
1312 if (substr($str, -1, 1) != '/') {
1316 // Return string with trailing slash
1321 * Prepare the template engine (WebTemplateEngine by default) for a given
1322 * application helper instance (ApplicationHelper by default).
1324 * @param $applicationInstance An application helper instance or
1325 * null if we shall use the default
1326 * @return $templateInstance The template engine instance
1327 * @throws NullPointerException If the discovered application
1328 * instance is still null
1330 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1331 // Is the application instance set?
1332 if (is_null($applicationInstance)) {
1333 // Get the current instance
1334 $applicationInstance = $this->getApplicationInstance();
1337 if (is_null($applicationInstance)) {
1338 // Thrown an exception
1339 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1343 // Initialize the template engine
1344 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
1346 // Return the prepared instance
1347 return $templateInstance;
1351 * Debugs this instance by putting out it's full content
1353 * @param $message Optional message to show in debug output
1356 public final function debugInstance ($message = '') {
1357 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1358 restore_error_handler();
1363 // Is a message set?
1364 if (!empty($message)) {
1365 // Construct message
1366 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1369 // Generate the output
1370 $content .= sprintf('<pre>%s</pre>',
1373 print_r($this, TRUE)
1379 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>',
1380 $this->__toString(),
1382 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1387 * Replaces control characters with printable output
1389 * @param $str String with control characters
1390 * @return $str Replaced string
1392 protected function replaceControlCharacters ($str) {
1395 chr(13), '[r]', str_replace(
1396 chr(10), '[n]', str_replace(
1406 * Output a partial stub message for the caller method
1408 * @param $message An optional message to display
1411 protected function partialStub ($message = '') {
1412 // Get the backtrace
1413 $backtrace = debug_backtrace();
1415 // Generate the class::method string
1416 $methodName = 'UnknownClass->unknownMethod';
1417 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1418 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1421 // Construct the full message
1422 $stubMessage = sprintf('[%s:] Partial stub!',
1426 // Is the extra message given?
1427 if (!empty($message)) {
1428 // Then add it as well
1429 $stubMessage .= ' Message: ' . $message;
1432 // Debug instance is there?
1433 if (!is_null($this->getDebugInstance())) {
1434 // Output stub message
1435 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1438 trigger_error($stubMessage);
1444 * Outputs a debug backtrace and stops further script execution
1446 * @param $message An optional message to output
1447 * @param $doExit Whether exit the program (TRUE is default)
1450 public function debugBackTrace ($message = '', $doExit = TRUE) {
1451 // Sorry, there is no other way getting this nice backtrace
1452 if (!empty($message)) {
1454 printf('Message: %s<br />' . chr(10), $message);
1458 debug_print_backtrace();
1462 if ($doExit === TRUE) {
1468 * Creates an instance of a debugger instance
1470 * @param $className Name of the class (currently unsupported)
1471 * @return $debugInstance An instance of a debugger class
1473 public final static function createDebugInstance ($className) {
1474 // Is the instance set?
1475 if (!Registry::getRegistry()->instanceExists('debug')) {
1476 // Init debug instance
1477 $debugInstance = NULL;
1481 // Get a debugger instance
1482 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_class'));
1483 } catch (NullPointerException $e) {
1484 // Didn't work, no instance there
1485 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1488 // Empty string should be ignored and used for testing the middleware
1489 DebugMiddleware::getSelfInstance()->output('');
1491 // Set it in its own class. This will set it in the registry
1492 $debugInstance->setDebugInstance($debugInstance);
1494 // Get instance from registry
1495 $debugInstance = Registry::getRegistry()->getDebugInstance();
1499 return $debugInstance;
1503 * Simple output of a message with line-break
1505 * @param $message Message to output
1508 public function outputLine ($message) {
1510 print($message . PHP_EOL);
1514 * Outputs a debug message whether to debug instance (should be set!) or
1515 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1516 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1518 * @param $message Message we shall send out...
1519 * @param $doPrint Whether print or die here (default: print)
1520 * @paran $stripTags Whether to strip tags (default: FALSE)
1523 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1524 // Set debug instance to NULL
1525 $debugInstance = NULL;
1529 // Get debug instance
1530 $debugInstance = $this->getDebugInstance();
1531 } catch (NullPointerException $e) {
1532 // The debug instance is not set (yet)
1535 // Is the debug instance there?
1536 if (is_object($debugInstance)) {
1537 // Use debug output handler
1538 $debugInstance->output($message, $stripTags);
1540 if ($doPrint === FALSE) {
1541 // Die here if not printed
1545 // Are debug times enabled?
1546 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1548 $message = $this->getPrintableExecutionTime() . $message;
1552 if ($doPrint === TRUE) {
1554 $this->outputLine($message);
1563 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1565 * @param $str The string, what ever it is needs to be converted
1566 * @return $className Generated class name
1568 public function convertToClassName ($str) {
1572 // Convert all dashes in underscores
1573 $str = $this->convertDashesToUnderscores($str);
1575 // Now use that underscores to get classname parts for hungarian style
1576 foreach (explode('_', $str) as $strPart) {
1577 // Make the class name part lower case and first upper case
1578 $className .= ucfirst(strtolower($strPart));
1581 // Return class name
1586 * Converts dashes to underscores, e.g. useable for configuration entries
1588 * @param $str The string with maybe dashes inside
1589 * @return $str The converted string with no dashed, but underscores
1591 public final function convertDashesToUnderscores ($str) {
1593 $str = str_replace('-', '_', $str);
1595 // Return converted string
1600 * Marks up the code by adding e.g. line numbers
1602 * @param $phpCode Unmarked PHP code
1603 * @return $markedCode Marked PHP code
1605 public function markupCode ($phpCode) {
1610 $errorArray = error_get_last();
1612 // Init the code with error message
1613 if (is_array($errorArray)) {
1615 $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>',
1616 basename($errorArray['file']),
1617 $errorArray['line'],
1618 $errorArray['message'],
1623 // Add line number to the code
1624 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1626 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1628 htmlentities($code, ENT_QUOTES)
1637 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1638 * beatiful for web-based front-ends. If null is given a message id
1639 * null_timestamp will be resolved and returned.
1641 * @param $timestamp Timestamp to prepare (filter) for display
1642 * @return $readable A readable timestamp
1644 public function doFilterFormatTimestamp ($timestamp) {
1645 // Default value to return
1648 // Is the timestamp null?
1649 if (is_null($timestamp)) {
1650 // Get a message string
1651 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1653 switch ($this->getLanguageInstance()->getLanguageCode()) {
1654 case 'de': // German format is a bit different to default
1655 // Split the GMT stamp up
1656 $dateTime = explode(' ', $timestamp );
1657 $dateArray = explode('-', $dateTime[0]);
1658 $timeArray = explode(':', $dateTime[1]);
1660 // Construct the timestamp
1661 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1671 default: // Default is pass-through
1672 $readable = $timestamp;
1682 * Filter a given number into a localized number
1684 * @param $value The raw value from e.g. database
1685 * @return $localized Localized value
1687 public function doFilterFormatNumber ($value) {
1688 // Generate it from config and localize dependencies
1689 switch ($this->getLanguageInstance()->getLanguageCode()) {
1690 case 'de': // German format is a bit different to default
1691 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1694 default: // US, etc.
1695 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1704 * "Getter" for databse entry
1706 * @return $entry An array with database entries
1707 * @throws NullPointerException If the database result is not found
1708 * @throws InvalidDatabaseResultException If the database result is invalid
1710 protected final function getDatabaseEntry () {
1711 // Is there an instance?
1712 if (is_null($this->getResultInstance())) {
1713 // Throw an exception here
1714 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1718 $this->getResultInstance()->rewind();
1720 // Do we have an entry?
1721 if ($this->getResultInstance()->valid() === FALSE) {
1722 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1726 $this->getResultInstance()->next();
1729 $entry = $this->getResultInstance()->current();
1736 * Getter for field name
1738 * @param $fieldName Field name which we shall get
1739 * @return $fieldValue Field value from the user
1740 * @throws NullPointerException If the result instance is null
1742 public final function getField ($fieldName) {
1743 // Default field value
1746 // Get result instance
1747 $resultInstance = $this->getResultInstance();
1749 // Is this instance null?
1750 if (is_null($resultInstance)) {
1751 // Then the user instance is no longer valid (expired cookies?)
1752 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1755 // Get current array
1756 $fieldArray = $resultInstance->current();
1757 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
1759 // Convert dashes to underscore
1760 $fieldName = $this->convertDashesToUnderscores($fieldName);
1762 // Does the field exist?
1763 if (isset($fieldArray[$fieldName])) {
1765 $fieldValue = $fieldArray[$fieldName];
1767 // Missing field entry, may require debugging
1768 self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ':fieldname=' . $fieldName . ' not found!');
1776 * Flushs all pending updates to the database layer
1780 public function flushPendingUpdates () {
1781 // Get result instance
1782 $resultInstance = $this->getResultInstance();
1784 // Do we have data to update?
1785 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1786 // Get wrapper class name config entry
1787 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1789 // Create object instance
1790 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1792 // Yes, then send the whole result to the database layer
1793 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1798 * Outputs a deprecation warning to the developer.
1800 * @param $message The message we shall output to the developer
1802 * @todo Write a logging mechanism for productive mode
1804 public function deprecationWarning ($message) {
1805 // Is developer mode active?
1806 if (defined('DEVELOPER')) {
1807 // Debug instance is there?
1808 if (!is_null($this->getDebugInstance())) {
1809 // Output stub message
1810 self::createDebugInstance(__CLASS__)->debugOutput($message);
1813 trigger_error($message . "<br />\n");
1817 // @TODO Finish this part!
1818 $this->partialStub('Developer mode inactive. Message:' . $message);
1823 * Checks whether the given PHP extension is loaded
1825 * @param $phpExtension The PHP extension we shall check
1826 * @return $isLoaded Whether the PHP extension is loaded
1828 public final function isPhpExtensionLoaded ($phpExtension) {
1830 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1837 * "Getter" as a time() replacement but with milliseconds. You should use this
1838 * method instead of the encapsulated getimeofday() function.
1840 * @return $milliTime Timestamp with milliseconds
1842 public function getMilliTime () {
1843 // Get the time of day as float
1844 $milliTime = gettimeofday(TRUE);
1851 * Idles (sleeps) for given milliseconds
1853 * @return $hasSlept Whether it goes fine
1855 public function idle ($milliSeconds) {
1856 // Sleep is fine by default
1859 // Idle so long with found function
1860 if (function_exists('time_sleep_until')) {
1861 // Get current time and add idle time
1862 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1864 // New PHP 5.1.0 function found, ignore errors
1865 $hasSlept = @time_sleep_until($sleepUntil);
1868 * My Sun station doesn't have that function even with latest PHP
1871 usleep($milliSeconds * 1000);
1878 * Converts a hexadecimal string, even with negative sign as first string to
1879 * a decimal number using BC functions.
1881 * This work is based on comment #86673 on php.net documentation page at:
1882 * <http://de.php.net/manual/en/function.dechex.php#86673>
1884 * @param $hex Hexadecimal string
1885 * @return $dec Decimal number
1887 protected function hex2dec ($hex) {
1888 // Convert to all lower-case
1889 $hex = strtolower($hex);
1891 // Detect sign (negative/positive numbers)
1893 if (substr($hex, 0, 1) == '-') {
1895 $hex = substr($hex, 1);
1898 // Decode the hexadecimal string into a decimal number
1900 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1901 $factor = self::$hexdec[substr($hex, $i, 1)];
1902 $dec = bcadd($dec, bcmul($factor, $e));
1905 // Return the decimal number
1906 return $sign . $dec;
1910 * Converts even very large decimal numbers, also signed, to a hexadecimal
1913 * This work is based on comment #97756 on php.net documentation page at:
1914 * <http://de.php.net/manual/en/function.hexdec.php#97756>
1916 * @param $dec Decimal number, even with negative sign
1917 * @param $maxLength Optional maximum length of the string
1918 * @return $hex Hexadecimal string
1920 protected function dec2hex ($dec, $maxLength = 0) {
1921 // maxLength can be zero or devideable by 2
1922 assert(($maxLength == 0) || (($maxLength % 2) == 0));
1924 // Detect sign (negative/positive numbers)
1931 // Encode the decimal number into a hexadecimal string
1934 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
1936 } while ($dec >= 1);
1939 * Leading zeros are required for hex-decimal "numbers". In some
1940 * situations more leading zeros are wanted, so check for both
1943 if ($maxLength > 0) {
1944 // Prepend more zeros
1945 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
1946 } elseif ((strlen($hex) % 2) != 0) {
1947 // Only make string's length dividable by 2
1951 // Return the hexadecimal string
1952 return $sign . $hex;
1956 * Converts a ASCII string (0 to 255) into a decimal number.
1958 * @param $asc The ASCII string to be converted
1959 * @return $dec Decimal number
1961 protected function asc2dec ($asc) {
1962 // Convert it into a hexadecimal number
1963 $hex = bin2hex($asc);
1965 // And back into a decimal number
1966 $dec = $this->hex2dec($hex);
1973 * Converts a decimal number into an ASCII string.
1975 * @param $dec Decimal number
1976 * @return $asc An ASCII string
1978 protected function dec2asc ($dec) {
1979 // First convert the number into a hexadecimal string
1980 $hex = $this->dec2hex($dec);
1982 // Then convert it into the ASCII string
1983 $asc = $this->hex2asc($hex);
1990 * Converts a hexadecimal number into an ASCII string. Negative numbers
1993 * @param $hex Hexadecimal string
1994 * @return $asc An ASCII string
1996 protected function hex2asc ($hex) {
1997 // Check for length, it must be devideable by 2
1998 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
1999 assert((strlen($hex) % 2) == 0);
2003 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2004 // Get the decimal number of the chunk
2005 $part = hexdec(substr($hex, $idx, 2));
2007 // Add it to the final string
2011 // Return the final string
2016 * Checks whether the given encoded data was encoded with Base64
2018 * @param $encodedData Encoded data we shall check
2019 * @return $isBase64 Whether the encoded data is Base64
2021 protected function isBase64Encoded ($encodedData) {
2023 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2030 * "Getter" to get response/request type from analysis of the system.
2032 * @return $responseType Analyzed response type
2034 protected function getResponseTypeFromSystem () {
2035 // Default is console
2036 $responseType = 'console';
2038 // Is 'HTTP_HOST' set?
2039 if (isset($_SERVER['HTTP_HOST'])) {
2040 // Then it is a HTTP response/request
2041 $responseType = 'http';
2045 return $responseType;
2049 * Gets a cache key from Criteria instance
2051 * @param $criteriaInstance An instance of a Criteria class
2052 * @param $onlyKeys Only use these keys for a cache key
2053 * @return $cacheKey A cache key suitable for lookup/storage purposes
2055 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2057 $cacheKey = sprintf('%s@%s',
2058 $this->__toString(),
2059 $criteriaInstance->getCacheKey($onlyKeys)
2063 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2068 * Getter for startup time in miliseconds
2070 * @return $startupTime Startup time in miliseconds
2072 protected function getStartupTime () {
2073 return self::$startupTime;
2077 * "Getter" for a printable currently execution time in nice braces
2079 * @return $executionTime Current execution time in nice braces
2081 protected function getPrintableExecutionTime () {
2082 // Caculate the execution time
2083 $executionTime = microtime(TRUE) - $this->getStartupTime();
2085 // Pack it in nice braces
2086 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2089 return $executionTime;
2093 * Hashes a given string with a simple but stronger hash function (no salts)
2095 * @param $str The string to be hashed
2096 * @return $hash The hash from string $str
2098 public function hashString ($str) {
2099 // Hash given string with (better secure) hasher
2100 $hash = mhash(MHASH_SHA256, $str);
2107 * Checks whether the given number is really a number (only chars 0-9).
2109 * @param $num A string consisting only chars between 0 and 9
2110 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2111 * @param $assertMismatch Whether to assert mismatches
2112 * @return $ret The (hopefully) secured numbered value
2114 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2115 // Filter all numbers out
2116 $ret = preg_replace('/[^0123456789]/', '', $num);
2119 if ($castValue === TRUE) {
2120 // Cast to biggest numeric type
2121 $ret = (double) $ret;
2124 // Assert only if requested
2125 if ($assertMismatch === TRUE) {
2126 // Has the whole value changed?
2127 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2135 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2137 * @param $num A string consisting only chars between 0 and 9
2138 * @param $assertMismatch Whether to assert mismatches
2139 * @return $ret The (hopefully) secured hext-numbered value
2141 public function hexval ($num, $assertMismatch = FALSE) {
2142 // Filter all numbers out
2143 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2145 // Assert only if requested
2146 if ($assertMismatch === TRUE) {
2147 // Has the whole value changed?
2148 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2156 * Checks whether start/end marker are set
2158 * @param $data Data to be checked
2159 * @return $isset Whether start/end marker are set
2161 public final function ifStartEndMarkersSet ($data) {
2163 $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));
2165 // ... and return it
2170 * Determines if an element is set in the generic array
2172 * @param $keyGroup Main group for the key
2173 * @param $subGroup Sub group for the key
2174 * @param $key Key to check
2175 * @param $element Element to check
2176 * @return $isset Whether the given key is set
2178 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2180 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2183 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2189 * Determines if a key is set in the generic array
2191 * @param $keyGroup Main group for the key
2192 * @param $subGroup Sub group for the key
2193 * @param $key Key to check
2194 * @return $isset Whether the given key is set
2196 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2198 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2201 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2209 * Determines if a group is set in the generic array
2211 * @param $keyGroup Main group
2212 * @param $subGroup Sub group
2213 * @return $isset Whether the given group is set
2215 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2217 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2220 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2227 * Getter for sub key group
2229 * @param $keyGroup Main key group
2230 * @param $subGroup Sub key group
2231 * @return $array An array with all array elements
2233 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2235 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2236 // No, then abort here
2237 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2242 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2245 return $this->genericArray[$keyGroup][$subGroup];
2249 * Unsets a given key in generic array
2251 * @param $keyGroup Main group for the key
2252 * @param $subGroup Sub group for the key
2253 * @param $key Key to unset
2256 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2258 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2261 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2265 * Unsets a given element in generic array
2267 * @param $keyGroup Main group for the key
2268 * @param $subGroup Sub group for the key
2269 * @param $key Key to unset
2270 * @param $element Element to unset
2273 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2275 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2278 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2282 * Append a string to a given generic array key
2284 * @param $keyGroup Main group for the key
2285 * @param $subGroup Sub group for the key
2286 * @param $key Key to unset
2287 * @param $value Value to add/append
2290 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2292 //* 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);
2294 // Is it already there?
2295 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2297 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2300 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2305 * Append a string to a given generic array element
2307 * @param $keyGroup Main group for the key
2308 * @param $subGroup Sub group for the key
2309 * @param $key Key to unset
2310 * @param $element Element to check
2311 * @param $value Value to add/append
2314 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2316 //* 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);
2318 // Is it already there?
2319 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2321 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2324 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2329 * Initializes given generic array group
2331 * @param $keyGroup Main group for the key
2332 * @param $subGroup Sub group for the key
2333 * @param $key Key to use
2334 * @param $forceInit Optionally force initialization
2337 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2339 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2341 // Is it already set?
2342 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2343 // Already initialized
2344 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2349 $this->genericArray[$keyGroup][$subGroup] = array();
2353 * Initializes given generic array key
2355 * @param $keyGroup Main group for the key
2356 * @param $subGroup Sub group for the key
2357 * @param $key Key to use
2358 * @param $forceInit Optionally force initialization
2361 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2363 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2365 // Is it already set?
2366 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2367 // Already initialized
2368 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2373 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2377 * Initializes given generic array element
2379 * @param $keyGroup Main group for the key
2380 * @param $subGroup Sub group for the key
2381 * @param $key Key to use
2382 * @param $element Element to use
2383 * @param $forceInit Optionally force initialization
2386 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2388 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2390 // Is it already set?
2391 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2392 // Already initialized
2393 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2398 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2402 * Pushes an element to a generic key
2404 * @param $keyGroup Main group for the key
2405 * @param $subGroup Sub group for the key
2406 * @param $key Key to use
2407 * @param $value Value to add/append
2408 * @return $count Number of array elements
2410 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2412 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2415 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2417 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2421 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2424 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2425 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2430 * Pushes an element to a generic array element
2432 * @param $keyGroup Main group for the key
2433 * @param $subGroup Sub group for the key
2434 * @param $key Key to use
2435 * @param $element Element to check
2436 * @param $value Value to add/append
2437 * @return $count Number of array elements
2439 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2441 //* 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));
2444 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2446 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2450 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2453 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2454 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2459 * Pops an element from a generic group
2461 * @param $keyGroup Main group for the key
2462 * @param $subGroup Sub group for the key
2463 * @param $key Key to unset
2464 * @return $value Last "popped" value
2466 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2468 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2471 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2473 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2478 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2481 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2482 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2487 * Shifts an element from a generic group
2489 * @param $keyGroup Main group for the key
2490 * @param $subGroup Sub group for the key
2491 * @param $key Key to unset
2492 * @return $value Last "popped" value
2494 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2496 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2499 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2501 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2506 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2509 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2510 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2515 * Count generic array group
2517 * @param $keyGroup Main group for the key
2518 * @return $count Count of given group
2520 protected final function countGenericArray ($keyGroup) {
2522 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2525 if (!isset($this->genericArray[$keyGroup])) {
2527 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2532 $count = count($this->genericArray[$keyGroup]);
2535 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2542 * Count generic array sub group
2544 * @param $keyGroup Main group for the key
2545 * @param $subGroup Sub group for the key
2546 * @return $count Count of given group
2548 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2550 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2553 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2555 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2560 $count = count($this->genericArray[$keyGroup][$subGroup]);
2563 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2570 * Count generic array elements
2572 * @param $keyGroup Main group for the key
2573 * @param $subGroup Sub group for the key
2574 * @para $key Key to count
2575 * @return $count Count of given key
2577 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2579 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2582 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2584 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2586 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2588 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2593 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2596 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2603 * Getter for whole generic group array
2605 * @param $keyGroup Key group to get
2606 * @return $array Whole generic array group
2608 protected final function getGenericArray ($keyGroup) {
2610 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2613 if (!isset($this->genericArray[$keyGroup])) {
2615 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2620 return $this->genericArray[$keyGroup];
2624 * Setter for generic array key
2626 * @param $keyGroup Key group to get
2627 * @param $subGroup Sub group for the key
2628 * @param $key Key to unset
2629 * @param $value Mixed value from generic array element
2632 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2634 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2637 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2641 * Getter for generic array key
2643 * @param $keyGroup Key group to get
2644 * @param $subGroup Sub group for the key
2645 * @param $key Key to unset
2646 * @return $value Mixed value from generic array element
2648 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2650 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2653 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2655 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2660 return $this->genericArray[$keyGroup][$subGroup][$key];
2664 * Sets a value in given generic array key/element
2666 * @param $keyGroup Main group for the key
2667 * @param $subGroup Sub group for the key
2668 * @param $key Key to set
2669 * @param $element Element to set
2670 * @param $value Value to set
2673 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2675 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2678 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2682 * Getter for generic array element
2684 * @param $keyGroup Key group to get
2685 * @param $subGroup Sub group for the key
2686 * @param $key Key to look for
2687 * @param $element Element to look for
2688 * @return $value Mixed value from generic array element
2690 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2692 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2695 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2697 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2702 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2706 * Checks if a given sub group is valid (array)
2708 * @param $keyGroup Key group to get
2709 * @param $subGroup Sub group for the key
2710 * @return $isValid Whether given sub group is valid
2712 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2714 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2717 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
2724 * Checks if a given key is valid (array)
2726 * @param $keyGroup Key group to get
2727 * @param $subGroup Sub group for the key
2728 * @param $key Key to check
2729 * @return $isValid Whether given sub group is valid
2731 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
2733 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2736 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
2743 * Translates boolean TRUE to 'Y' and FALSE to 'N'
2745 * @param $boolean Boolean value
2746 * @return $translated Translated boolean value
2748 public static final function translateBooleanToYesNo ($boolean) {
2749 // Make sure it is really boolean
2750 assert(is_bool($boolean));
2753 $translated = ($boolean === TRUE) ? 'Y' : 'N';
2755 // ... and return it