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@ship-simu.org>
8 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Core Developer Team
9 * @license GNU GPL 3.0 or any newer version
10 * @link http://www.ship-simu.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 * Thousands separator
179 private $thousands = '.'; // German
184 private $decimals = ','; // German
189 private $socketResource = FALSE;
194 private $packageData = array();
199 private $genericArray = array();
201 /***********************
202 * Exception codes.... *
203 ***********************/
205 // @todo Try to clean these constants up
206 const EXCEPTION_IS_NULL_POINTER = 0x001;
207 const EXCEPTION_IS_NO_OBJECT = 0x002;
208 const EXCEPTION_IS_NO_ARRAY = 0x003;
209 const EXCEPTION_MISSING_METHOD = 0x004;
210 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
211 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
212 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
213 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
214 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
215 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
216 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
217 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
218 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
219 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
220 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
221 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
222 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
223 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
224 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
225 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
226 const EXCEPTION_PATH_NOT_FOUND = 0x015;
227 const EXCEPTION_INVALID_PATH_NAME = 0x016;
228 const EXCEPTION_READ_PROTECED_PATH = 0x017;
229 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
230 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
231 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
232 const EXCEPTION_INVALID_RESOURCE = 0x01b;
233 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
234 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
235 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
236 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
237 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
238 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
239 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
240 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
241 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
242 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
243 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
244 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
245 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
246 const EXCEPTION_INVALID_STRING = 0x029;
247 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
248 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
249 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
250 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
251 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
252 const EXCEPTION_MISSING_ELEMENT = 0x030;
253 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
254 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
255 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
256 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
257 const EXCEPTION_FATAL_ERROR = 0x035;
258 const EXCEPTION_FILE_NOT_FOUND = 0x036;
259 const EXCEPTION_ASSERTION_FAILED = 0x037;
260 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
261 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
262 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x040;
265 * Hexadecimal->Decimal translation array
267 private static $hexdec = array(
287 * Decimal->hexadecimal translation array
289 private static $dechex = array(
309 * Startup time in miliseconds
311 private static $startupTime = 0;
314 * Protected super constructor
316 * @param $className Name of the class
319 protected function __construct ($className) {
321 $this->setRealClass($className);
323 // Set configuration instance if no registry ...
324 if (!$this instanceof Register) {
325 // ... because registries doesn't need to be configured
326 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
329 // Is the startup time set? (0 cannot be true anymore)
330 if (self::$startupTime == 0) {
332 self::$startupTime = microtime(true);
337 * Destructor for all classes
341 public function __destruct () {
342 // Flush any updated entries to the database
343 $this->flushPendingUpdates();
345 // Is this object already destroyed?
346 if ($this->__toString() != 'DestructedObject') {
347 // Destroy all informations about this class but keep some text about it alive
348 $this->setRealClass('DestructedObject');
349 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
350 // Already destructed object
351 self::createDebugInstance(__CLASS__)->debugOutput(sprintf("[%s:] The object <span class=\"object_name\">%s</span> is already destroyed.",
359 * The __call() method where all non-implemented methods end up
361 * @param $methodName Name of the missing method
362 * @args $args Arguments passed to the method
365 public final function __call ($methodName, $args) {
366 return self::__callStatic($methodName, $args);
370 * The __callStatic() method where all non-implemented static methods end up
372 * @param $methodName Name of the missing method
373 * @args $args Arguments passed to the method
376 public static final function __callStatic ($methodName, $args) {
377 // Init argument string
380 // Is it empty or an array?
383 $argsString = 'NULL';
384 } elseif (is_array($args)) {
385 // Some arguments are there
386 foreach ($args as $arg) {
387 // Add the value itself if not array. This prevents 'array to string conversion' message
388 if (is_array($arg)) {
389 $argsString .= 'Array';
394 // Add data about the argument
395 $argsString .= ' (' . gettype($arg);
397 if (is_string($arg)) {
398 // Add length for strings
399 $argsString .= ', ' . strlen($arg);
400 } elseif (is_array($arg)) {
401 // .. or size if array
402 $argsString .= ', ' . count($arg);
403 } elseif ($arg === TRUE) {
404 // ... is boolean 'true'
405 $argsString .= ', true';
406 } elseif ($arg === FALSE) {
407 // ... is boolean 'true'
408 $argsString .= ', false';
412 $argsString .= '), ';
416 if (substr($argsString, -2, 1) == ',') {
417 $argsString = substr($argsString, 0, -2);
420 // Invalid arguments!
421 $argsString = '!INVALID:' . gettype($args) . '!';
424 // Output stub message
425 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
426 self::createDebugInstance(__CLASS__)->debugOutput(sprintf("[unknown::%s:] Stub! Args: %s",
436 * Getter for $realClass
438 * @return $realClass The name of the real class (not BaseFrameworkSystem)
440 public function __toString () {
441 return $this->realClass;
445 * Magic function to catch setting of missing but set class fields/attributes
447 * @param $name Name of the field/attribute
448 * @param $value Value to store
451 public final function __set ($name, $value) {
452 $this->debugBackTrace(sprintf("Tried to set a missing field. name=%s, value[%s]=%s",
460 * Magic function to catch getting of missing fields/attributes
462 * @param $name Name of the field/attribute
465 public final function __get ($name) {
466 $this->debugBackTrace(sprintf("Tried to get a missing field. name=%s",
472 * Magic function to catch unsetting of missing fields/attributes
474 * @param $name Name of the field/attribute
477 public final function __unset ($name) {
478 $this->debugBackTrace(sprintf("Tried to unset a missing field. name=%s",
484 * Setter for the real class name
486 * @param $realClass Class name (string)
489 public final function setRealClass ($realClass) {
491 $this->realClass = (string) $realClass;
495 * Setter for database result instance
497 * @param $resultInstance An instance of a database result class
499 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
501 protected final function setResultInstance (SearchableResult $resultInstance) {
502 $this->resultInstance = $resultInstance;
506 * Getter for database result instance
508 * @return $resultInstance An instance of a database result class
510 public final function getResultInstance () {
511 return $this->resultInstance;
515 * Setter for template engine instances
517 * @param $templateInstance An instance of a template engine class
520 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
521 $this->templateInstance = $templateInstance;
525 * Getter for template engine instances
527 * @return $templateInstance An instance of a template engine class
529 protected final function getTemplateInstance () {
530 return $this->templateInstance;
534 * Setter for search instance
536 * @param $searchInstance Searchable criteria instance
539 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
540 $this->searchInstance = $searchInstance;
544 * Getter for search instance
546 * @return $searchInstance Searchable criteria instance
548 public final function getSearchInstance () {
549 return $this->searchInstance;
553 * Setter for update instance
555 * @param $updateInstance Searchable criteria instance
558 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
559 $this->updateInstance = $updateInstance;
563 * Getter for update instance
565 * @return $updateInstance Updateable criteria instance
567 public final function getUpdateInstance () {
568 return $this->updateInstance;
572 * Setter for resolver instance
574 * @param $resolverInstance Instance of a command resolver class
577 public final function setResolverInstance (Resolver $resolverInstance) {
578 $this->resolverInstance = $resolverInstance;
582 * Getter for resolver instance
584 * @return $resolverInstance Instance of a command resolver class
586 public final function getResolverInstance () {
587 return $this->resolverInstance;
591 * Setter for language instance
593 * @param $configInstance The configuration instance which shall
594 * be FrameworkConfiguration
597 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
598 Registry::getRegistry()->addInstance('config', $configInstance);
602 * Getter for configuration instance
604 * @return $configInstance Configuration instance
606 public final function getConfigInstance () {
607 $configInstance = Registry::getRegistry()->getInstance('config');
608 return $configInstance;
612 * Setter for debug instance
614 * @param $debugInstance The instance for debug output class
617 public final function setDebugInstance (DebugMiddleware $debugInstance) {
618 Registry::getRegistry()->addInstance('debug', $debugInstance);
622 * Getter for debug instance
624 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
626 public final function getDebugInstance () {
627 // Get debug instance
628 $debugInstance = Registry::getRegistry()->getInstance('debug');
631 return $debugInstance;
635 * Setter for web output instance
637 * @param $webInstance The instance for web output class
640 public final function setWebOutputInstance (OutputStreamer $webInstance) {
641 Registry::getRegistry()->addInstance('web_output', $webInstance);
645 * Getter for web output instance
647 * @return $webOutputInstance - Instance to class WebOutput
649 public final function getWebOutputInstance () {
650 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
651 return $webOutputInstance;
655 * Setter for database instance
657 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
660 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
661 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
665 * Getter for database layer
667 * @return $databaseInstance The database layer instance
669 public final function getDatabaseInstance () {
671 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
674 return $databaseInstance;
678 * Setter for compressor channel
680 * @param $compressorInstance An instance of CompressorChannel
683 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
684 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
688 * Getter for compressor channel
690 * @return $compressorInstance The compressor channel
692 public final function getCompressorChannel () {
693 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
694 return $compressorInstance;
698 * Protected getter for a manageable application helper class
700 * @return $applicationInstance An instance of a manageable application helper class
702 protected final function getApplicationInstance () {
703 $applicationInstance = Registry::getRegistry()->getInstance('application');
704 return $applicationInstance;
708 * Setter for a manageable application helper class
710 * @param $applicationInstance An instance of a manageable application helper class
713 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
714 Registry::getRegistry()->addInstance('application', $applicationInstance);
718 * Setter for request instance
720 * @param $requestInstance An instance of a Requestable class
723 public final function setRequestInstance (Requestable $requestInstance) {
724 $this->requestInstance = $requestInstance;
728 * Getter for request instance
730 * @return $requestInstance An instance of a Requestable class
732 public final function getRequestInstance () {
733 return $this->requestInstance;
737 * Setter for response instance
739 * @param $responseInstance An instance of a Responseable class
742 public final function setResponseInstance (Responseable $responseInstance) {
743 $this->responseInstance = $responseInstance;
747 * Getter for response instance
749 * @return $responseInstance An instance of a Responseable class
751 public final function getResponseInstance () {
752 return $this->responseInstance;
756 * Private getter for language instance
758 * @return $langInstance An instance to the language sub-system
760 protected final function getLanguageInstance () {
761 $langInstance = Registry::getRegistry()->getInstance('language');
762 return $langInstance;
766 * Setter for language instance
768 * @param $langInstance An instance to the language sub-system
770 * @see LanguageSystem
772 public final function setLanguageInstance (ManageableLanguage $langInstance) {
773 Registry::getRegistry()->addInstance('language', $langInstance);
777 * Private getter for file IO instance
779 * @return $fileIoInstance An instance to the file I/O sub-system
781 protected final function getFileIoInstance () {
782 return $this->fileIoInstance;
786 * Setter for file I/O instance
788 * @param $fileIoInstance An instance to the file I/O sub-system
791 public final function setFileIoInstance (IoHandler $fileIoInstance) {
792 $this->fileIoInstance = $fileIoInstance;
796 * Protected setter for user instance
798 * @param $userInstance An instance of a user class
801 protected final function setUserInstance (ManageableAccount $userInstance) {
802 $this->userInstance = $userInstance;
806 * Getter for user instance
808 * @return $userInstance An instance of a user class
810 public final function getUserInstance () {
811 return $this->userInstance;
815 * Setter for controller instance (this surely breaks a bit the MVC patterm)
817 * @param $controllerInstance An instance of the controller
820 public final function setControllerInstance (Controller $controllerInstance) {
821 $this->controllerInstance = $controllerInstance;
825 * Getter for controller instance (this surely breaks a bit the MVC patterm)
827 * @return $controllerInstance An instance of the controller
829 public final function getControllerInstance () {
830 return $this->controllerInstance;
834 * Setter for RNG instance
836 * @param $rngInstance An instance of a random number generator (RNG)
839 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
840 $this->rngInstance = $rngInstance;
844 * Getter for RNG instance
846 * @return $rngInstance An instance of a random number generator (RNG)
848 public final function getRngInstance () {
849 return $this->rngInstance;
853 * Setter for Cryptable instance
855 * @param $cryptoInstance An instance of a Cryptable class
858 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
859 $this->cryptoInstance = $cryptoInstance;
863 * Getter for Cryptable instance
865 * @return $cryptoInstance An instance of a Cryptable class
867 public final function getCryptoInstance () {
868 return $this->cryptoInstance;
872 * Setter for the list instance
874 * @param $listInstance A list of Listable
877 protected final function setListInstance (Listable $listInstance) {
878 $this->listInstance = $listInstance;
882 * Getter for the list instance
884 * @return $listInstance A list of Listable
886 protected final function getListInstance () {
887 return $this->listInstance;
891 * Setter for the menu instance
893 * @param $menuInstance A RenderableMenu instance
896 protected final function setMenuInstance (RenderableMenu $menuInstance) {
897 $this->menuInstance = $menuInstance;
901 * Getter for the menu instance
903 * @return $menuInstance A RenderableMenu instance
905 protected final function getMenuInstance () {
906 return $this->menuInstance;
910 * Setter for image instance
912 * @param $imageInstance An instance of an image
915 public final function setImageInstance (BaseImage $imageInstance) {
916 $this->imageInstance = $imageInstance;
920 * Getter for image instance
922 * @return $imageInstance An instance of an image
924 public final function getImageInstance () {
925 return $this->imageInstance;
929 * Setter for stacker instance
931 * @param $stackerInstance An instance of an stacker
934 public final function setStackerInstance (Stackable $stackerInstance) {
935 $this->stackerInstance = $stackerInstance;
939 * Getter for stacker instance
941 * @return $stackerInstance An instance of an stacker
943 public final function getStackerInstance () {
944 return $this->stackerInstance;
948 * Setter for compressor instance
950 * @param $compressorInstance An instance of an compressor
953 public final function setCompressorInstance (Compressor $compressorInstance) {
954 $this->compressorInstance = $compressorInstance;
958 * Getter for compressor instance
960 * @return $compressorInstance An instance of an compressor
962 public final function getCompressorInstance () {
963 return $this->compressorInstance;
967 * Setter for Parseable instance
969 * @param $parserInstance An instance of an Parseable
972 public final function setParserInstance (Parseable $parserInstance) {
973 $this->parserInstance = $parserInstance;
977 * Getter for Parseable instance
979 * @return $parserInstance An instance of an Parseable
981 public final function getParserInstance () {
982 return $this->parserInstance;
986 * Setter for ProtocolHandler instance
988 * @param $protocolInstance An instance of an ProtocolHandler
991 public final function setProtocolInstance (ProtocolHandler $protocolInstance = NULL) {
992 $this->protocolInstance = $protocolInstance;
996 * Getter for ProtocolHandler instance
998 * @return $protocolInstance An instance of an ProtocolHandler
1000 public final function getProtocolInstance () {
1001 return $this->protocolInstance;
1005 * Setter for DatabaseWrapper instance
1007 * @param $wrapperInstance An instance of an DatabaseWrapper
1010 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1011 $this->wrapperInstance = $wrapperInstance;
1015 * Getter for DatabaseWrapper instance
1017 * @return $wrapperInstance An instance of an DatabaseWrapper
1019 public final function getWrapperInstance () {
1020 return $this->wrapperInstance;
1024 * Setter for socket resource
1026 * @param $socketResource A valid socket resource
1029 public final function setSocketResource ($socketResource) {
1030 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1031 $this->socketResource = $socketResource;
1035 * Getter for socket resource
1037 * @return $socketResource A valid socket resource
1039 public final function getSocketResource () {
1040 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1041 return $this->socketResource;
1045 * Setter for helper instance
1047 * @param $helperInstance An instance of a helper class
1050 protected final function setHelperInstance (Helper $helperInstance) {
1051 $this->helperInstance = $helperInstance;
1055 * Getter for helper instance
1057 * @return $helperInstance An instance of a helper class
1059 public final function getHelperInstance () {
1060 return $this->helperInstance;
1064 * Setter for a Sourceable instance
1066 * @param $sourceInstance The Sourceable instance
1069 protected final function setSourceInstance (Sourceable $sourceInstance) {
1070 $this->sourceInstance = $sourceInstance;
1074 * Getter for a Sourceable instance
1076 * @return $sourceInstance The Sourceable instance
1078 protected final function getSourceInstance () {
1079 return $this->sourceInstance;
1083 * Getter for a InputStreamable instance
1085 * @param $inputStreamInstance The InputStreamable instance
1087 protected final function getInputStreamInstance () {
1088 return $this->inputStreamInstance;
1092 * Setter for a InputStreamable instance
1094 * @param $inputStreamInstance The InputStreamable instance
1097 protected final function setInputStreamInstance (InputStreamable $inputStreamInstance) {
1098 $this->inputStreamInstance = $inputStreamInstance;
1102 * Getter for a OutputStreamable instance
1104 * @param $outputStreamInstance The OutputStreamable instance
1106 protected final function getOutputStreamInstance () {
1107 return $this->outputStreamInstance;
1111 * Setter for a OutputStreamable instance
1113 * @param $outputStreamInstance The OutputStreamable instance
1116 protected final function setOutputStreamInstance (OutputStreamable $outputStreamInstance) {
1117 $this->outputStreamInstance = $outputStreamInstance;
1121 * Setter for handler instance
1123 * @param $handlerInstance An instance of a Handleable class
1126 protected final function setHandlerInstance (Handleable $handlerInstance) {
1127 $this->handlerInstance = $handlerInstance;
1131 * Getter for handler instance
1133 * @return $handlerInstance A Networkable instance
1135 protected final function getHandlerInstance () {
1136 return $this->handlerInstance;
1140 * Setter for visitor instance
1142 * @param $visitorInstance A Visitor instance
1145 protected final function setVisitorInstance (Visitor $visitorInstance) {
1146 $this->visitorInstance = $visitorInstance;
1150 * Getter for visitor instance
1152 * @return $visitorInstance A Visitor instance
1154 protected final function getVisitorInstance () {
1155 return $this->visitorInstance;
1159 * Setter for DHT instance
1161 * @param $dhtInstance A Distributable instance
1164 protected final function setDhtInstance (Distributable $dhtInstance) {
1165 $this->dhtInstance = $dhtInstance;
1169 * Getter for DHT instance
1171 * @return $dhtInstance A Distributable instance
1173 protected final function getDhtInstance () {
1174 return $this->dhtInstance;
1178 * Setter for raw package Data
1180 * @param $packageData Raw package Data
1183 public final function setPackageData (array $packageData) {
1184 $this->packageData = $packageData;
1188 * Getter for raw package Data
1190 * @return $packageData Raw package Data
1192 public function getPackageData () {
1193 return $this->packageData;
1198 * Setter for Iterator instance
1200 * @param $iteratorInstance An instance of an Iterator
1203 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1204 $this->iteratorInstance = $iteratorInstance;
1208 * Getter for Iterator instance
1210 * @return $iteratorInstance An instance of an Iterator
1212 public final function getIteratorInstance () {
1213 return $this->iteratorInstance;
1217 * Checks whether an object equals this object. You should overwrite this
1218 * method to implement own equality checks
1220 * @param $objectInstance An instance of a FrameworkInterface object
1221 * @return $equals Whether both objects equals
1223 public function equals (FrameworkInterface $objectInstance) {
1226 $this->__toString() == $objectInstance->__toString()
1228 $this->hashCode() == $objectInstance->hashCode()
1231 // Return the result
1236 * Generates a generic hash code of this class. You should really overwrite
1237 * this method with your own hash code generator code. But keep KISS in mind.
1239 * @return $hashCode A generic hash code respresenting this whole class
1241 public function hashCode () {
1243 return crc32($this->__toString());
1247 * Formats computer generated price values into human-understandable formats
1248 * with thousand and decimal separators.
1250 * @param $value The in computer format value for a price
1251 * @param $currency The currency symbol (use HTML-valid characters!)
1252 * @param $decNum Number of decimals after commata
1253 * @return $price The for the current language formated price string
1254 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1255 * thousands separator
1258 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1259 // Are all required attriutes set?
1260 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1261 // Throw an exception
1262 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1266 $value = (float) $value;
1268 // Reformat the US number
1269 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1271 // Return as string...
1276 * Appends a trailing slash to a string
1278 * @param $str A string (maybe) without trailing slash
1279 * @return $str A string with an auto-appended trailing slash
1281 public final function addMissingTrailingSlash ($str) {
1282 // Is there a trailing slash?
1283 if (substr($str, -1, 1) != '/') {
1287 // Return string with trailing slash
1292 * Prepare the template engine (WebTemplateEngine by default) for a given
1293 * application helper instance (ApplicationHelper by default).
1295 * @param $applicationInstance An application helper instance or
1296 * null if we shall use the default
1297 * @return $templateInstance The template engine instance
1298 * @throws NullPointerException If the discovered application
1299 * instance is still null
1301 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1302 // Is the application instance set?
1303 if (is_null($applicationInstance)) {
1304 // Get the current instance
1305 $applicationInstance = $this->getApplicationInstance();
1308 if (is_null($applicationInstance)) {
1309 // Thrown an exception
1310 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1314 // Initialize the template engine
1315 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
1317 // Return the prepared instance
1318 return $templateInstance;
1322 * Debugs this instance by putting out it's full content
1324 * @param $message Optional message to show in debug output
1327 public final function debugInstance ($message = '') {
1328 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1329 restore_error_handler();
1334 // Is a message set?
1335 if (!empty($message)) {
1336 // Construct message
1337 $content = sprintf("<div class=\"debug_message\">Message: %s</div>\n", $message);
1340 // Generate the output
1341 $content .= sprintf("<pre>%s</pre>",
1344 print_r($this, true)
1350 ApplicationEntryPoint::app_exit(sprintf("<div class=\"debug_header\">%s debug output:</div><div class=\"debug_content\">%s</div>\nLoaded includes: <div class=\"debug_include_list\">%s</div>",
1351 $this->__toString(),
1353 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1358 * Replaces control characters with printable output
1360 * @param $str String with control characters
1361 * @return $str Replaced string
1363 protected function replaceControlCharacters ($str) {
1366 chr(13), '[r]', str_replace(
1367 chr(10), '[n]', str_replace(
1377 * Output a partial stub message for the caller method
1379 * @param $message An optional message to display
1382 protected function partialStub ($message = '') {
1383 // Get the backtrace
1384 $backtrace = debug_backtrace();
1386 // Generate the class::method string
1387 $methodName = 'UnknownClass->unknownMethod';
1388 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1389 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1392 // Construct the full message
1393 $stubMessage = sprintf('[%s:] Partial stub!',
1397 // Is the extra message given?
1398 if (!empty($message)) {
1399 // Then add it as well
1400 $stubMessage .= ' Message: ' . $message;
1403 // Debug instance is there?
1404 if (!is_null($this->getDebugInstance())) {
1405 // Output stub message
1406 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1409 trigger_error($stubMessage);
1414 * Outputs a debug backtrace and stops further script execution
1416 * @param $message An optional message to output
1417 * @param $doExit Whether exit the program (true is default)
1420 public function debugBackTrace ($message = '', $doExit = TRUE) {
1421 // Sorry, there is no other way getting this nice backtrace
1422 if (!empty($message)) {
1424 printf('Message: %s<br />' . chr(10), $message);
1428 debug_print_backtrace();
1432 if ($doExit === TRUE) {
1438 * Creates an instance of a debugger instance
1440 * @param $className Name of the class (currently unsupported)
1441 * @return $debugInstance An instance of a debugger class
1443 public final static function createDebugInstance ($className) {
1444 // Init debug instance
1445 $debugInstance = NULL;
1449 // Get a debugger instance
1450 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_class'));
1451 } catch (NullPointerException $e) {
1452 // Didn't work, no instance there
1453 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1456 // Empty string should be ignored and used for testing the middleware
1457 DebugMiddleware::getSelfInstance()->output('');
1460 return $debugInstance;
1464 * Outputs a debug message whether to debug instance (should be set!) or
1465 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1466 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1468 * @param $message Message we shall send out...
1469 * @param $doPrint Whether print or die here (default: print)
1470 * @paran $stripTags Whether to strip tags (default: false)
1473 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1474 // Set debug instance to NULL
1475 $debugInstance = NULL;
1479 // Get debug instance
1480 $debugInstance = $this->getDebugInstance();
1481 } catch (NullPointerException $e) {
1482 // The debug instance is not set (yet)
1485 // Is the debug instance there?
1486 if (is_object($debugInstance)) {
1487 // Use debug output handler
1488 $debugInstance->output($message, $stripTags);
1490 if ($doPrint === FALSE) {
1491 // Die here if not printed
1495 // Are debug times enabled?
1496 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1498 $message = $this->getPrintableExecutionTime() . $message;
1502 if ($doPrint === TRUE) {
1504 print($message . chr(10));
1513 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1515 * @param $str The string, what ever it is needs to be converted
1516 * @return $className Generated class name
1518 public function convertToClassName ($str) {
1522 // Convert all dashes in underscores
1523 $str = $this->convertDashesToUnderscores($str);
1525 // Now use that underscores to get classname parts for hungarian style
1526 foreach (explode('_', $str) as $strPart) {
1527 // Make the class name part lower case and first upper case
1528 $className .= ucfirst(strtolower($strPart));
1531 // Return class name
1536 * Converts dashes to underscores, e.g. useable for configuration entries
1538 * @param $str The string with maybe dashes inside
1539 * @return $str The converted string with no dashed, but underscores
1541 public final function convertDashesToUnderscores ($str) {
1543 $str = str_replace('-', '_', $str);
1545 // Return converted string
1550 * Marks up the code by adding e.g. line numbers
1552 * @param $phpCode Unmarked PHP code
1553 * @return $markedCode Marked PHP code
1555 public function markupCode ($phpCode) {
1560 $errorArray = error_get_last();
1562 // Init the code with error message
1563 if (is_array($errorArray)) {
1565 $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>',
1566 basename($errorArray['file']),
1567 $errorArray['line'],
1568 $errorArray['message'],
1573 // Add line number to the code
1574 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1576 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1578 htmlentities($code, ENT_QUOTES)
1587 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1588 * beatiful for web-based front-ends. If null is given a message id
1589 * null_timestamp will be resolved and returned.
1591 * @param $timestamp Timestamp to prepare (filter) for display
1592 * @return $readable A readable timestamp
1594 public function doFilterFormatTimestamp ($timestamp) {
1595 // Default value to return
1598 // Is the timestamp null?
1599 if (is_null($timestamp)) {
1600 // Get a message string
1601 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1603 switch ($this->getLanguageInstance()->getLanguageCode()) {
1604 case 'de': // German format is a bit different to default
1605 // Split the GMT stamp up
1606 $dateTime = explode(' ', $timestamp );
1607 $dateArray = explode('-', $dateTime[0]);
1608 $timeArray = explode(':', $dateTime[1]);
1610 // Construct the timestamp
1611 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1621 default: // Default is pass-through
1622 $readable = $timestamp;
1632 * Filter a given number into a localized number
1634 * @param $value The raw value from e.g. database
1635 * @return $localized Localized value
1637 public function doFilterFormatNumber ($value) {
1638 // Generate it from config and localize dependencies
1639 switch ($this->getLanguageInstance()->getLanguageCode()) {
1640 case 'de': // German format is a bit different to default
1641 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1644 default: // US, etc.
1645 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1654 * "Getter" for databse entry
1656 * @return $entry An array with database entries
1657 * @throws NullPointerException If the database result is not found
1658 * @throws InvalidDatabaseResultException If the database result is invalid
1660 protected final function getDatabaseEntry () {
1661 // Is there an instance?
1662 if (is_null($this->getResultInstance())) {
1663 // Throw an exception here
1664 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1668 $this->getResultInstance()->rewind();
1670 // Do we have an entry?
1671 if ($this->getResultInstance()->valid() === FALSE) {
1672 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1676 $this->getResultInstance()->next();
1679 $entry = $this->getResultInstance()->current();
1686 * Getter for field name
1688 * @param $fieldName Field name which we shall get
1689 * @return $fieldValue Field value from the user
1690 * @throws NullPointerException If the result instance is null
1692 public final function getField ($fieldName) {
1693 // Default field value
1696 // Get result instance
1697 $resultInstance = $this->getResultInstance();
1699 // Is this instance null?
1700 if (is_null($resultInstance)) {
1701 // Then the user instance is no longer valid (expired cookies?)
1702 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1705 // Get current array
1706 $fieldArray = $resultInstance->current();
1707 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1709 // Convert dashes to underscore
1710 $fieldName = $this->convertDashesToUnderscores($fieldName);
1712 // Does the field exist?
1713 if (isset($fieldArray[$fieldName])) {
1715 $fieldValue = $fieldArray[$fieldName];
1717 // Missing field entry, may require debugging
1718 self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ':fieldname=' . $fieldName . ' not found!');
1726 * Flushs all pending updates to the database layer
1730 public function flushPendingUpdates () {
1731 // Get result instance
1732 $resultInstance = $this->getResultInstance();
1734 // Do we have data to update?
1735 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1736 // Get wrapper class name config entry
1737 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1739 // Create object instance
1740 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1742 // Yes, then send the whole result to the database layer
1743 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1748 * Outputs a deprecation warning to the developer.
1750 * @param $message The message we shall output to the developer
1752 * @todo Write a logging mechanism for productive mode
1754 public function deprecationWarning ($message) {
1755 // Is developer mode active?
1756 if (defined('DEVELOPER')) {
1757 // Debug instance is there?
1758 if (!is_null($this->getDebugInstance())) {
1759 // Output stub message
1760 self::createDebugInstance(__CLASS__)->debugOutput($message);
1763 trigger_error($message . "<br />\n");
1766 // @TODO Finish this part!
1767 $this->partialStub('Developer mode inactive. Message:' . $message);
1772 * Checks whether the given PHP extension is loaded
1774 * @param $phpExtension The PHP extension we shall check
1775 * @return $isLoaded Whether the PHP extension is loaded
1777 public final function isPhpExtensionLoaded ($phpExtension) {
1779 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1786 * "Getter" as a time() replacement but with milliseconds. You should use this
1787 * method instead of the encapsulated getimeofday() function.
1789 * @return $milliTime Timestamp with milliseconds
1791 public function getMilliTime () {
1792 // Get the time of day as float
1793 $milliTime = gettimeofday(true);
1800 * Idles (sleeps) for given milliseconds
1802 * @return $hasSlept Whether it goes fine
1804 public function idle ($milliSeconds) {
1805 // Sleep is fine by default
1808 // Idle so long with found function
1809 if (function_exists('time_sleep_until')) {
1810 // Get current time and add idle time
1811 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1813 // New PHP 5.1.0 function found, ignore errors
1814 $hasSlept = @time_sleep_until($sleepUntil);
1817 * My Sun station doesn't have that function even with latest PHP
1820 usleep($milliSeconds * 1000);
1827 * Converts a hexadecimal string, even with negative sign as first string to
1828 * a decimal number using BC functions.
1830 * This work is based on comment #86673 on php.net documentation page at:
1831 * <http://de.php.net/manual/en/function.dechex.php#86673>
1833 * @param $hex Hexadecimal string
1834 * @return $dec Decimal number
1836 protected function hex2dec ($hex) {
1837 // Convert to all lower-case
1838 $hex = strtolower($hex);
1840 // Detect sign (negative/positive numbers)
1842 if (substr($hex, 0, 1) == '-') {
1844 $hex = substr($hex, 1);
1847 // Decode the hexadecimal string into a decimal number
1849 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1850 $factor = self::$hexdec[substr($hex, $i, 1)];
1851 $dec = bcadd($dec, bcmul($factor, $e));
1854 // Return the decimal number
1855 return $sign . $dec;
1859 * Converts even very large decimal numbers, also signed, to a hexadecimal
1862 * This work is based on comment #97756 on php.net documentation page at:
1863 * <http://de.php.net/manual/en/function.hexdec.php#97756>
1865 * @param $dec Decimal number, even with negative sign
1866 * @param $maxLength Optional maximum length of the string
1867 * @return $hex Hexadecimal string
1869 protected function dec2hex ($dec, $maxLength = 0) {
1870 // maxLength can be zero or devideable by 2
1871 assert(($maxLength == 0) || (($maxLength % 2) == 0));
1873 // Detect sign (negative/positive numbers)
1880 // Encode the decimal number into a hexadecimal string
1883 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
1885 } while ($dec >= 1);
1888 * Leading zeros are required for hex-decimal "numbers". In some
1889 * situations more leading zeros are wanted, so check for both
1892 if ($maxLength > 0) {
1893 // Prepend more zeros
1894 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
1895 } elseif ((strlen($hex) % 2) != 0) {
1896 // Only make string's length dividable by 2
1900 // Return the hexadecimal string
1901 return $sign . $hex;
1905 * Converts a ASCII string (0 to 255) into a decimal number.
1907 * @param $asc The ASCII string to be converted
1908 * @return $dec Decimal number
1910 protected function asc2dec ($asc) {
1911 // Convert it into a hexadecimal number
1912 $hex = bin2hex($asc);
1914 // And back into a decimal number
1915 $dec = $this->hex2dec($hex);
1922 * Converts a decimal number into an ASCII string.
1924 * @param $dec Decimal number
1925 * @return $asc An ASCII string
1927 protected function dec2asc ($dec) {
1928 // First convert the number into a hexadecimal string
1929 $hex = $this->dec2hex($dec);
1931 // Then convert it into the ASCII string
1932 $asc = $this->hex2asc($hex);
1939 * Converts a hexadecimal number into an ASCII string. Negative numbers
1942 * @param $hex Hexadecimal string
1943 * @return $asc An ASCII string
1945 protected function hex2asc ($hex) {
1946 // Check for length, it must be devideable by 2
1947 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
1948 assert((strlen($hex) % 2) == 0);
1952 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
1953 // Get the decimal number of the chunk
1954 $part = hexdec(substr($hex, $idx, 2));
1956 // Add it to the final string
1960 // Return the final string
1965 * Checks whether the given encoded data was encoded with Base64
1967 * @param $encodedData Encoded data we shall check
1968 * @return $isBase64 Whether the encoded data is Base64
1970 protected function isBase64Encoded ($encodedData) {
1972 $isBase64 = (@base64_decode($encodedData, true) !== FALSE);
1979 * "Getter" to get response/request type from analysis of the system.
1981 * @return $responseType Analyzed response type
1983 protected function getResponseTypeFromSystem () {
1984 // Default is console
1985 $responseType = 'console';
1987 // Is 'HTTP_HOST' set?
1988 if (isset($_SERVER['HTTP_HOST'])) {
1989 // Then it is a HTTP response/request
1990 $responseType = 'http';
1994 return $responseType;
1998 * Gets a cache key from Criteria instance
2000 * @param $criteriaInstance An instance of a Criteria class
2001 * @param $onlyKeys Only use these keys for a cache key
2002 * @return $cacheKey A cache key suitable for lookup/storage purposes
2004 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2006 $cacheKey = sprintf("%s@%s",
2007 $this->__toString(),
2008 $criteriaInstance->getCacheKey($onlyKeys)
2012 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2017 * Getter for startup time in miliseconds
2019 * @return $startupTime Startup time in miliseconds
2021 protected function getStartupTime () {
2022 return self::$startupTime;
2026 * "Getter" for a printable currently execution time in nice braces
2028 * @return $executionTime Current execution time in nice braces
2030 protected function getPrintableExecutionTime () {
2031 // Caculate the execution time
2032 $executionTime = microtime(true) - $this->getStartupTime();
2034 // Pack it in nice braces
2035 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2038 return $executionTime;
2042 * Hashes a given string with a simple but stronger hash function (no salts)
2044 * @param $str The string to be hashed
2045 * @return $hash The hash from string $str
2047 public function hashString ($str) {
2048 // Hash given string with (better secure) hasher
2049 $hash = mhash(MHASH_SHA256, $str);
2056 * Checks whether the given number is really a number (only chars 0-9).
2058 * @param $num A string consisting only chars between 0 and 9
2059 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2060 * @param $assertMismatch Whether to assert mismatches
2061 * @return $ret The (hopefully) secured numbered value
2063 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2064 // Filter all numbers out
2065 $ret = preg_replace('/[^0123456789]/', '', $num);
2068 if ($castValue === TRUE) {
2069 // Cast to biggest numeric type
2070 $ret = (double) $ret;
2073 // Assert only if requested
2074 if ($assertMismatch === TRUE) {
2075 // Has the whole value changed?
2076 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2084 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2086 * @param $num A string consisting only chars between 0 and 9
2087 * @param $assertMismatch Whether to assert mismatches
2088 * @return $ret The (hopefully) secured hext-numbered value
2090 public function hexval ($num, $assertMismatch = FALSE) {
2091 // Filter all numbers out
2092 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2094 // Assert only if requested
2095 if ($assertMismatch === TRUE) {
2096 // Has the whole value changed?
2097 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2105 * Checks whether start/end marker are set
2107 * @param $data Data to be checked
2108 * @return $isset Whether start/end marker are set
2110 public final function ifStartEndMarkersSet ($data) {
2112 $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));
2114 // ... and return it
2119 * Determines if a key is set in the generic array
2121 * @param $keyGroup Main group for the key
2122 * @param $subGroup Sub group for the key
2123 * @param $key Key to check
2124 * @return $isset Whether the given key is set
2126 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2128 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2135 * Determines if an element is set in the generic array
2137 * @param $keyGroup Main group for the key
2138 * @param $subGroup Sub group for the key
2139 * @param $key Key to check
2140 * @param $element Element to check
2141 * @return $isset Whether the given key is set
2143 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2145 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2152 * Determines if a group is set in the generic array
2154 * @param $keyGroup Main group
2155 * @param $subGroup Sub group
2156 * @return $isset Whether the given group is set
2158 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2160 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2167 * Getter for sub key group
2169 * @param $keyGroup Main key group
2170 * @param $subGroup Sub key group
2171 * @return $array An array with all array elements
2173 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2175 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2176 // No, then abort here
2177 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2181 return $this->genericArray[$keyGroup][$subGroup];
2185 * Unsets a given key in generic array
2187 * @param $keyGroup Main group for the key
2188 * @param $subGroup Sub group for the key
2189 * @param $key Key to unset
2192 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key) {
2194 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2198 * Append a string to a given generic array key
2200 * @param $keyGroup Main group for the key
2201 * @param $subGroup Sub group for the key
2202 * @param $key Key to unset
2203 * @param $value Value to add/append
2206 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2207 // Is it already there?
2208 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2210 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2213 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2218 * Pushes an element to a generic key
2220 * @param $keyGroup Main group for the key
2221 * @param $subGroup Sub group for the key
2222 * @param $key Key to use
2223 * @param $value Value to add/append
2224 * @return $count Number of array elements
2226 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $value) {
2228 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2230 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2234 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2241 * Sets a value in given generic array key/element
2243 * @param $keyGroup Main group for the key
2244 * @param $subGroup Sub group for the key
2245 * @param $key Key to set
2246 * @param $element Element to set
2247 * @param $value Value to set
2250 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2252 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2256 * Pops an element from a generic group
2258 * @param $keyGroup Main group for the key
2259 * @param $subGroup Sub group for the key
2260 * @param $key Key to unset
2261 * @return $value Last "popped" value
2263 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2265 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2267 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2271 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2278 * Shifts an element from a generic group
2280 * @param $keyGroup Main group for the key
2281 * @param $subGroup Sub group for the key
2282 * @param $key Key to unset
2283 * @return $value Last "popped" value
2285 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2287 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2289 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2293 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2300 * Count generic array group
2302 * @param $keyGroup Main group for the key
2303 * @return $count Count of given group
2305 protected final function countGenericArray ($keyGroup) {
2307 if (!isset($this->genericArray[$keyGroup])) {
2309 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2313 $count = count($this->genericArray[$keyGroup]);
2320 * Count generic array sub group
2322 * @param $keyGroup Main group for the key
2323 * @param $subGroup Sub group for the key
2324 * @return $count Count of given group
2326 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2328 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2330 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2334 $count = count($this->genericArray[$keyGroup][$subGroup]);
2341 * Count generic array elements
2343 * @param $keyGroup Main group for the key
2344 * @param $subGroup Sub group for the key
2345 * @para $key Key to count
2346 * @return $count Count of given key
2348 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2350 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup)) {
2352 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2353 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2355 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2359 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2366 * Getter for whole generic group array
2368 * @param $keyGroup Key group to get
2369 * @return $array Whole generic array group
2371 protected final function getGenericArray ($keyGroup) {
2373 if (!isset($this->genericArray[$keyGroup])) {
2375 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2379 return $this->genericArray[$keyGroup];
2383 * Getter for generic array key
2385 * @param $keyGroup Key group to get
2386 * @param $subGroup Sub group for the key
2387 * @param $key Key to unset
2388 * @return $value Mixed value from generic array element
2390 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2392 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2394 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2398 return $this->genericArray[$keyGroup][$subGroup][$key];
2402 * Getter for generic array element
2404 * @param $keyGroup Key group to get
2405 * @param $subGroup Sub group for the key
2406 * @param $key Key to look for
2407 * @param $element Element to look for
2408 * @return $value Mixed value from generic array element
2410 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2412 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2414 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2418 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2422 * Checks if a given sub group is valid (array)
2424 * @param $keyGroup Key group to get
2425 * @param $subGroup Sub group for the key
2426 * @return $isValid Whether given sub group is valid
2428 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2430 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));