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 InputStream class
149 private $inputStreamInstance = NULL;
152 * An instance of a OutputStream 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();
207 * Length of output from hash()
209 private static $hashLength = NULL;
211 /***********************
212 * Exception codes.... *
213 ***********************/
215 // @todo Try to clean these constants up
216 const EXCEPTION_IS_NULL_POINTER = 0x001;
217 const EXCEPTION_IS_NO_OBJECT = 0x002;
218 const EXCEPTION_IS_NO_ARRAY = 0x003;
219 const EXCEPTION_MISSING_METHOD = 0x004;
220 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
221 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
222 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
223 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
224 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
225 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
226 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
227 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
228 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
229 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
230 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
231 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
232 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
233 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
234 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
235 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
236 const EXCEPTION_PATH_NOT_FOUND = 0x015;
237 const EXCEPTION_INVALID_PATH_NAME = 0x016;
238 const EXCEPTION_READ_PROTECED_PATH = 0x017;
239 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
240 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
241 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
242 const EXCEPTION_INVALID_RESOURCE = 0x01b;
243 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
244 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
245 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
246 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
247 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
248 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
249 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
250 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
251 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
252 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
253 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
254 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
255 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
256 const EXCEPTION_INVALID_STRING = 0x029;
257 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
258 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
259 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
260 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
261 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
262 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
263 const EXCEPTION_MISSING_ELEMENT = 0x030;
264 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
265 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
266 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
267 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
268 const EXCEPTION_FATAL_ERROR = 0x035;
269 const EXCEPTION_FILE_NOT_FOUND = 0x036;
270 const EXCEPTION_ASSERTION_FAILED = 0x037;
271 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
272 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
273 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03a;
276 * Hexadecimal->Decimal translation array
278 private static $hexdec = array(
298 * Decimal->hexadecimal translation array
300 private static $dechex = array(
320 * Startup time in miliseconds
322 private static $startupTime = 0;
325 * Protected super constructor
327 * @param $className Name of the class
330 protected function __construct ($className) {
332 $this->setRealClass($className);
334 // Set configuration instance if no registry ...
335 if (!$this instanceof Register) {
336 // ... because registries doesn't need to be configured
337 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
340 // Is the startup time set? (0 cannot be TRUE anymore)
341 if (self::$startupTime == 0) {
343 self::$startupTime = microtime(TRUE);
348 * Destructor for all classes
352 public function __destruct () {
353 // Flush any updated entries to the database
354 $this->flushPendingUpdates();
356 // Is this object already destroyed?
357 if ($this->__toString() != 'DestructedObject') {
358 // Destroy all informations about this class but keep some text about it alive
359 $this->setRealClass('DestructedObject');
360 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
361 // Already destructed object
362 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
367 // Do not call this twice
368 trigger_error(__METHOD__ . ': Called twice.');
374 * The __call() method where all non-implemented methods end up
376 * @param $methodName Name of the missing method
377 * @args $args Arguments passed to the method
380 public final function __call ($methodName, $args) {
381 return self::__callStatic($methodName, $args);
385 * The __callStatic() method where all non-implemented static methods end up
387 * @param $methodName Name of the missing method
388 * @args $args Arguments passed to the method
391 public static final function __callStatic ($methodName, $args) {
392 // Init argument string
395 // Is it empty or an array?
398 $argsString = 'NULL';
399 } elseif (is_array($args)) {
400 // Some arguments are there
401 foreach ($args as $arg) {
402 // Add the value itself if not array. This prevents 'array to string conversion' message
403 if (is_array($arg)) {
404 $argsString .= 'Array';
409 // Add data about the argument
410 $argsString .= ' (' . gettype($arg);
412 if (is_string($arg)) {
413 // Add length for strings
414 $argsString .= ', ' . strlen($arg);
415 } elseif (is_array($arg)) {
416 // .. or size if array
417 $argsString .= ', ' . count($arg);
418 } elseif ($arg === TRUE) {
419 // ... is boolean 'TRUE'
420 $argsString .= ', TRUE';
421 } elseif ($arg === FALSE) {
422 // ... is boolean 'FALSE'
423 $argsString .= ', FALSE';
427 $argsString .= '), ';
431 if (substr($argsString, -2, 1) == ',') {
432 $argsString = substr($argsString, 0, -2);
435 // Invalid arguments!
436 $argsString = '!INVALID:' . gettype($args) . '!';
439 // Output stub message
440 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
441 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
451 * Getter for $realClass
453 * @return $realClass The name of the real class (not BaseFrameworkSystem)
455 public function __toString () {
456 return $this->realClass;
460 * Magic function to catch setting of missing but set class fields/attributes
462 * @param $name Name of the field/attribute
463 * @param $value Value to store
466 public final function __set ($name, $value) {
467 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
475 * Magic function to catch getting of missing fields/attributes
477 * @param $name Name of the field/attribute
480 public final function __get ($name) {
481 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
487 * Magic function to catch unsetting of missing fields/attributes
489 * @param $name Name of the field/attribute
492 public final function __unset ($name) {
493 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
499 * Setter for the real class name
501 * @param $realClass Class name (string)
504 public final function setRealClass ($realClass) {
506 $this->realClass = (string) $realClass;
510 * Setter for database result instance
512 * @param $resultInstance An instance of a database result class
514 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
516 protected final function setResultInstance (SearchableResult $resultInstance) {
517 $this->resultInstance = $resultInstance;
521 * Getter for database result instance
523 * @return $resultInstance An instance of a database result class
525 public final function getResultInstance () {
526 return $this->resultInstance;
530 * Setter for template engine instances
532 * @param $templateInstance An instance of a template engine class
535 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
536 $this->templateInstance = $templateInstance;
540 * Getter for template engine instances
542 * @return $templateInstance An instance of a template engine class
544 protected final function getTemplateInstance () {
545 return $this->templateInstance;
549 * Setter for search instance
551 * @param $searchInstance Searchable criteria instance
554 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
555 $this->searchInstance = $searchInstance;
559 * Getter for search instance
561 * @return $searchInstance Searchable criteria instance
563 public final function getSearchInstance () {
564 return $this->searchInstance;
568 * Setter for update instance
570 * @param $updateInstance Searchable criteria instance
573 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
574 $this->updateInstance = $updateInstance;
578 * Getter for update instance
580 * @return $updateInstance Updateable criteria instance
582 public final function getUpdateInstance () {
583 return $this->updateInstance;
587 * Setter for resolver instance
589 * @param $resolverInstance Instance of a command resolver class
592 public final function setResolverInstance (Resolver $resolverInstance) {
593 $this->resolverInstance = $resolverInstance;
597 * Getter for resolver instance
599 * @return $resolverInstance Instance of a command resolver class
601 public final function getResolverInstance () {
602 return $this->resolverInstance;
606 * Setter for language instance
608 * @param $configInstance The configuration instance which shall
609 * be FrameworkConfiguration
612 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
613 Registry::getRegistry()->addInstance('config', $configInstance);
617 * Getter for configuration instance
619 * @return $configInstance Configuration instance
621 public final function getConfigInstance () {
622 $configInstance = Registry::getRegistry()->getInstance('config');
623 return $configInstance;
627 * Setter for debug instance
629 * @param $debugInstance The instance for debug output class
632 public final function setDebugInstance (DebugMiddleware $debugInstance) {
633 Registry::getRegistry()->addInstance('debug', $debugInstance);
637 * Getter for debug instance
639 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
641 public final function getDebugInstance () {
642 // Get debug instance
643 $debugInstance = Registry::getRegistry()->getInstance('debug');
646 return $debugInstance;
650 * Setter for web output instance
652 * @param $webInstance The instance for web output class
655 public final function setWebOutputInstance (OutputStreamer $webInstance) {
656 Registry::getRegistry()->addInstance('web_output', $webInstance);
660 * Getter for web output instance
662 * @return $webOutputInstance - Instance to class WebOutput
664 public final function getWebOutputInstance () {
665 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
666 return $webOutputInstance;
670 * Setter for database instance
672 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
675 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
676 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
680 * Getter for database layer
682 * @return $databaseInstance The database layer instance
684 public final function getDatabaseInstance () {
686 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
689 return $databaseInstance;
693 * Setter for compressor channel
695 * @param $compressorInstance An instance of CompressorChannel
698 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
699 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
703 * Getter for compressor channel
705 * @return $compressorInstance The compressor channel
707 public final function getCompressorChannel () {
708 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
709 return $compressorInstance;
713 * Protected getter for a manageable application helper class
715 * @return $applicationInstance An instance of a manageable application helper class
717 protected final function getApplicationInstance () {
718 $applicationInstance = Registry::getRegistry()->getInstance('application');
719 return $applicationInstance;
723 * Setter for a manageable application helper class
725 * @param $applicationInstance An instance of a manageable application helper class
728 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
729 Registry::getRegistry()->addInstance('application', $applicationInstance);
733 * Setter for request instance
735 * @param $requestInstance An instance of a Requestable class
738 public final function setRequestInstance (Requestable $requestInstance) {
739 $this->requestInstance = $requestInstance;
743 * Getter for request instance
745 * @return $requestInstance An instance of a Requestable class
747 public final function getRequestInstance () {
748 return $this->requestInstance;
752 * Setter for response instance
754 * @param $responseInstance An instance of a Responseable class
757 public final function setResponseInstance (Responseable $responseInstance) {
758 $this->responseInstance = $responseInstance;
762 * Getter for response instance
764 * @return $responseInstance An instance of a Responseable class
766 public final function getResponseInstance () {
767 return $this->responseInstance;
771 * Private getter for language instance
773 * @return $langInstance An instance to the language sub-system
775 protected final function getLanguageInstance () {
776 $langInstance = Registry::getRegistry()->getInstance('language');
777 return $langInstance;
781 * Setter for language instance
783 * @param $langInstance An instance to the language sub-system
785 * @see LanguageSystem
787 public final function setLanguageInstance (ManageableLanguage $langInstance) {
788 Registry::getRegistry()->addInstance('language', $langInstance);
792 * Private getter for file IO instance
794 * @return $fileIoInstance An instance to the file I/O sub-system
796 protected final function getFileIoInstance () {
797 return $this->fileIoInstance;
801 * Setter for file I/O instance
803 * @param $fileIoInstance An instance to the file I/O sub-system
806 public final function setFileIoInstance (IoHandler $fileIoInstance) {
807 $this->fileIoInstance = $fileIoInstance;
811 * Protected setter for user instance
813 * @param $userInstance An instance of a user class
816 protected final function setUserInstance (ManageableAccount $userInstance) {
817 $this->userInstance = $userInstance;
821 * Getter for user instance
823 * @return $userInstance An instance of a user class
825 public final function getUserInstance () {
826 return $this->userInstance;
830 * Setter for controller instance (this surely breaks a bit the MVC patterm)
832 * @param $controllerInstance An instance of the controller
835 public final function setControllerInstance (Controller $controllerInstance) {
836 $this->controllerInstance = $controllerInstance;
840 * Getter for controller instance (this surely breaks a bit the MVC patterm)
842 * @return $controllerInstance An instance of the controller
844 public final function getControllerInstance () {
845 return $this->controllerInstance;
849 * Setter for RNG instance
851 * @param $rngInstance An instance of a random number generator (RNG)
854 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
855 $this->rngInstance = $rngInstance;
859 * Getter for RNG instance
861 * @return $rngInstance An instance of a random number generator (RNG)
863 public final function getRngInstance () {
864 return $this->rngInstance;
868 * Setter for Cryptable instance
870 * @param $cryptoInstance An instance of a Cryptable class
873 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
874 $this->cryptoInstance = $cryptoInstance;
878 * Getter for Cryptable instance
880 * @return $cryptoInstance An instance of a Cryptable class
882 public final function getCryptoInstance () {
883 return $this->cryptoInstance;
887 * Setter for the list instance
889 * @param $listInstance A list of Listable
892 protected final function setListInstance (Listable $listInstance) {
893 $this->listInstance = $listInstance;
897 * Getter for the list instance
899 * @return $listInstance A list of Listable
901 protected final function getListInstance () {
902 return $this->listInstance;
906 * Setter for the menu instance
908 * @param $menuInstance A RenderableMenu instance
911 protected final function setMenuInstance (RenderableMenu $menuInstance) {
912 $this->menuInstance = $menuInstance;
916 * Getter for the menu instance
918 * @return $menuInstance A RenderableMenu instance
920 protected final function getMenuInstance () {
921 return $this->menuInstance;
925 * Setter for image instance
927 * @param $imageInstance An instance of an image
930 public final function setImageInstance (BaseImage $imageInstance) {
931 $this->imageInstance = $imageInstance;
935 * Getter for image instance
937 * @return $imageInstance An instance of an image
939 public final function getImageInstance () {
940 return $this->imageInstance;
944 * Setter for stacker instance
946 * @param $stackerInstance An instance of an stacker
949 public final function setStackerInstance (Stackable $stackerInstance) {
950 $this->stackerInstance = $stackerInstance;
954 * Getter for stacker instance
956 * @return $stackerInstance An instance of an stacker
958 public final function getStackerInstance () {
959 return $this->stackerInstance;
963 * Setter for compressor instance
965 * @param $compressorInstance An instance of an compressor
968 public final function setCompressorInstance (Compressor $compressorInstance) {
969 $this->compressorInstance = $compressorInstance;
973 * Getter for compressor instance
975 * @return $compressorInstance An instance of an compressor
977 public final function getCompressorInstance () {
978 return $this->compressorInstance;
982 * Setter for Parseable instance
984 * @param $parserInstance An instance of an Parseable
987 public final function setParserInstance (Parseable $parserInstance) {
988 $this->parserInstance = $parserInstance;
992 * Getter for Parseable instance
994 * @return $parserInstance An instance of an Parseable
996 public final function getParserInstance () {
997 return $this->parserInstance;
1001 * Setter for ProtocolHandler instance
1003 * @param $protocolInstance An instance of an ProtocolHandler
1006 public final function setProtocolInstance (ProtocolHandler $protocolInstance = NULL) {
1007 $this->protocolInstance = $protocolInstance;
1011 * Getter for ProtocolHandler instance
1013 * @return $protocolInstance An instance of an ProtocolHandler
1015 public final function getProtocolInstance () {
1016 return $this->protocolInstance;
1020 * Setter for DatabaseWrapper instance
1022 * @param $wrapperInstance An instance of an DatabaseWrapper
1025 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1026 $this->wrapperInstance = $wrapperInstance;
1030 * Getter for DatabaseWrapper instance
1032 * @return $wrapperInstance An instance of an DatabaseWrapper
1034 public final function getWrapperInstance () {
1035 return $this->wrapperInstance;
1039 * Setter for socket resource
1041 * @param $socketResource A valid socket resource
1044 public final function setSocketResource ($socketResource) {
1045 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1046 $this->socketResource = $socketResource;
1050 * Getter for socket resource
1052 * @return $socketResource A valid socket resource
1054 public final function getSocketResource () {
1055 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1056 return $this->socketResource;
1060 * Setter for helper instance
1062 * @param $helperInstance An instance of a helper class
1065 protected final function setHelperInstance (Helper $helperInstance) {
1066 $this->helperInstance = $helperInstance;
1070 * Getter for helper instance
1072 * @return $helperInstance An instance of a helper class
1074 public final function getHelperInstance () {
1075 return $this->helperInstance;
1079 * Setter for a Sourceable instance
1081 * @param $sourceInstance The Sourceable instance
1084 protected final function setSourceInstance (Sourceable $sourceInstance) {
1085 $this->sourceInstance = $sourceInstance;
1089 * Getter for a Sourceable instance
1091 * @return $sourceInstance The Sourceable instance
1093 protected final function getSourceInstance () {
1094 return $this->sourceInstance;
1098 * Getter for a InputStream instance
1100 * @param $inputStreamInstance The InputStream instance
1102 protected final function getInputStreamInstance () {
1103 return $this->inputStreamInstance;
1107 * Setter for a InputStream instance
1109 * @param $inputStreamInstance The InputStream instance
1112 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1113 $this->inputStreamInstance = $inputStreamInstance;
1117 * Getter for a OutputStream instance
1119 * @param $outputStreamInstance The OutputStream instance
1121 protected final function getOutputStreamInstance () {
1122 return $this->outputStreamInstance;
1126 * Setter for a OutputStream instance
1128 * @param $outputStreamInstance The OutputStream instance
1131 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1132 $this->outputStreamInstance = $outputStreamInstance;
1136 * Setter for handler instance
1138 * @param $handlerInstance An instance of a Handleable class
1141 protected final function setHandlerInstance (Handleable $handlerInstance) {
1142 $this->handlerInstance = $handlerInstance;
1146 * Getter for handler instance
1148 * @return $handlerInstance A Networkable instance
1150 protected final function getHandlerInstance () {
1151 return $this->handlerInstance;
1155 * Setter for visitor instance
1157 * @param $visitorInstance A Visitor instance
1160 protected final function setVisitorInstance (Visitor $visitorInstance) {
1161 $this->visitorInstance = $visitorInstance;
1165 * Getter for visitor instance
1167 * @return $visitorInstance A Visitor instance
1169 protected final function getVisitorInstance () {
1170 return $this->visitorInstance;
1174 * Setter for DHT instance
1176 * @param $dhtInstance A Distributable instance
1179 protected final function setDhtInstance (Distributable $dhtInstance) {
1180 $this->dhtInstance = $dhtInstance;
1184 * Getter for DHT instance
1186 * @return $dhtInstance A Distributable instance
1188 protected final function getDhtInstance () {
1189 return $this->dhtInstance;
1193 * Setter for raw package Data
1195 * @param $packageData Raw package Data
1198 public final function setPackageData (array $packageData) {
1199 $this->packageData = $packageData;
1203 * Getter for raw package Data
1205 * @return $packageData Raw package Data
1207 public function getPackageData () {
1208 return $this->packageData;
1213 * Setter for Iterator instance
1215 * @param $iteratorInstance An instance of an Iterator
1218 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1219 $this->iteratorInstance = $iteratorInstance;
1223 * Getter for Iterator instance
1225 * @return $iteratorInstance An instance of an Iterator
1227 public final function getIteratorInstance () {
1228 return $this->iteratorInstance;
1232 * Setter for InputOutputPointer instance
1234 * @param $pointerInstance An instance of an InputOutputPointer
1237 protected final function setPointerInstance (InputOutputPointer $pointerInstance) {
1238 $this->pointerInstance = $pointerInstance;
1242 * Getter for InputOutputPointer instance
1244 * @return $pointerInstance An instance of an InputOutputPointer
1246 public final function getPointerInstance () {
1247 return $this->pointerInstance;
1251 * Checks whether an object equals this object. You should overwrite this
1252 * method to implement own equality checks
1254 * @param $objectInstance An instance of a FrameworkInterface object
1255 * @return $equals Whether both objects equals
1257 public function equals (FrameworkInterface $objectInstance) {
1260 $this->__toString() == $objectInstance->__toString()
1262 $this->hashCode() == $objectInstance->hashCode()
1265 // Return the result
1270 * Generates a generic hash code of this class. You should really overwrite
1271 * this method with your own hash code generator code. But keep KISS in mind.
1273 * @return $hashCode A generic hash code respresenting this whole class
1275 public function hashCode () {
1277 return crc32($this->__toString());
1281 * Formats computer generated price values into human-understandable formats
1282 * with thousand and decimal separators.
1284 * @param $value The in computer format value for a price
1285 * @param $currency The currency symbol (use HTML-valid characters!)
1286 * @param $decNum Number of decimals after commata
1287 * @return $price The for the current language formated price string
1288 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1289 * thousands separator
1292 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1293 // Are all required attriutes set?
1294 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1295 // Throw an exception
1296 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1300 $value = (float) $value;
1302 // Reformat the US number
1303 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1305 // Return as string...
1310 * Appends a trailing slash to a string
1312 * @param $str A string (maybe) without trailing slash
1313 * @return $str A string with an auto-appended trailing slash
1315 public final function addMissingTrailingSlash ($str) {
1316 // Is there a trailing slash?
1317 if (substr($str, -1, 1) != '/') {
1321 // Return string with trailing slash
1326 * Prepare the template engine (WebTemplateEngine by default) for a given
1327 * application helper instance (ApplicationHelper by default).
1329 * @param $applicationInstance An application helper instance or
1330 * null if we shall use the default
1331 * @return $templateInstance The template engine instance
1332 * @throws NullPointerException If the discovered application
1333 * instance is still null
1335 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1336 // Is the application instance set?
1337 if (is_null($applicationInstance)) {
1338 // Get the current instance
1339 $applicationInstance = $this->getApplicationInstance();
1342 if (is_null($applicationInstance)) {
1343 // Thrown an exception
1344 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1348 // Initialize the template engine
1349 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
1351 // Return the prepared instance
1352 return $templateInstance;
1356 * Debugs this instance by putting out it's full content
1358 * @param $message Optional message to show in debug output
1361 public final function debugInstance ($message = '') {
1362 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1363 restore_error_handler();
1368 // Is a message set?
1369 if (!empty($message)) {
1370 // Construct message
1371 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1374 // Generate the output
1375 $content .= sprintf('<pre>%s</pre>',
1378 print_r($this, TRUE)
1384 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>',
1385 $this->__toString(),
1387 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1392 * Replaces control characters with printable output
1394 * @param $str String with control characters
1395 * @return $str Replaced string
1397 protected function replaceControlCharacters ($str) {
1400 chr(13), '[r]', str_replace(
1401 chr(10), '[n]', str_replace(
1411 * Output a partial stub message for the caller method
1413 * @param $message An optional message to display
1416 protected function partialStub ($message = '') {
1417 // Get the backtrace
1418 $backtrace = debug_backtrace();
1420 // Generate the class::method string
1421 $methodName = 'UnknownClass->unknownMethod';
1422 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1423 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1426 // Construct the full message
1427 $stubMessage = sprintf('[%s:] Partial stub!',
1431 // Is the extra message given?
1432 if (!empty($message)) {
1433 // Then add it as well
1434 $stubMessage .= ' Message: ' . $message;
1437 // Debug instance is there?
1438 if (!is_null($this->getDebugInstance())) {
1439 // Output stub message
1440 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1443 trigger_error($stubMessage);
1449 * Outputs a debug backtrace and stops further script execution
1451 * @param $message An optional message to output
1452 * @param $doExit Whether exit the program (TRUE is default)
1455 public function debugBackTrace ($message = '', $doExit = TRUE) {
1456 // Sorry, there is no other way getting this nice backtrace
1457 if (!empty($message)) {
1459 printf('Message: %s<br />' . chr(10), $message);
1463 debug_print_backtrace();
1467 if ($doExit === TRUE) {
1473 * Creates an instance of a debugger instance
1475 * @param $className Name of the class (currently unsupported)
1476 * @return $debugInstance An instance of a debugger class
1478 public final static function createDebugInstance ($className) {
1479 // Is the instance set?
1480 if (!Registry::getRegistry()->instanceExists('debug')) {
1481 // Init debug instance
1482 $debugInstance = NULL;
1486 // Get a debugger instance
1487 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_class'));
1488 } catch (NullPointerException $e) {
1489 // Didn't work, no instance there
1490 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1493 // Empty string should be ignored and used for testing the middleware
1494 DebugMiddleware::getSelfInstance()->output('');
1496 // Set it in its own class. This will set it in the registry
1497 $debugInstance->setDebugInstance($debugInstance);
1499 // Get instance from registry
1500 $debugInstance = Registry::getRegistry()->getDebugInstance();
1504 return $debugInstance;
1508 * Simple output of a message with line-break
1510 * @param $message Message to output
1513 public function outputLine ($message) {
1515 print($message . PHP_EOL);
1519 * Outputs a debug message whether to debug instance (should be set!) or
1520 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1521 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1523 * @param $message Message we shall send out...
1524 * @param $doPrint Whether print or die here (default: print)
1525 * @paran $stripTags Whether to strip tags (default: FALSE)
1528 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1529 // Set debug instance to NULL
1530 $debugInstance = NULL;
1534 // Get debug instance
1535 $debugInstance = $this->getDebugInstance();
1536 } catch (NullPointerException $e) {
1537 // The debug instance is not set (yet)
1540 // Is the debug instance there?
1541 if (is_object($debugInstance)) {
1542 // Use debug output handler
1543 $debugInstance->output($message, $stripTags);
1545 if ($doPrint === FALSE) {
1546 // Die here if not printed
1550 // Are debug times enabled?
1551 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1553 $message = $this->getPrintableExecutionTime() . $message;
1557 if ($doPrint === TRUE) {
1559 $this->outputLine($message);
1568 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1570 * @param $str The string, what ever it is needs to be converted
1571 * @return $className Generated class name
1573 public function convertToClassName ($str) {
1577 // Convert all dashes in underscores
1578 $str = $this->convertDashesToUnderscores($str);
1580 // Now use that underscores to get classname parts for hungarian style
1581 foreach (explode('_', $str) as $strPart) {
1582 // Make the class name part lower case and first upper case
1583 $className .= ucfirst(strtolower($strPart));
1586 // Return class name
1591 * Converts dashes to underscores, e.g. useable for configuration entries
1593 * @param $str The string with maybe dashes inside
1594 * @return $str The converted string with no dashed, but underscores
1596 public final function convertDashesToUnderscores ($str) {
1598 $str = str_replace('-', '_', $str);
1600 // Return converted string
1605 * Marks up the code by adding e.g. line numbers
1607 * @param $phpCode Unmarked PHP code
1608 * @return $markedCode Marked PHP code
1610 public function markupCode ($phpCode) {
1615 $errorArray = error_get_last();
1617 // Init the code with error message
1618 if (is_array($errorArray)) {
1620 $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>',
1621 basename($errorArray['file']),
1622 $errorArray['line'],
1623 $errorArray['message'],
1628 // Add line number to the code
1629 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1631 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1633 htmlentities($code, ENT_QUOTES)
1642 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1643 * beatiful for web-based front-ends. If null is given a message id
1644 * null_timestamp will be resolved and returned.
1646 * @param $timestamp Timestamp to prepare (filter) for display
1647 * @return $readable A readable timestamp
1649 public function doFilterFormatTimestamp ($timestamp) {
1650 // Default value to return
1653 // Is the timestamp null?
1654 if (is_null($timestamp)) {
1655 // Get a message string
1656 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1658 switch ($this->getLanguageInstance()->getLanguageCode()) {
1659 case 'de': // German format is a bit different to default
1660 // Split the GMT stamp up
1661 $dateTime = explode(' ', $timestamp );
1662 $dateArray = explode('-', $dateTime[0]);
1663 $timeArray = explode(':', $dateTime[1]);
1665 // Construct the timestamp
1666 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1676 default: // Default is pass-through
1677 $readable = $timestamp;
1687 * Filter a given number into a localized number
1689 * @param $value The raw value from e.g. database
1690 * @return $localized Localized value
1692 public function doFilterFormatNumber ($value) {
1693 // Generate it from config and localize dependencies
1694 switch ($this->getLanguageInstance()->getLanguageCode()) {
1695 case 'de': // German format is a bit different to default
1696 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1699 default: // US, etc.
1700 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1709 * "Getter" for databse entry
1711 * @return $entry An array with database entries
1712 * @throws NullPointerException If the database result is not found
1713 * @throws InvalidDatabaseResultException If the database result is invalid
1715 protected final function getDatabaseEntry () {
1716 // Is there an instance?
1717 if (is_null($this->getResultInstance())) {
1718 // Throw an exception here
1719 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1723 $this->getResultInstance()->rewind();
1725 // Do we have an entry?
1726 if ($this->getResultInstance()->valid() === FALSE) {
1727 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1731 $this->getResultInstance()->next();
1734 $entry = $this->getResultInstance()->current();
1741 * Getter for field name
1743 * @param $fieldName Field name which we shall get
1744 * @return $fieldValue Field value from the user
1745 * @throws NullPointerException If the result instance is null
1747 public final function getField ($fieldName) {
1748 // Default field value
1751 // Get result instance
1752 $resultInstance = $this->getResultInstance();
1754 // Is this instance null?
1755 if (is_null($resultInstance)) {
1756 // Then the user instance is no longer valid (expired cookies?)
1757 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1760 // Get current array
1761 $fieldArray = $resultInstance->current();
1762 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
1764 // Convert dashes to underscore
1765 $fieldName = $this->convertDashesToUnderscores($fieldName);
1767 // Does the field exist?
1768 if (isset($fieldArray[$fieldName])) {
1770 $fieldValue = $fieldArray[$fieldName];
1772 // Missing field entry, may require debugging
1773 self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ':fieldname=' . $fieldName . ' not found!');
1781 * Flushs all pending updates to the database layer
1785 public function flushPendingUpdates () {
1786 // Get result instance
1787 $resultInstance = $this->getResultInstance();
1789 // Do we have data to update?
1790 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1791 // Get wrapper class name config entry
1792 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1794 // Create object instance
1795 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1797 // Yes, then send the whole result to the database layer
1798 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1803 * Outputs a deprecation warning to the developer.
1805 * @param $message The message we shall output to the developer
1807 * @todo Write a logging mechanism for productive mode
1809 public function deprecationWarning ($message) {
1810 // Is developer mode active?
1811 if (defined('DEVELOPER')) {
1812 // Debug instance is there?
1813 if (!is_null($this->getDebugInstance())) {
1814 // Output stub message
1815 self::createDebugInstance(__CLASS__)->debugOutput($message);
1818 trigger_error($message . "<br />\n");
1822 // @TODO Finish this part!
1823 $this->partialStub('Developer mode inactive. Message:' . $message);
1828 * Checks whether the given PHP extension is loaded
1830 * @param $phpExtension The PHP extension we shall check
1831 * @return $isLoaded Whether the PHP extension is loaded
1833 public final function isPhpExtensionLoaded ($phpExtension) {
1835 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1842 * "Getter" as a time() replacement but with milliseconds. You should use this
1843 * method instead of the encapsulated getimeofday() function.
1845 * @return $milliTime Timestamp with milliseconds
1847 public function getMilliTime () {
1848 // Get the time of day as float
1849 $milliTime = gettimeofday(TRUE);
1856 * Idles (sleeps) for given milliseconds
1858 * @return $hasSlept Whether it goes fine
1860 public function idle ($milliSeconds) {
1861 // Sleep is fine by default
1864 // Idle so long with found function
1865 if (function_exists('time_sleep_until')) {
1866 // Get current time and add idle time
1867 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1869 // New PHP 5.1.0 function found, ignore errors
1870 $hasSlept = @time_sleep_until($sleepUntil);
1873 * My Sun station doesn't have that function even with latest PHP
1876 usleep($milliSeconds * 1000);
1883 * Converts a hexadecimal string, even with negative sign as first string to
1884 * a decimal number using BC functions.
1886 * This work is based on comment #86673 on php.net documentation page at:
1887 * <http://de.php.net/manual/en/function.dechex.php#86673>
1889 * @param $hex Hexadecimal string
1890 * @return $dec Decimal number
1892 protected function hex2dec ($hex) {
1893 // Convert to all lower-case
1894 $hex = strtolower($hex);
1896 // Detect sign (negative/positive numbers)
1898 if (substr($hex, 0, 1) == '-') {
1900 $hex = substr($hex, 1);
1903 // Decode the hexadecimal string into a decimal number
1905 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1906 $factor = self::$hexdec[substr($hex, $i, 1)];
1907 $dec = bcadd($dec, bcmul($factor, $e));
1910 // Return the decimal number
1911 return $sign . $dec;
1915 * Converts even very large decimal numbers, also signed, to a hexadecimal
1918 * This work is based on comment #97756 on php.net documentation page at:
1919 * <http://de.php.net/manual/en/function.hexdec.php#97756>
1921 * @param $dec Decimal number, even with negative sign
1922 * @param $maxLength Optional maximum length of the string
1923 * @return $hex Hexadecimal string
1925 protected function dec2hex ($dec, $maxLength = 0) {
1926 // maxLength can be zero or devideable by 2
1927 assert(($maxLength == 0) || (($maxLength % 2) == 0));
1929 // Detect sign (negative/positive numbers)
1936 // Encode the decimal number into a hexadecimal string
1939 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
1941 } while ($dec >= 1);
1944 * Leading zeros are required for hex-decimal "numbers". In some
1945 * situations more leading zeros are wanted, so check for both
1948 if ($maxLength > 0) {
1949 // Prepend more zeros
1950 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
1951 } elseif ((strlen($hex) % 2) != 0) {
1952 // Only make string's length dividable by 2
1956 // Return the hexadecimal string
1957 return $sign . $hex;
1961 * Converts a ASCII string (0 to 255) into a decimal number.
1963 * @param $asc The ASCII string to be converted
1964 * @return $dec Decimal number
1966 protected function asc2dec ($asc) {
1967 // Convert it into a hexadecimal number
1968 $hex = bin2hex($asc);
1970 // And back into a decimal number
1971 $dec = $this->hex2dec($hex);
1978 * Converts a decimal number into an ASCII string.
1980 * @param $dec Decimal number
1981 * @return $asc An ASCII string
1983 protected function dec2asc ($dec) {
1984 // First convert the number into a hexadecimal string
1985 $hex = $this->dec2hex($dec);
1987 // Then convert it into the ASCII string
1988 $asc = $this->hex2asc($hex);
1995 * Converts a hexadecimal number into an ASCII string. Negative numbers
1998 * @param $hex Hexadecimal string
1999 * @return $asc An ASCII string
2001 protected function hex2asc ($hex) {
2002 // Check for length, it must be devideable by 2
2003 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2004 assert((strlen($hex) % 2) == 0);
2008 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2009 // Get the decimal number of the chunk
2010 $part = hexdec(substr($hex, $idx, 2));
2012 // Add it to the final string
2016 // Return the final string
2021 * Checks whether the given encoded data was encoded with Base64
2023 * @param $encodedData Encoded data we shall check
2024 * @return $isBase64 Whether the encoded data is Base64
2026 protected function isBase64Encoded ($encodedData) {
2028 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2035 * "Getter" to get response/request type from analysis of the system.
2037 * @return $responseType Analyzed response type
2039 protected function getResponseTypeFromSystem () {
2040 // Default is console
2041 $responseType = 'console';
2043 // Is 'HTTP_HOST' set?
2044 if (isset($_SERVER['HTTP_HOST'])) {
2045 // Then it is a HTTP response/request
2046 $responseType = 'http';
2050 return $responseType;
2054 * Gets a cache key from Criteria instance
2056 * @param $criteriaInstance An instance of a Criteria class
2057 * @param $onlyKeys Only use these keys for a cache key
2058 * @return $cacheKey A cache key suitable for lookup/storage purposes
2060 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2062 $cacheKey = sprintf('%s@%s',
2063 $this->__toString(),
2064 $criteriaInstance->getCacheKey($onlyKeys)
2068 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2073 * Getter for startup time in miliseconds
2075 * @return $startupTime Startup time in miliseconds
2077 protected function getStartupTime () {
2078 return self::$startupTime;
2082 * "Getter" for a printable currently execution time in nice braces
2084 * @return $executionTime Current execution time in nice braces
2086 protected function getPrintableExecutionTime () {
2087 // Caculate the execution time
2088 $executionTime = microtime(TRUE) - $this->getStartupTime();
2090 // Pack it in nice braces
2091 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2094 return $executionTime;
2098 * Hashes a given string with a simple but stronger hash function (no salt)
2099 * and hex-encode it.
2101 * @param $str The string to be hashed
2102 * @return $hash The hash from string $str
2104 public static final function hash ($str) {
2105 // Hash given string with (better secure) hasher
2106 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2113 * "Getter" for length of hash() output. This will be "cached" to speed up
2116 * @return $length Length of hash() output
2118 public static final function getHashLength () {
2120 if (is_null(self::$hashLength)) {
2121 // No, then hash a string and save its length.
2122 self::$hashLength = strlen(self::hash('abc123'));
2126 return self::$hashLength;
2130 * Checks whether the given number is really a number (only chars 0-9).
2132 * @param $num A string consisting only chars between 0 and 9
2133 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2134 * @param $assertMismatch Whether to assert mismatches
2135 * @return $ret The (hopefully) secured numbered value
2137 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2138 // Filter all numbers out
2139 $ret = preg_replace('/[^0123456789]/', '', $num);
2142 if ($castValue === TRUE) {
2143 // Cast to biggest numeric type
2144 $ret = (double) $ret;
2147 // Assert only if requested
2148 if ($assertMismatch === TRUE) {
2149 // Has the whole value changed?
2150 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2158 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2160 * @param $num A string consisting only chars between 0 and 9
2161 * @param $assertMismatch Whether to assert mismatches
2162 * @return $ret The (hopefully) secured hext-numbered value
2164 public function hexval ($num, $assertMismatch = FALSE) {
2165 // Filter all numbers out
2166 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2168 // Assert only if requested
2169 if ($assertMismatch === TRUE) {
2170 // Has the whole value changed?
2171 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2179 * Checks whether start/end marker are set
2181 * @param $data Data to be checked
2182 * @return $isset Whether start/end marker are set
2184 public final function ifStartEndMarkersSet ($data) {
2186 $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));
2188 // ... and return it
2193 * Determines if an element is set in the generic array
2195 * @param $keyGroup Main group for the key
2196 * @param $subGroup Sub group for the key
2197 * @param $key Key to check
2198 * @param $element Element to check
2199 * @return $isset Whether the given key is set
2201 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2203 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2206 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2212 * Determines if a key is set in the generic array
2214 * @param $keyGroup Main group for the key
2215 * @param $subGroup Sub group for the key
2216 * @param $key Key to check
2217 * @return $isset Whether the given key is set
2219 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2221 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2224 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2232 * Determines if a group is set in the generic array
2234 * @param $keyGroup Main group
2235 * @param $subGroup Sub group
2236 * @return $isset Whether the given group is set
2238 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2240 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2243 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2250 * Getter for sub key group
2252 * @param $keyGroup Main key group
2253 * @param $subGroup Sub key group
2254 * @return $array An array with all array elements
2256 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2258 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2259 // No, then abort here
2260 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2265 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2268 return $this->genericArray[$keyGroup][$subGroup];
2272 * Unsets a given key in generic array
2274 * @param $keyGroup Main group for the key
2275 * @param $subGroup Sub group for the key
2276 * @param $key Key to unset
2279 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2281 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2284 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2288 * Unsets a given element in generic array
2290 * @param $keyGroup Main group for the key
2291 * @param $subGroup Sub group for the key
2292 * @param $key Key to unset
2293 * @param $element Element to unset
2296 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2298 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2301 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2305 * Append a string to a given generic array key
2307 * @param $keyGroup Main group for the key
2308 * @param $subGroup Sub group for the key
2309 * @param $key Key to unset
2310 * @param $value Value to add/append
2313 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2315 //* 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);
2317 // Is it already there?
2318 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2320 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2323 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2328 * Append a string to a given generic array element
2330 * @param $keyGroup Main group for the key
2331 * @param $subGroup Sub group for the key
2332 * @param $key Key to unset
2333 * @param $element Element to check
2334 * @param $value Value to add/append
2337 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2339 //* 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);
2341 // Is it already there?
2342 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2344 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2347 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2352 * Initializes given generic array group
2354 * @param $keyGroup Main group for the key
2355 * @param $subGroup Sub group for the key
2356 * @param $key Key to use
2357 * @param $forceInit Optionally force initialization
2360 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2362 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2364 // Is it already set?
2365 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2366 // Already initialized
2367 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2372 $this->genericArray[$keyGroup][$subGroup] = array();
2376 * Initializes given generic array key
2378 * @param $keyGroup Main group for the key
2379 * @param $subGroup Sub group for the key
2380 * @param $key Key to use
2381 * @param $forceInit Optionally force initialization
2384 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2386 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2388 // Is it already set?
2389 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2390 // Already initialized
2391 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2396 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2400 * Initializes given generic array element
2402 * @param $keyGroup Main group for the key
2403 * @param $subGroup Sub group for the key
2404 * @param $key Key to use
2405 * @param $element Element to use
2406 * @param $forceInit Optionally force initialization
2409 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2411 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2413 // Is it already set?
2414 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2415 // Already initialized
2416 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2421 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2425 * Pushes an element to a generic key
2427 * @param $keyGroup Main group for the key
2428 * @param $subGroup Sub group for the key
2429 * @param $key Key to use
2430 * @param $value Value to add/append
2431 * @return $count Number of array elements
2433 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2435 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2438 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2440 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2444 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2447 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2448 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2453 * Pushes an element to a generic array element
2455 * @param $keyGroup Main group for the key
2456 * @param $subGroup Sub group for the key
2457 * @param $key Key to use
2458 * @param $element Element to check
2459 * @param $value Value to add/append
2460 * @return $count Number of array elements
2462 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2464 //* 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));
2467 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2469 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2473 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2476 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2477 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2482 * Pops an element from a generic group
2484 * @param $keyGroup Main group for the key
2485 * @param $subGroup Sub group for the key
2486 * @param $key Key to unset
2487 * @return $value Last "popped" value
2489 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2491 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2494 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2496 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2501 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2504 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2505 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2510 * Shifts an element from a generic group
2512 * @param $keyGroup Main group for the key
2513 * @param $subGroup Sub group for the key
2514 * @param $key Key to unset
2515 * @return $value Last "popped" value
2517 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2519 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2522 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2524 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2529 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2532 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2533 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2538 * Count generic array group
2540 * @param $keyGroup Main group for the key
2541 * @return $count Count of given group
2543 protected final function countGenericArray ($keyGroup) {
2545 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2548 if (!isset($this->genericArray[$keyGroup])) {
2550 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2555 $count = count($this->genericArray[$keyGroup]);
2558 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2565 * Count generic array sub group
2567 * @param $keyGroup Main group for the key
2568 * @param $subGroup Sub group for the key
2569 * @return $count Count of given group
2571 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2573 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2576 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2578 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2583 $count = count($this->genericArray[$keyGroup][$subGroup]);
2586 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2593 * Count generic array elements
2595 * @param $keyGroup Main group for the key
2596 * @param $subGroup Sub group for the key
2597 * @para $key Key to count
2598 * @return $count Count of given key
2600 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2602 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2605 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2607 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2609 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2611 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2616 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2619 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2626 * Getter for whole generic group array
2628 * @param $keyGroup Key group to get
2629 * @return $array Whole generic array group
2631 protected final function getGenericArray ($keyGroup) {
2633 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2636 if (!isset($this->genericArray[$keyGroup])) {
2638 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2643 return $this->genericArray[$keyGroup];
2647 * Setter for generic array key
2649 * @param $keyGroup Key group to get
2650 * @param $subGroup Sub group for the key
2651 * @param $key Key to unset
2652 * @param $value Mixed value from generic array element
2655 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2657 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2660 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2664 * Getter for generic array key
2666 * @param $keyGroup Key group to get
2667 * @param $subGroup Sub group for the key
2668 * @param $key Key to unset
2669 * @return $value Mixed value from generic array element
2671 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2673 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2676 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2678 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2683 return $this->genericArray[$keyGroup][$subGroup][$key];
2687 * Sets a value in given generic array key/element
2689 * @param $keyGroup Main group for the key
2690 * @param $subGroup Sub group for the key
2691 * @param $key Key to set
2692 * @param $element Element to set
2693 * @param $value Value to set
2696 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2698 //* 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));
2701 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2705 * Getter for generic array element
2707 * @param $keyGroup Key group to get
2708 * @param $subGroup Sub group for the key
2709 * @param $key Key to look for
2710 * @param $element Element to look for
2711 * @return $value Mixed value from generic array element
2713 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2715 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2718 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2720 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2725 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2729 * Checks if a given sub group is valid (array)
2731 * @param $keyGroup Key group to get
2732 * @param $subGroup Sub group for the key
2733 * @return $isValid Whether given sub group is valid
2735 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2737 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2740 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
2747 * Checks if a given key is valid (array)
2749 * @param $keyGroup Key group to get
2750 * @param $subGroup Sub group for the key
2751 * @param $key Key to check
2752 * @return $isValid Whether given sub group is valid
2754 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
2756 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2759 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
2766 * Translates boolean TRUE to 'Y' and FALSE to 'N'
2768 * @param $boolean Boolean value
2769 * @return $translated Translated boolean value
2771 public static final function translateBooleanToYesNo ($boolean) {
2772 // Make sure it is really boolean
2773 assert(is_bool($boolean));
2776 $translated = ($boolean === TRUE) ? 'Y' : 'N';
2778 // ... and return it