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 {
27 * Separator for header data
29 const SEPARATOR_HEADER_DATA = 0x01;
32 * Separator header->entries
34 const SEPARATOR_HEADER_ENTRIES = 0x02;
37 * Separator hash->name
39 const SEPARATOR_HASH_NAME = 0x03;
42 * Separator entry->entry
44 const SEPARATOR_ENTRIES = 0x04;
47 * Separator type->position
49 const SEPARATOR_TYPE_POSITION = 0x05;
54 const LENGTH_COUNT = 20;
59 const LENGTH_POSITION = 20;
64 const LENGTH_NAME = 10;
67 * Maximum length of entry type
69 const LENGTH_TYPE = 20;
74 private $realClass = 'BaseFrameworkSystem';
77 * Instance of a request class
79 private $requestInstance = NULL;
82 * Instance of a response class
84 private $responseInstance = NULL;
87 * Search criteria instance
89 private $searchInstance = NULL;
92 * Update criteria instance
94 private $updateInstance = NULL;
97 * The file I/O instance for the template loader
99 private $fileIoInstance = NULL;
104 private $resolverInstance = NULL;
107 * Template engine instance
109 private $templateInstance = NULL;
112 * Database result instance
114 private $resultInstance = NULL;
117 * Instance for user class
119 private $userInstance = NULL;
122 * A controller instance
124 private $controllerInstance = NULL;
129 private $rngInstance = NULL;
132 * Instance of a crypto helper
134 private $cryptoInstance = NULL;
137 * Instance of an Iterator class
139 private $iteratorInstance = NULL;
142 * Instance of the list
144 private $listInstance = NULL;
149 private $menuInstance = NULL;
152 * Instance of the image
154 private $imageInstance = NULL;
157 * Instance of the stacker
159 private $stackerInstance = NULL;
162 * A Compressor instance
164 private $compressorInstance = NULL;
167 * A Parseable instance
169 private $parserInstance = NULL;
172 * A ProtocolHandler instance
174 private $protocolInstance = NULL;
177 * A database wrapper instance
179 private $databaseInstance = NULL;
182 * A helper instance for the form
184 private $helperInstance = NULL;
187 * An instance of a Sourceable class
189 private $sourceInstance = NULL;
192 * An instance of a InputStream class
194 private $inputStreamInstance = NULL;
197 * An instance of a OutputStream class
199 private $outputStreamInstance = NULL;
202 * Networkable handler instance
204 private $handlerInstance = NULL;
207 * Visitor handler instance
209 private $visitorInstance = NULL;
214 private $dhtInstance = NULL;
217 * An instance of a database wrapper class
219 private $wrapperInstance = NULL;
222 * An instance of a file I/O pointer class (not handler)
224 private $pointerInstance = NULL;
227 * An instance of an Indexable class
229 private $indexInstance = NULL;
232 * An instance of a Block class
234 private $blockInstance = NULL;
237 * Thousands separator
239 private $thousands = '.'; // German
244 private $decimals = ','; // German
249 private $socketResource = FALSE;
254 private $packageData = array();
259 private $genericArray = array();
262 * Length of output from hash()
264 private static $hashLength = NULL;
267 * Counter for total entries
269 private $totalEntries = 0;
272 * Current seek position
274 private $seekPosition = 0;
279 private $headerSize = 0;
284 private $header = array();
287 * Seek positions for gaps ("fragmentation")
289 private $gaps = array();
292 * Seek positions for damaged entries (e.g. mismatching hash sum, ...)
294 private $damagedEntries = array();
296 /***********************
297 * Exception codes.... *
298 ***********************/
300 // @todo Try to clean these constants up
301 const EXCEPTION_IS_NULL_POINTER = 0x001;
302 const EXCEPTION_IS_NO_OBJECT = 0x002;
303 const EXCEPTION_IS_NO_ARRAY = 0x003;
304 const EXCEPTION_MISSING_METHOD = 0x004;
305 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
306 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
307 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
308 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
309 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
310 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
311 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
312 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
313 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
314 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
315 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
316 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
317 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
318 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
319 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
320 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
321 const EXCEPTION_PATH_NOT_FOUND = 0x015;
322 const EXCEPTION_INVALID_PATH_NAME = 0x016;
323 const EXCEPTION_READ_PROTECED_PATH = 0x017;
324 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
325 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
326 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
327 const EXCEPTION_INVALID_RESOURCE = 0x01b;
328 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
329 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
330 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
331 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
332 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
333 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
334 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
335 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
336 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
337 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
338 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
339 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
340 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
341 const EXCEPTION_INVALID_STRING = 0x029;
342 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
343 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
344 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
345 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
346 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
347 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
348 const EXCEPTION_MISSING_ELEMENT = 0x030;
349 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
350 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
351 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
352 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
353 const EXCEPTION_FATAL_ERROR = 0x035;
354 const EXCEPTION_FILE_NOT_FOUND = 0x036;
355 const EXCEPTION_ASSERTION_FAILED = 0x037;
356 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
357 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
358 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03a;
361 * Hexadecimal->Decimal translation array
363 private static $hexdec = array(
383 * Decimal->hexadecimal translation array
385 private static $dechex = array(
405 * Startup time in miliseconds
407 private static $startupTime = 0;
410 * Protected super constructor
412 * @param $className Name of the class
415 protected function __construct ($className) {
417 $this->setRealClass($className);
419 // Set configuration instance if no registry ...
420 if (!$this instanceof Register) {
421 // ... because registries doesn't need to be configured
422 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
425 // Is the startup time set? (0 cannot be TRUE anymore)
426 if (self::$startupTime == 0) {
428 self::$startupTime = microtime(TRUE);
433 * Destructor for all classes
437 public function __destruct () {
438 // Flush any updated entries to the database
439 $this->flushPendingUpdates();
441 // Is this object already destroyed?
442 if ($this->__toString() != 'DestructedObject') {
443 // Destroy all informations about this class but keep some text about it alive
444 $this->setRealClass('DestructedObject');
445 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
446 // Already destructed object
447 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
452 // Do not call this twice
453 trigger_error(__METHOD__ . ': Called twice.');
459 * The __call() method where all non-implemented methods end up
461 * @param $methodName Name of the missing method
462 * @args $args Arguments passed to the method
465 public final function __call ($methodName, $args) {
466 return self::__callStatic($methodName, $args);
470 * The __callStatic() method where all non-implemented static methods end up
472 * @param $methodName Name of the missing method
473 * @args $args Arguments passed to the method
476 public static final function __callStatic ($methodName, $args) {
477 // Init argument string
480 // Is it empty or an array?
483 $argsString = 'NULL';
484 } elseif (is_array($args)) {
485 // Some arguments are there
486 foreach ($args as $arg) {
487 // Add the value itself if not array. This prevents 'array to string conversion' message
488 if (is_array($arg)) {
489 $argsString .= 'Array';
494 // Add data about the argument
495 $argsString .= ' (' . gettype($arg);
497 if (is_string($arg)) {
498 // Add length for strings
499 $argsString .= ', ' . strlen($arg);
500 } elseif (is_array($arg)) {
501 // .. or size if array
502 $argsString .= ', ' . count($arg);
503 } elseif ($arg === TRUE) {
504 // ... is boolean 'TRUE'
505 $argsString .= ', TRUE';
506 } elseif ($arg === FALSE) {
507 // ... is boolean 'FALSE'
508 $argsString .= ', FALSE';
512 $argsString .= '), ';
516 if (substr($argsString, -2, 1) == ',') {
517 $argsString = substr($argsString, 0, -2);
520 // Invalid arguments!
521 $argsString = '!INVALID:' . gettype($args) . '!';
524 // Output stub message
525 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
526 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
536 * Getter for $realClass
538 * @return $realClass The name of the real class (not BaseFrameworkSystem)
540 public function __toString () {
541 return $this->realClass;
545 * Magic function to catch setting of missing but set class fields/attributes
547 * @param $name Name of the field/attribute
548 * @param $value Value to store
551 public final function __set ($name, $value) {
552 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
555 print_r($value, TRUE)
560 * Magic function to catch getting of missing fields/attributes
562 * @param $name Name of the field/attribute
565 public final function __get ($name) {
566 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
572 * Magic function to catch unsetting of missing fields/attributes
574 * @param $name Name of the field/attribute
577 public final function __unset ($name) {
578 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
584 * Setter for the real class name
586 * @param $realClass Class name (string)
589 public final function setRealClass ($realClass) {
591 $this->realClass = (string) $realClass;
595 * Setter for database result instance
597 * @param $resultInstance An instance of a database result class
599 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
601 protected final function setResultInstance (SearchableResult $resultInstance) {
602 $this->resultInstance = $resultInstance;
606 * Getter for database result instance
608 * @return $resultInstance An instance of a database result class
610 public final function getResultInstance () {
611 return $this->resultInstance;
615 * Setter for template engine instances
617 * @param $templateInstance An instance of a template engine class
620 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
621 $this->templateInstance = $templateInstance;
625 * Getter for template engine instances
627 * @return $templateInstance An instance of a template engine class
629 protected final function getTemplateInstance () {
630 return $this->templateInstance;
634 * Setter for search instance
636 * @param $searchInstance Searchable criteria instance
639 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
640 $this->searchInstance = $searchInstance;
644 * Getter for search instance
646 * @return $searchInstance Searchable criteria instance
648 public final function getSearchInstance () {
649 return $this->searchInstance;
653 * Setter for update instance
655 * @param $updateInstance Searchable criteria instance
658 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
659 $this->updateInstance = $updateInstance;
663 * Getter for update instance
665 * @return $updateInstance Updateable criteria instance
667 public final function getUpdateInstance () {
668 return $this->updateInstance;
672 * Setter for resolver instance
674 * @param $resolverInstance Instance of a command resolver class
677 public final function setResolverInstance (Resolver $resolverInstance) {
678 $this->resolverInstance = $resolverInstance;
682 * Getter for resolver instance
684 * @return $resolverInstance Instance of a command resolver class
686 public final function getResolverInstance () {
687 return $this->resolverInstance;
691 * Setter for language instance
693 * @param $configInstance The configuration instance which shall
694 * be FrameworkConfiguration
697 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
698 Registry::getRegistry()->addInstance('config', $configInstance);
702 * Getter for configuration instance
704 * @return $configInstance Configuration instance
706 public final function getConfigInstance () {
707 $configInstance = Registry::getRegistry()->getInstance('config');
708 return $configInstance;
712 * Setter for debug instance
714 * @param $debugInstance The instance for debug output class
717 public final function setDebugInstance (DebugMiddleware $debugInstance) {
718 Registry::getRegistry()->addInstance('debug', $debugInstance);
722 * Getter for debug instance
724 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
726 public final function getDebugInstance () {
727 // Get debug instance
728 $debugInstance = Registry::getRegistry()->getInstance('debug');
731 return $debugInstance;
735 * Setter for web output instance
737 * @param $webInstance The instance for web output class
740 public final function setWebOutputInstance (OutputStreamer $webInstance) {
741 Registry::getRegistry()->addInstance('web_output', $webInstance);
745 * Getter for web output instance
747 * @return $webOutputInstance - Instance to class WebOutput
749 public final function getWebOutputInstance () {
750 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
751 return $webOutputInstance;
755 * Setter for database instance
757 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
760 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
761 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
765 * Getter for database layer
767 * @return $databaseInstance The database layer instance
769 public final function getDatabaseInstance () {
771 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
774 return $databaseInstance;
778 * Setter for compressor channel
780 * @param $compressorInstance An instance of CompressorChannel
783 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
784 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
788 * Getter for compressor channel
790 * @return $compressorInstance The compressor channel
792 public final function getCompressorChannel () {
793 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
794 return $compressorInstance;
798 * Protected getter for a manageable application helper class
800 * @return $applicationInstance An instance of a manageable application helper class
802 protected final function getApplicationInstance () {
803 $applicationInstance = Registry::getRegistry()->getInstance('application');
804 return $applicationInstance;
808 * Setter for a manageable application helper class
810 * @param $applicationInstance An instance of a manageable application helper class
813 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
814 Registry::getRegistry()->addInstance('application', $applicationInstance);
818 * Setter for request instance
820 * @param $requestInstance An instance of a Requestable class
823 public final function setRequestInstance (Requestable $requestInstance) {
824 $this->requestInstance = $requestInstance;
828 * Getter for request instance
830 * @return $requestInstance An instance of a Requestable class
832 public final function getRequestInstance () {
833 return $this->requestInstance;
837 * Setter for response instance
839 * @param $responseInstance An instance of a Responseable class
842 public final function setResponseInstance (Responseable $responseInstance) {
843 $this->responseInstance = $responseInstance;
847 * Getter for response instance
849 * @return $responseInstance An instance of a Responseable class
851 public final function getResponseInstance () {
852 return $this->responseInstance;
856 * Private getter for language instance
858 * @return $langInstance An instance to the language sub-system
860 protected final function getLanguageInstance () {
861 $langInstance = Registry::getRegistry()->getInstance('language');
862 return $langInstance;
866 * Setter for language instance
868 * @param $langInstance An instance to the language sub-system
870 * @see LanguageSystem
872 public final function setLanguageInstance (ManageableLanguage $langInstance) {
873 Registry::getRegistry()->addInstance('language', $langInstance);
877 * Private getter for file IO instance
879 * @return $fileIoInstance An instance to the file I/O sub-system
881 protected final function getFileIoInstance () {
882 return $this->fileIoInstance;
886 * Setter for file I/O instance
888 * @param $fileIoInstance An instance to the file I/O sub-system
891 public final function setFileIoInstance (IoHandler $fileIoInstance) {
892 $this->fileIoInstance = $fileIoInstance;
896 * Protected setter for user instance
898 * @param $userInstance An instance of a user class
901 protected final function setUserInstance (ManageableAccount $userInstance) {
902 $this->userInstance = $userInstance;
906 * Getter for user instance
908 * @return $userInstance An instance of a user class
910 public final function getUserInstance () {
911 return $this->userInstance;
915 * Setter for controller instance (this surely breaks a bit the MVC patterm)
917 * @param $controllerInstance An instance of the controller
920 public final function setControllerInstance (Controller $controllerInstance) {
921 $this->controllerInstance = $controllerInstance;
925 * Getter for controller instance (this surely breaks a bit the MVC patterm)
927 * @return $controllerInstance An instance of the controller
929 public final function getControllerInstance () {
930 return $this->controllerInstance;
934 * Setter for RNG instance
936 * @param $rngInstance An instance of a random number generator (RNG)
939 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
940 $this->rngInstance = $rngInstance;
944 * Getter for RNG instance
946 * @return $rngInstance An instance of a random number generator (RNG)
948 public final function getRngInstance () {
949 return $this->rngInstance;
953 * Setter for Cryptable instance
955 * @param $cryptoInstance An instance of a Cryptable class
958 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
959 $this->cryptoInstance = $cryptoInstance;
963 * Getter for Cryptable instance
965 * @return $cryptoInstance An instance of a Cryptable class
967 public final function getCryptoInstance () {
968 return $this->cryptoInstance;
972 * Setter for the list instance
974 * @param $listInstance A list of Listable
977 protected final function setListInstance (Listable $listInstance) {
978 $this->listInstance = $listInstance;
982 * Getter for the list instance
984 * @return $listInstance A list of Listable
986 protected final function getListInstance () {
987 return $this->listInstance;
991 * Setter for the menu instance
993 * @param $menuInstance A RenderableMenu instance
996 protected final function setMenuInstance (RenderableMenu $menuInstance) {
997 $this->menuInstance = $menuInstance;
1001 * Getter for the menu instance
1003 * @return $menuInstance A RenderableMenu instance
1005 protected final function getMenuInstance () {
1006 return $this->menuInstance;
1010 * Setter for image instance
1012 * @param $imageInstance An instance of an image
1015 public final function setImageInstance (BaseImage $imageInstance) {
1016 $this->imageInstance = $imageInstance;
1020 * Getter for image instance
1022 * @return $imageInstance An instance of an image
1024 public final function getImageInstance () {
1025 return $this->imageInstance;
1029 * Setter for stacker instance
1031 * @param $stackerInstance An instance of an stacker
1034 public final function setStackerInstance (Stackable $stackerInstance) {
1035 $this->stackerInstance = $stackerInstance;
1039 * Getter for stacker instance
1041 * @return $stackerInstance An instance of an stacker
1043 public final function getStackerInstance () {
1044 return $this->stackerInstance;
1048 * Setter for compressor instance
1050 * @param $compressorInstance An instance of an compressor
1053 public final function setCompressorInstance (Compressor $compressorInstance) {
1054 $this->compressorInstance = $compressorInstance;
1058 * Getter for compressor instance
1060 * @return $compressorInstance An instance of an compressor
1062 public final function getCompressorInstance () {
1063 return $this->compressorInstance;
1067 * Setter for Parseable instance
1069 * @param $parserInstance An instance of an Parseable
1072 public final function setParserInstance (Parseable $parserInstance) {
1073 $this->parserInstance = $parserInstance;
1077 * Getter for Parseable instance
1079 * @return $parserInstance An instance of an Parseable
1081 public final function getParserInstance () {
1082 return $this->parserInstance;
1086 * Setter for ProtocolHandler instance
1088 * @param $protocolInstance An instance of an ProtocolHandler
1091 public final function setProtocolInstance (ProtocolHandler $protocolInstance = NULL) {
1092 $this->protocolInstance = $protocolInstance;
1096 * Getter for ProtocolHandler instance
1098 * @return $protocolInstance An instance of an ProtocolHandler
1100 public final function getProtocolInstance () {
1101 return $this->protocolInstance;
1105 * Setter for DatabaseWrapper instance
1107 * @param $wrapperInstance An instance of an DatabaseWrapper
1110 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1111 $this->wrapperInstance = $wrapperInstance;
1115 * Getter for DatabaseWrapper instance
1117 * @return $wrapperInstance An instance of an DatabaseWrapper
1119 public final function getWrapperInstance () {
1120 return $this->wrapperInstance;
1124 * Setter for socket resource
1126 * @param $socketResource A valid socket resource
1129 public final function setSocketResource ($socketResource) {
1130 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1131 $this->socketResource = $socketResource;
1135 * Getter for socket resource
1137 * @return $socketResource A valid socket resource
1139 public final function getSocketResource () {
1140 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1141 return $this->socketResource;
1145 * Setter for helper instance
1147 * @param $helperInstance An instance of a helper class
1150 protected final function setHelperInstance (Helper $helperInstance) {
1151 $this->helperInstance = $helperInstance;
1155 * Getter for helper instance
1157 * @return $helperInstance An instance of a helper class
1159 public final function getHelperInstance () {
1160 return $this->helperInstance;
1164 * Setter for a Sourceable instance
1166 * @param $sourceInstance The Sourceable instance
1169 protected final function setSourceInstance (Sourceable $sourceInstance) {
1170 $this->sourceInstance = $sourceInstance;
1174 * Getter for a Sourceable instance
1176 * @return $sourceInstance The Sourceable instance
1178 protected final function getSourceInstance () {
1179 return $this->sourceInstance;
1183 * Getter for a InputStream instance
1185 * @param $inputStreamInstance The InputStream instance
1187 protected final function getInputStreamInstance () {
1188 return $this->inputStreamInstance;
1192 * Setter for a InputStream instance
1194 * @param $inputStreamInstance The InputStream instance
1197 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1198 $this->inputStreamInstance = $inputStreamInstance;
1202 * Getter for a OutputStream instance
1204 * @param $outputStreamInstance The OutputStream instance
1206 protected final function getOutputStreamInstance () {
1207 return $this->outputStreamInstance;
1211 * Setter for a OutputStream instance
1213 * @param $outputStreamInstance The OutputStream instance
1216 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1217 $this->outputStreamInstance = $outputStreamInstance;
1221 * Setter for handler instance
1223 * @param $handlerInstance An instance of a Handleable class
1226 protected final function setHandlerInstance (Handleable $handlerInstance) {
1227 $this->handlerInstance = $handlerInstance;
1231 * Getter for handler instance
1233 * @return $handlerInstance A Networkable instance
1235 protected final function getHandlerInstance () {
1236 return $this->handlerInstance;
1240 * Setter for visitor instance
1242 * @param $visitorInstance A Visitor instance
1245 protected final function setVisitorInstance (Visitor $visitorInstance) {
1246 $this->visitorInstance = $visitorInstance;
1250 * Getter for visitor instance
1252 * @return $visitorInstance A Visitor instance
1254 protected final function getVisitorInstance () {
1255 return $this->visitorInstance;
1259 * Setter for DHT instance
1261 * @param $dhtInstance A Distributable instance
1264 protected final function setDhtInstance (Distributable $dhtInstance) {
1265 $this->dhtInstance = $dhtInstance;
1269 * Getter for DHT instance
1271 * @return $dhtInstance A Distributable instance
1273 protected final function getDhtInstance () {
1274 return $this->dhtInstance;
1278 * Setter for raw package Data
1280 * @param $packageData Raw package Data
1283 public final function setPackageData (array $packageData) {
1284 $this->packageData = $packageData;
1288 * Getter for raw package Data
1290 * @return $packageData Raw package Data
1292 public function getPackageData () {
1293 return $this->packageData;
1298 * Setter for Iterator instance
1300 * @param $iteratorInstance An instance of an Iterator
1303 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1304 $this->iteratorInstance = $iteratorInstance;
1308 * Getter for Iterator instance
1310 * @return $iteratorInstance An instance of an Iterator
1312 public final function getIteratorInstance () {
1313 return $this->iteratorInstance;
1317 * Setter for InputOutputPointer instance
1319 * @param $pointerInstance An instance of an InputOutputPointer class
1322 protected final function setPointerInstance (InputOutputPointer $pointerInstance) {
1323 $this->pointerInstance = $pointerInstance;
1327 * Getter for InputOutputPointer instance
1329 * @return $pointerInstance An instance of an InputOutputPointer class
1331 public final function getPointerInstance () {
1332 return $this->pointerInstance;
1336 * Setter for Indexable instance
1338 * @param $indexInstance An instance of an Indexable class
1341 protected final function setIndexInstance (Indexable $indexInstance) {
1342 $this->indexInstance = $indexInstance;
1346 * Getter for Indexable instance
1348 * @return $indexInstance An instance of an Indexable class
1350 public final function getIndexInstance () {
1351 return $this->indexInstance;
1355 * Setter for Block instance
1357 * @param $blockInstance An instance of an Block class
1360 protected final function setBlockInstance (Block $blockInstance) {
1361 $this->blockInstance = $blockInstance;
1365 * Getter for Block instance
1367 * @return $blockInstance An instance of an Block class
1369 public final function getBlockInstance () {
1370 return $this->blockInstance;
1374 * Checks whether an object equals this object. You should overwrite this
1375 * method to implement own equality checks
1377 * @param $objectInstance An instance of a FrameworkInterface object
1378 * @return $equals Whether both objects equals
1380 public function equals (FrameworkInterface $objectInstance) {
1383 $this->__toString() == $objectInstance->__toString()
1385 $this->hashCode() == $objectInstance->hashCode()
1388 // Return the result
1393 * Generates a generic hash code of this class. You should really overwrite
1394 * this method with your own hash code generator code. But keep KISS in mind.
1396 * @return $hashCode A generic hash code respresenting this whole class
1398 public function hashCode () {
1400 return crc32($this->__toString());
1404 * Formats computer generated price values into human-understandable formats
1405 * with thousand and decimal separators.
1407 * @param $value The in computer format value for a price
1408 * @param $currency The currency symbol (use HTML-valid characters!)
1409 * @param $decNum Number of decimals after commata
1410 * @return $price The for the current language formated price string
1411 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1412 * thousands separator
1415 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1416 // Are all required attriutes set?
1417 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1418 // Throw an exception
1419 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1423 $value = (float) $value;
1425 // Reformat the US number
1426 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1428 // Return as string...
1433 * Appends a trailing slash to a string
1435 * @param $str A string (maybe) without trailing slash
1436 * @return $str A string with an auto-appended trailing slash
1438 public final function addMissingTrailingSlash ($str) {
1439 // Is there a trailing slash?
1440 if (substr($str, -1, 1) != '/') {
1444 // Return string with trailing slash
1449 * Prepare the template engine (WebTemplateEngine by default) for a given
1450 * application helper instance (ApplicationHelper by default).
1452 * @param $applicationInstance An application helper instance or
1453 * null if we shall use the default
1454 * @return $templateInstance The template engine instance
1455 * @throws NullPointerException If the discovered application
1456 * instance is still null
1458 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1459 // Is the application instance set?
1460 if (is_null($applicationInstance)) {
1461 // Get the current instance
1462 $applicationInstance = $this->getApplicationInstance();
1465 if (is_null($applicationInstance)) {
1466 // Thrown an exception
1467 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1471 // Initialize the template engine
1472 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
1474 // Return the prepared instance
1475 return $templateInstance;
1479 * Debugs this instance by putting out it's full content
1481 * @param $message Optional message to show in debug output
1484 public final function debugInstance ($message = '') {
1485 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1486 restore_error_handler();
1491 // Is a message set?
1492 if (!empty($message)) {
1493 // Construct message
1494 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1497 // Generate the output
1498 $content .= sprintf('<pre>%s</pre>',
1501 print_r($this, TRUE)
1507 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>',
1508 $this->__toString(),
1510 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1515 * Replaces control characters with printable output
1517 * @param $str String with control characters
1518 * @return $str Replaced string
1520 protected function replaceControlCharacters ($str) {
1523 chr(13), '[r]', str_replace(
1524 chr(10), '[n]', str_replace(
1534 * Output a partial stub message for the caller method
1536 * @param $message An optional message to display
1539 protected function partialStub ($message = '') {
1540 // Get the backtrace
1541 $backtrace = debug_backtrace();
1543 // Generate the class::method string
1544 $methodName = 'UnknownClass->unknownMethod';
1545 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1546 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1549 // Construct the full message
1550 $stubMessage = sprintf('[%s:] Partial stub!',
1554 // Is the extra message given?
1555 if (!empty($message)) {
1556 // Then add it as well
1557 $stubMessage .= ' Message: ' . $message;
1560 // Debug instance is there?
1561 if (!is_null($this->getDebugInstance())) {
1562 // Output stub message
1563 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1566 trigger_error($stubMessage);
1572 * Outputs a debug backtrace and stops further script execution
1574 * @param $message An optional message to output
1575 * @param $doExit Whether exit the program (TRUE is default)
1578 public function debugBackTrace ($message = '', $doExit = TRUE) {
1579 // Sorry, there is no other way getting this nice backtrace
1580 if (!empty($message)) {
1582 printf('Message: %s<br />' . chr(10), $message);
1586 debug_print_backtrace();
1590 if ($doExit === TRUE) {
1596 * Creates an instance of a debugger instance
1598 * @param $className Name of the class (currently unsupported)
1599 * @return $debugInstance An instance of a debugger class
1601 public final static function createDebugInstance ($className) {
1602 // Is the instance set?
1603 if (!Registry::getRegistry()->instanceExists('debug')) {
1604 // Init debug instance
1605 $debugInstance = NULL;
1609 // Get a debugger instance
1610 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_class'));
1611 } catch (NullPointerException $e) {
1612 // Didn't work, no instance there
1613 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1616 // Empty string should be ignored and used for testing the middleware
1617 DebugMiddleware::getSelfInstance()->output('');
1619 // Set it in its own class. This will set it in the registry
1620 $debugInstance->setDebugInstance($debugInstance);
1622 // Get instance from registry
1623 $debugInstance = Registry::getRegistry()->getDebugInstance();
1627 return $debugInstance;
1631 * Simple output of a message with line-break
1633 * @param $message Message to output
1636 public function outputLine ($message) {
1638 print($message . PHP_EOL);
1642 * Outputs a debug message whether to debug instance (should be set!) or
1643 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1644 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1646 * @param $message Message we shall send out...
1647 * @param $doPrint Whether print or die here (default: print)
1648 * @paran $stripTags Whether to strip tags (default: FALSE)
1651 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1652 // Set debug instance to NULL
1653 $debugInstance = NULL;
1657 // Get debug instance
1658 $debugInstance = $this->getDebugInstance();
1659 } catch (NullPointerException $e) {
1660 // The debug instance is not set (yet)
1663 // Is the debug instance there?
1664 if (is_object($debugInstance)) {
1665 // Use debug output handler
1666 $debugInstance->output($message, $stripTags);
1668 if ($doPrint === FALSE) {
1669 // Die here if not printed
1673 // Are debug times enabled?
1674 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1676 $message = $this->getPrintableExecutionTime() . $message;
1680 if ($doPrint === TRUE) {
1682 $this->outputLine($message);
1691 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1693 * @param $str The string, what ever it is needs to be converted
1694 * @return $className Generated class name
1696 public function convertToClassName ($str) {
1700 // Convert all dashes in underscores
1701 $str = $this->convertDashesToUnderscores($str);
1703 // Now use that underscores to get classname parts for hungarian style
1704 foreach (explode('_', $str) as $strPart) {
1705 // Make the class name part lower case and first upper case
1706 $className .= ucfirst(strtolower($strPart));
1709 // Return class name
1714 * Converts dashes to underscores, e.g. useable for configuration entries
1716 * @param $str The string with maybe dashes inside
1717 * @return $str The converted string with no dashed, but underscores
1719 public final function convertDashesToUnderscores ($str) {
1721 $str = str_replace('-', '_', $str);
1723 // Return converted string
1728 * Marks up the code by adding e.g. line numbers
1730 * @param $phpCode Unmarked PHP code
1731 * @return $markedCode Marked PHP code
1733 public function markupCode ($phpCode) {
1738 $errorArray = error_get_last();
1740 // Init the code with error message
1741 if (is_array($errorArray)) {
1743 $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>',
1744 basename($errorArray['file']),
1745 $errorArray['line'],
1746 $errorArray['message'],
1751 // Add line number to the code
1752 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1754 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1756 htmlentities($code, ENT_QUOTES)
1765 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1766 * beatiful for web-based front-ends. If null is given a message id
1767 * null_timestamp will be resolved and returned.
1769 * @param $timestamp Timestamp to prepare (filter) for display
1770 * @return $readable A readable timestamp
1772 public function doFilterFormatTimestamp ($timestamp) {
1773 // Default value to return
1776 // Is the timestamp null?
1777 if (is_null($timestamp)) {
1778 // Get a message string
1779 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1781 switch ($this->getLanguageInstance()->getLanguageCode()) {
1782 case 'de': // German format is a bit different to default
1783 // Split the GMT stamp up
1784 $dateTime = explode(' ', $timestamp );
1785 $dateArray = explode('-', $dateTime[0]);
1786 $timeArray = explode(':', $dateTime[1]);
1788 // Construct the timestamp
1789 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1799 default: // Default is pass-through
1800 $readable = $timestamp;
1810 * Filter a given number into a localized number
1812 * @param $value The raw value from e.g. database
1813 * @return $localized Localized value
1815 public function doFilterFormatNumber ($value) {
1816 // Generate it from config and localize dependencies
1817 switch ($this->getLanguageInstance()->getLanguageCode()) {
1818 case 'de': // German format is a bit different to default
1819 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1822 default: // US, etc.
1823 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1832 * "Getter" for databse entry
1834 * @return $entry An array with database entries
1835 * @throws NullPointerException If the database result is not found
1836 * @throws InvalidDatabaseResultException If the database result is invalid
1838 protected final function getDatabaseEntry () {
1839 // Is there an instance?
1840 if (is_null($this->getResultInstance())) {
1841 // Throw an exception here
1842 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1846 $this->getResultInstance()->rewind();
1848 // Do we have an entry?
1849 if ($this->getResultInstance()->valid() === FALSE) {
1850 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1854 $this->getResultInstance()->next();
1857 $entry = $this->getResultInstance()->current();
1864 * Getter for field name
1866 * @param $fieldName Field name which we shall get
1867 * @return $fieldValue Field value from the user
1868 * @throws NullPointerException If the result instance is null
1870 public final function getField ($fieldName) {
1871 // Default field value
1874 // Get result instance
1875 $resultInstance = $this->getResultInstance();
1877 // Is this instance null?
1878 if (is_null($resultInstance)) {
1879 // Then the user instance is no longer valid (expired cookies?)
1880 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1883 // Get current array
1884 $fieldArray = $resultInstance->current();
1885 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
1887 // Convert dashes to underscore
1888 $fieldName = $this->convertDashesToUnderscores($fieldName);
1890 // Does the field exist?
1891 if (isset($fieldArray[$fieldName])) {
1893 $fieldValue = $fieldArray[$fieldName];
1895 // Missing field entry, may require debugging
1896 self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ':fieldname=' . $fieldName . ' not found!');
1904 * Flushs all pending updates to the database layer
1908 public function flushPendingUpdates () {
1909 // Get result instance
1910 $resultInstance = $this->getResultInstance();
1912 // Do we have data to update?
1913 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1914 // Get wrapper class name config entry
1915 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1917 // Create object instance
1918 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1920 // Yes, then send the whole result to the database layer
1921 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1926 * Outputs a deprecation warning to the developer.
1928 * @param $message The message we shall output to the developer
1930 * @todo Write a logging mechanism for productive mode
1932 public function deprecationWarning ($message) {
1933 // Is developer mode active?
1934 if (defined('DEVELOPER')) {
1935 // Debug instance is there?
1936 if (!is_null($this->getDebugInstance())) {
1937 // Output stub message
1938 self::createDebugInstance(__CLASS__)->debugOutput($message);
1941 trigger_error($message . "<br />\n");
1945 // @TODO Finish this part!
1946 $this->partialStub('Developer mode inactive. Message:' . $message);
1951 * Checks whether the given PHP extension is loaded
1953 * @param $phpExtension The PHP extension we shall check
1954 * @return $isLoaded Whether the PHP extension is loaded
1956 public final function isPhpExtensionLoaded ($phpExtension) {
1958 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1965 * "Getter" as a time() replacement but with milliseconds. You should use this
1966 * method instead of the encapsulated getimeofday() function.
1968 * @return $milliTime Timestamp with milliseconds
1970 public function getMilliTime () {
1971 // Get the time of day as float
1972 $milliTime = gettimeofday(TRUE);
1979 * Idles (sleeps) for given milliseconds
1981 * @return $hasSlept Whether it goes fine
1983 public function idle ($milliSeconds) {
1984 // Sleep is fine by default
1987 // Idle so long with found function
1988 if (function_exists('time_sleep_until')) {
1989 // Get current time and add idle time
1990 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1992 // New PHP 5.1.0 function found, ignore errors
1993 $hasSlept = @time_sleep_until($sleepUntil);
1996 * My Sun station doesn't have that function even with latest PHP
1999 usleep($milliSeconds * 1000);
2006 * Converts a hexadecimal string, even with negative sign as first string to
2007 * a decimal number using BC functions.
2009 * This work is based on comment #86673 on php.net documentation page at:
2010 * <http://de.php.net/manual/en/function.dechex.php#86673>
2012 * @param $hex Hexadecimal string
2013 * @return $dec Decimal number
2015 protected function hex2dec ($hex) {
2016 // Convert to all lower-case
2017 $hex = strtolower($hex);
2019 // Detect sign (negative/positive numbers)
2021 if (substr($hex, 0, 1) == '-') {
2023 $hex = substr($hex, 1);
2026 // Decode the hexadecimal string into a decimal number
2028 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2029 $factor = self::$hexdec[substr($hex, $i, 1)];
2030 $dec = bcadd($dec, bcmul($factor, $e));
2033 // Return the decimal number
2034 return $sign . $dec;
2038 * Converts even very large decimal numbers, also signed, to a hexadecimal
2041 * This work is based on comment #97756 on php.net documentation page at:
2042 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2044 * @param $dec Decimal number, even with negative sign
2045 * @param $maxLength Optional maximum length of the string
2046 * @return $hex Hexadecimal string
2048 protected function dec2hex ($dec, $maxLength = 0) {
2049 // maxLength can be zero or devideable by 2
2050 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2052 // Detect sign (negative/positive numbers)
2059 // Encode the decimal number into a hexadecimal string
2062 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2064 } while ($dec >= 1);
2067 * Leading zeros are required for hex-decimal "numbers". In some
2068 * situations more leading zeros are wanted, so check for both
2071 if ($maxLength > 0) {
2072 // Prepend more zeros
2073 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2074 } elseif ((strlen($hex) % 2) != 0) {
2075 // Only make string's length dividable by 2
2079 // Return the hexadecimal string
2080 return $sign . $hex;
2084 * Converts a ASCII string (0 to 255) into a decimal number.
2086 * @param $asc The ASCII string to be converted
2087 * @return $dec Decimal number
2089 protected function asc2dec ($asc) {
2090 // Convert it into a hexadecimal number
2091 $hex = bin2hex($asc);
2093 // And back into a decimal number
2094 $dec = $this->hex2dec($hex);
2101 * Converts a decimal number into an ASCII string.
2103 * @param $dec Decimal number
2104 * @return $asc An ASCII string
2106 protected function dec2asc ($dec) {
2107 // First convert the number into a hexadecimal string
2108 $hex = $this->dec2hex($dec);
2110 // Then convert it into the ASCII string
2111 $asc = $this->hex2asc($hex);
2118 * Converts a hexadecimal number into an ASCII string. Negative numbers
2121 * @param $hex Hexadecimal string
2122 * @return $asc An ASCII string
2124 protected function hex2asc ($hex) {
2125 // Check for length, it must be devideable by 2
2126 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2127 assert((strlen($hex) % 2) == 0);
2131 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2132 // Get the decimal number of the chunk
2133 $part = hexdec(substr($hex, $idx, 2));
2135 // Add it to the final string
2139 // Return the final string
2144 * Checks whether the given encoded data was encoded with Base64
2146 * @param $encodedData Encoded data we shall check
2147 * @return $isBase64 Whether the encoded data is Base64
2149 protected function isBase64Encoded ($encodedData) {
2151 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2158 * "Getter" to get response/request type from analysis of the system.
2160 * @return $responseType Analyzed response type
2162 protected function getResponseTypeFromSystem () {
2163 // Default is console
2164 $responseType = 'console';
2166 // Is 'HTTP_HOST' set?
2167 if (isset($_SERVER['HTTP_HOST'])) {
2168 // Then it is a HTTP response/request
2169 $responseType = 'http';
2173 return $responseType;
2177 * Gets a cache key from Criteria instance
2179 * @param $criteriaInstance An instance of a Criteria class
2180 * @param $onlyKeys Only use these keys for a cache key
2181 * @return $cacheKey A cache key suitable for lookup/storage purposes
2183 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2185 $cacheKey = sprintf('%s@%s',
2186 $this->__toString(),
2187 $criteriaInstance->getCacheKey($onlyKeys)
2191 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2196 * Getter for startup time in miliseconds
2198 * @return $startupTime Startup time in miliseconds
2200 protected function getStartupTime () {
2201 return self::$startupTime;
2205 * "Getter" for a printable currently execution time in nice braces
2207 * @return $executionTime Current execution time in nice braces
2209 protected function getPrintableExecutionTime () {
2210 // Caculate the execution time
2211 $executionTime = microtime(TRUE) - $this->getStartupTime();
2213 // Pack it in nice braces
2214 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2217 return $executionTime;
2221 * Hashes a given string with a simple but stronger hash function (no salt)
2222 * and hex-encode it.
2224 * @param $str The string to be hashed
2225 * @return $hash The hash from string $str
2227 public static final function hash ($str) {
2228 // Hash given string with (better secure) hasher
2229 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2236 * "Getter" for length of hash() output. This will be "cached" to speed up
2239 * @return $length Length of hash() output
2241 public static final function getHashLength () {
2243 if (is_null(self::$hashLength)) {
2244 // No, then hash a string and save its length.
2245 self::$hashLength = strlen(self::hash('abc123'));
2249 return self::$hashLength;
2253 * Checks whether the given number is really a number (only chars 0-9).
2255 * @param $num A string consisting only chars between 0 and 9
2256 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2257 * @param $assertMismatch Whether to assert mismatches
2258 * @return $ret The (hopefully) secured numbered value
2260 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2261 // Filter all numbers out
2262 $ret = preg_replace('/[^0123456789]/', '', $num);
2265 if ($castValue === TRUE) {
2266 // Cast to biggest numeric type
2267 $ret = (double) $ret;
2270 // Assert only if requested
2271 if ($assertMismatch === TRUE) {
2272 // Has the whole value changed?
2273 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2281 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2283 * @param $num A string consisting only chars between 0 and 9
2284 * @param $assertMismatch Whether to assert mismatches
2285 * @return $ret The (hopefully) secured hext-numbered value
2287 public function hexval ($num, $assertMismatch = FALSE) {
2288 // Filter all numbers out
2289 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2291 // Assert only if requested
2292 if ($assertMismatch === TRUE) {
2293 // Has the whole value changed?
2294 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2302 * Checks whether start/end marker are set
2304 * @param $data Data to be checked
2305 * @return $isset Whether start/end marker are set
2307 public final function ifStartEndMarkersSet ($data) {
2309 $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));
2311 // ... and return it
2316 * Determines if an element is set in the generic array
2318 * @param $keyGroup Main group for the key
2319 * @param $subGroup Sub group for the key
2320 * @param $key Key to check
2321 * @param $element Element to check
2322 * @return $isset Whether the given key is set
2324 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2326 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2329 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2335 * Determines if a key is set in the generic array
2337 * @param $keyGroup Main group for the key
2338 * @param $subGroup Sub group for the key
2339 * @param $key Key to check
2340 * @return $isset Whether the given key is set
2342 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2344 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2347 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2355 * Determines if a group is set in the generic array
2357 * @param $keyGroup Main group
2358 * @param $subGroup Sub group
2359 * @return $isset Whether the given group is set
2361 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2363 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2366 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2373 * Getter for sub key group
2375 * @param $keyGroup Main key group
2376 * @param $subGroup Sub key group
2377 * @return $array An array with all array elements
2379 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2381 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2382 // No, then abort here
2383 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2388 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2391 return $this->genericArray[$keyGroup][$subGroup];
2395 * Unsets a given key in generic array
2397 * @param $keyGroup Main group for the key
2398 * @param $subGroup Sub group for the key
2399 * @param $key Key to unset
2402 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2404 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2407 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2411 * Unsets a given element in generic array
2413 * @param $keyGroup Main group for the key
2414 * @param $subGroup Sub group for the key
2415 * @param $key Key to unset
2416 * @param $element Element to unset
2419 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2421 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2424 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2428 * Append a string to a given generic array key
2430 * @param $keyGroup Main group for the key
2431 * @param $subGroup Sub group for the key
2432 * @param $key Key to unset
2433 * @param $value Value to add/append
2436 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2438 //* 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);
2440 // Is it already there?
2441 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2443 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2446 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2451 * Append a string to a given generic array element
2453 * @param $keyGroup Main group for the key
2454 * @param $subGroup Sub group for the key
2455 * @param $key Key to unset
2456 * @param $element Element to check
2457 * @param $value Value to add/append
2460 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2462 //* 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);
2464 // Is it already there?
2465 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2467 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2470 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2475 * Initializes given generic array group
2477 * @param $keyGroup Main group for the key
2478 * @param $subGroup Sub group for the key
2479 * @param $key Key to use
2480 * @param $forceInit Optionally force initialization
2483 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2485 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2487 // Is it already set?
2488 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2489 // Already initialized
2490 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2495 $this->genericArray[$keyGroup][$subGroup] = array();
2499 * Initializes given generic array key
2501 * @param $keyGroup Main group for the key
2502 * @param $subGroup Sub group for the key
2503 * @param $key Key to use
2504 * @param $forceInit Optionally force initialization
2507 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2509 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2511 // Is it already set?
2512 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2513 // Already initialized
2514 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2519 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2523 * Initializes given generic array element
2525 * @param $keyGroup Main group for the key
2526 * @param $subGroup Sub group for the key
2527 * @param $key Key to use
2528 * @param $element Element to use
2529 * @param $forceInit Optionally force initialization
2532 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2534 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2536 // Is it already set?
2537 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2538 // Already initialized
2539 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2544 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2548 * Pushes an element to a generic key
2550 * @param $keyGroup Main group for the key
2551 * @param $subGroup Sub group for the key
2552 * @param $key Key to use
2553 * @param $value Value to add/append
2554 * @return $count Number of array elements
2556 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2558 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2561 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2563 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2567 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2570 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2571 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2576 * Pushes an element to a generic array element
2578 * @param $keyGroup Main group for the key
2579 * @param $subGroup Sub group for the key
2580 * @param $key Key to use
2581 * @param $element Element to check
2582 * @param $value Value to add/append
2583 * @return $count Number of array elements
2585 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2587 //* 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));
2590 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2592 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2596 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2599 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2600 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2605 * Pops an element from a generic group
2607 * @param $keyGroup Main group for the key
2608 * @param $subGroup Sub group for the key
2609 * @param $key Key to unset
2610 * @return $value Last "popped" value
2612 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2614 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2617 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2619 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2624 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2627 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2628 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2633 * Shifts an element from a generic group
2635 * @param $keyGroup Main group for the key
2636 * @param $subGroup Sub group for the key
2637 * @param $key Key to unset
2638 * @return $value Last "popped" value
2640 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2642 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2645 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2647 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2652 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2655 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2656 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2661 * Count generic array group
2663 * @param $keyGroup Main group for the key
2664 * @return $count Count of given group
2666 protected final function countGenericArray ($keyGroup) {
2668 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2671 if (!isset($this->genericArray[$keyGroup])) {
2673 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2678 $count = count($this->genericArray[$keyGroup]);
2681 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2688 * Count generic array sub group
2690 * @param $keyGroup Main group for the key
2691 * @param $subGroup Sub group for the key
2692 * @return $count Count of given group
2694 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2696 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2699 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2701 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2706 $count = count($this->genericArray[$keyGroup][$subGroup]);
2709 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2716 * Count generic array elements
2718 * @param $keyGroup Main group for the key
2719 * @param $subGroup Sub group for the key
2720 * @para $key Key to count
2721 * @return $count Count of given key
2723 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2725 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2728 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2730 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2732 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2734 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2739 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2742 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2749 * Getter for whole generic group array
2751 * @param $keyGroup Key group to get
2752 * @return $array Whole generic array group
2754 protected final function getGenericArray ($keyGroup) {
2756 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2759 if (!isset($this->genericArray[$keyGroup])) {
2761 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2766 return $this->genericArray[$keyGroup];
2770 * Setter for generic array key
2772 * @param $keyGroup Key group to get
2773 * @param $subGroup Sub group for the key
2774 * @param $key Key to unset
2775 * @param $value Mixed value from generic array element
2778 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2780 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2783 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2787 * Getter for generic array key
2789 * @param $keyGroup Key group to get
2790 * @param $subGroup Sub group for the key
2791 * @param $key Key to unset
2792 * @return $value Mixed value from generic array element
2794 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2796 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2799 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2801 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2806 return $this->genericArray[$keyGroup][$subGroup][$key];
2810 * Sets a value in given generic array key/element
2812 * @param $keyGroup Main group for the key
2813 * @param $subGroup Sub group for the key
2814 * @param $key Key to set
2815 * @param $element Element to set
2816 * @param $value Value to set
2819 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2821 //* 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));
2824 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2828 * Getter for generic array element
2830 * @param $keyGroup Key group to get
2831 * @param $subGroup Sub group for the key
2832 * @param $key Key to look for
2833 * @param $element Element to look for
2834 * @return $value Mixed value from generic array element
2836 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2838 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2841 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2843 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2848 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2852 * Checks if a given sub group is valid (array)
2854 * @param $keyGroup Key group to get
2855 * @param $subGroup Sub group for the key
2856 * @return $isValid Whether given sub group is valid
2858 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2860 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2863 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
2870 * Checks if a given key is valid (array)
2872 * @param $keyGroup Key group to get
2873 * @param $subGroup Sub group for the key
2874 * @param $key Key to check
2875 * @return $isValid Whether given sub group is valid
2877 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
2879 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2882 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
2889 * Translates boolean TRUE to 'Y' and FALSE to 'N'
2891 * @param $boolean Boolean value
2892 * @return $translated Translated boolean value
2894 public static final function translateBooleanToYesNo ($boolean) {
2895 // Make sure it is really boolean
2896 assert(is_bool($boolean));
2899 $translated = ($boolean === TRUE) ? 'Y' : 'N';
2901 // ... and return it
2906 * Initializes counter for valid entries, arrays for damaged entries and
2907 * an array for gap seek positions. If you call this method on your own,
2908 * please re-analyze the file structure. So you are better to call
2909 * analyzeFile() instead of this method.
2913 protected function initCountersGapsArray () {
2914 // Init counter and seek position
2915 $this->setCounter(0);
2916 $this->setSeekPosition(0);
2919 $this->gaps = array();
2920 $this->damagedEntries = array();
2924 * Getter for total entries
2926 * @return $totalEntries Total entries in this file
2928 protected final function getCounter () {
2930 return $this->totalEntries;
2934 * Setter for total entries
2936 * @param $totalEntries Total entries in this file
2939 protected final function setCounter ($counter) {
2941 $this->totalEntries = $counter;
2949 protected final function incrementCounter () {
2951 $this->totalEntries++;
2955 * Getter for header size
2957 * @return $totalEntries Size of file header
2959 public final function getHeaderSize () {
2961 return $this->headerSize;
2965 * Setter for header size
2967 * @param $headerSize Size of file header
2970 protected final function setHeaderSize ($headerSize) {
2972 $this->headerSize = $headerSize;
2976 * Getter for header array
2978 * @return $totalEntries Size of file header
2980 protected final function getHeade () {
2982 return $this->header;
2988 * @param $header Array for a file header
2991 protected final function setHeader (array $header) {
2993 $this->header = $header;
2997 * Getter for seek position
2999 * @return $seekPosition Current seek position (stored here in object)
3001 protected final function getSeekPosition () {
3003 return $this->seekPosition;
3007 * Setter for seek position
3009 * @param $seekPosition Current seek position (stored here in object)
3012 protected final function setSeekPosition ($seekPosition) {
3014 $this->seekPosition = $seekPosition;
3018 * Updates seekPosition attribute from file to avoid to much access on file.
3022 protected function updateSeekPosition () {
3023 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3025 // Get key (= seek position)
3026 $seekPosition = $this->getIteratorInstance()->key();
3027 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Setting seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
3030 $this->setSeekPosition($seekPosition);
3032 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
3036 * Seeks to beginning of file, updates seek position in this object and
3037 * flushes the header.
3041 protected function rewineUpdateSeekPosition () {
3042 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3044 // flushFileHeader must be callable
3045 assert(is_callable(array($this, 'flushFileHeader')));
3047 // Seek to beginning of file
3048 $this->getIteratorInstance()->rewind();
3050 // And update seek position ...
3051 $this->updateSeekPosition();
3053 // ... to write it back into the file
3054 $this->flushFileHeader();
3056 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!!', __METHOD__, __LINE__));
3060 * Seeks to old position
3064 protected function seekToOldPosition () {
3065 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3067 // Seek to currently ("old") saved position
3068 $this->getIteratorInstance()->seek($this->getSeekPosition());
3070 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!!', __METHOD__, __LINE__));
3074 * Checks whether the block separator has been found
3076 * @param $str String to look in
3077 * @return $isFound Whether the block separator has been found
3079 public static function isBlockSeparatorFound ($str) {
3081 $isFound = (strpos($str, chr(self::SEPARATOR_ENTRIES)) !== FALSE);