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;
49 const LENGTH_COUNT = 20;
54 const LENGTH_POSITION = 20;
59 const LENGTH_NAME = 10;
64 private $realClass = 'BaseFrameworkSystem';
67 * Instance of a request class
69 private $requestInstance = NULL;
72 * Instance of a response class
74 private $responseInstance = NULL;
77 * Search criteria instance
79 private $searchInstance = NULL;
82 * Update criteria instance
84 private $updateInstance = NULL;
87 * The file I/O instance for the template loader
89 private $fileIoInstance = NULL;
94 private $resolverInstance = NULL;
97 * Template engine instance
99 private $templateInstance = NULL;
102 * Database result instance
104 private $resultInstance = NULL;
107 * Instance for user class
109 private $userInstance = NULL;
112 * A controller instance
114 private $controllerInstance = NULL;
119 private $rngInstance = NULL;
122 * Instance of a crypto helper
124 private $cryptoInstance = NULL;
127 * Instance of an Iterator class
129 private $iteratorInstance = NULL;
132 * Instance of the list
134 private $listInstance = NULL;
139 private $menuInstance = NULL;
142 * Instance of the image
144 private $imageInstance = NULL;
147 * Instance of the stacker
149 private $stackerInstance = NULL;
152 * A Compressor instance
154 private $compressorInstance = NULL;
157 * A Parseable instance
159 private $parserInstance = NULL;
162 * A ProtocolHandler instance
164 private $protocolInstance = NULL;
167 * A database wrapper instance
169 private $databaseInstance = NULL;
172 * A helper instance for the form
174 private $helperInstance = NULL;
177 * An instance of a Sourceable class
179 private $sourceInstance = NULL;
182 * An instance of a InputStream class
184 private $inputStreamInstance = NULL;
187 * An instance of a OutputStream class
189 private $outputStreamInstance = NULL;
192 * Networkable handler instance
194 private $handlerInstance = NULL;
197 * Visitor handler instance
199 private $visitorInstance = NULL;
204 private $dhtInstance = NULL;
207 * An instance of a database wrapper class
209 private $wrapperInstance = NULL;
212 * An instance of a file I/O pointer class (not handler)
214 private $pointerInstance = NULL;
217 * An instance of an Indexable class
219 private $indexInstance = NULL;
222 * An instance of a CalculatableBlock class
224 private $blockInstance = NULL;
227 * Thousands separator
229 private $thousands = '.'; // German
234 private $decimals = ','; // German
239 private $socketResource = FALSE;
244 private $packageData = array();
249 private $genericArray = array();
252 * Length of output from hash()
254 private static $hashLength = NULL;
257 * Counter for total entries
259 private $totalEntries = 0;
262 * Current seek position
264 private $seekPosition = 0;
269 private $headerSize = 0;
274 private $header = array();
277 * Seek positions for gaps ("fragmentation")
279 private $gaps = array();
282 * Seek positions for damaged entries (e.g. mismatching hash sum, ...)
284 private $damagedEntries = array();
286 /***********************
287 * Exception codes.... *
288 ***********************/
290 // @todo Try to clean these constants up
291 const EXCEPTION_IS_NULL_POINTER = 0x001;
292 const EXCEPTION_IS_NO_OBJECT = 0x002;
293 const EXCEPTION_IS_NO_ARRAY = 0x003;
294 const EXCEPTION_MISSING_METHOD = 0x004;
295 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
296 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
297 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
298 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
299 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
300 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
301 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
302 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
303 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
304 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
305 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
306 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
307 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
308 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
309 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
310 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
311 const EXCEPTION_PATH_NOT_FOUND = 0x015;
312 const EXCEPTION_INVALID_PATH_NAME = 0x016;
313 const EXCEPTION_READ_PROTECED_PATH = 0x017;
314 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
315 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
316 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
317 const EXCEPTION_INVALID_RESOURCE = 0x01b;
318 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
319 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
320 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
321 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
322 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
323 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
324 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
325 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
326 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
327 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
328 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
329 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
330 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
331 const EXCEPTION_INVALID_STRING = 0x029;
332 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
333 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
334 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
335 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
336 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
337 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
338 const EXCEPTION_MISSING_ELEMENT = 0x030;
339 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
340 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
341 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
342 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
343 const EXCEPTION_FATAL_ERROR = 0x035;
344 const EXCEPTION_FILE_NOT_FOUND = 0x036;
345 const EXCEPTION_ASSERTION_FAILED = 0x037;
346 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
347 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
348 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03a;
351 * Hexadecimal->Decimal translation array
353 private static $hexdec = array(
373 * Decimal->hexadecimal translation array
375 private static $dechex = array(
395 * Startup time in miliseconds
397 private static $startupTime = 0;
400 * Protected super constructor
402 * @param $className Name of the class
405 protected function __construct ($className) {
407 $this->setRealClass($className);
409 // Set configuration instance if no registry ...
410 if (!$this instanceof Register) {
411 // ... because registries doesn't need to be configured
412 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
415 // Is the startup time set? (0 cannot be TRUE anymore)
416 if (self::$startupTime == 0) {
418 self::$startupTime = microtime(TRUE);
423 * Destructor for all classes
427 public function __destruct () {
428 // Flush any updated entries to the database
429 $this->flushPendingUpdates();
431 // Is this object already destroyed?
432 if ($this->__toString() != 'DestructedObject') {
433 // Destroy all informations about this class but keep some text about it alive
434 $this->setRealClass('DestructedObject');
435 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
436 // Already destructed object
437 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
442 // Do not call this twice
443 trigger_error(__METHOD__ . ': Called twice.');
449 * The __call() method where all non-implemented methods end up
451 * @param $methodName Name of the missing method
452 * @args $args Arguments passed to the method
455 public final function __call ($methodName, $args) {
456 return self::__callStatic($methodName, $args);
460 * The __callStatic() method where all non-implemented static methods end up
462 * @param $methodName Name of the missing method
463 * @args $args Arguments passed to the method
466 public static final function __callStatic ($methodName, $args) {
467 // Init argument string
470 // Is it empty or an array?
473 $argsString = 'NULL';
474 } elseif (is_array($args)) {
475 // Some arguments are there
476 foreach ($args as $arg) {
477 // Add the value itself if not array. This prevents 'array to string conversion' message
478 if (is_array($arg)) {
479 $argsString .= 'Array';
484 // Add data about the argument
485 $argsString .= ' (' . gettype($arg);
487 if (is_string($arg)) {
488 // Add length for strings
489 $argsString .= ', ' . strlen($arg);
490 } elseif (is_array($arg)) {
491 // .. or size if array
492 $argsString .= ', ' . count($arg);
493 } elseif ($arg === TRUE) {
494 // ... is boolean 'TRUE'
495 $argsString .= ', TRUE';
496 } elseif ($arg === FALSE) {
497 // ... is boolean 'FALSE'
498 $argsString .= ', FALSE';
502 $argsString .= '), ';
506 if (substr($argsString, -2, 1) == ',') {
507 $argsString = substr($argsString, 0, -2);
510 // Invalid arguments!
511 $argsString = '!INVALID:' . gettype($args) . '!';
514 // Output stub message
515 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
516 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
526 * Getter for $realClass
528 * @return $realClass The name of the real class (not BaseFrameworkSystem)
530 public function __toString () {
531 return $this->realClass;
535 * Magic function to catch setting of missing but set class fields/attributes
537 * @param $name Name of the field/attribute
538 * @param $value Value to store
541 public final function __set ($name, $value) {
542 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
545 print_r($value, TRUE)
550 * Magic function to catch getting of missing fields/attributes
552 * @param $name Name of the field/attribute
555 public final function __get ($name) {
556 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
562 * Magic function to catch unsetting of missing fields/attributes
564 * @param $name Name of the field/attribute
567 public final function __unset ($name) {
568 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
574 * Setter for the real class name
576 * @param $realClass Class name (string)
579 public final function setRealClass ($realClass) {
581 $this->realClass = (string) $realClass;
585 * Setter for database result instance
587 * @param $resultInstance An instance of a database result class
589 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
591 protected final function setResultInstance (SearchableResult $resultInstance) {
592 $this->resultInstance = $resultInstance;
596 * Getter for database result instance
598 * @return $resultInstance An instance of a database result class
600 public final function getResultInstance () {
601 return $this->resultInstance;
605 * Setter for template engine instances
607 * @param $templateInstance An instance of a template engine class
610 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
611 $this->templateInstance = $templateInstance;
615 * Getter for template engine instances
617 * @return $templateInstance An instance of a template engine class
619 protected final function getTemplateInstance () {
620 return $this->templateInstance;
624 * Setter for search instance
626 * @param $searchInstance Searchable criteria instance
629 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
630 $this->searchInstance = $searchInstance;
634 * Getter for search instance
636 * @return $searchInstance Searchable criteria instance
638 public final function getSearchInstance () {
639 return $this->searchInstance;
643 * Setter for update instance
645 * @param $updateInstance Searchable criteria instance
648 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
649 $this->updateInstance = $updateInstance;
653 * Getter for update instance
655 * @return $updateInstance Updateable criteria instance
657 public final function getUpdateInstance () {
658 return $this->updateInstance;
662 * Setter for resolver instance
664 * @param $resolverInstance Instance of a command resolver class
667 public final function setResolverInstance (Resolver $resolverInstance) {
668 $this->resolverInstance = $resolverInstance;
672 * Getter for resolver instance
674 * @return $resolverInstance Instance of a command resolver class
676 public final function getResolverInstance () {
677 return $this->resolverInstance;
681 * Setter for language instance
683 * @param $configInstance The configuration instance which shall
684 * be FrameworkConfiguration
687 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
688 Registry::getRegistry()->addInstance('config', $configInstance);
692 * Getter for configuration instance
694 * @return $configInstance Configuration instance
696 public final function getConfigInstance () {
697 $configInstance = Registry::getRegistry()->getInstance('config');
698 return $configInstance;
702 * Setter for debug instance
704 * @param $debugInstance The instance for debug output class
707 public final function setDebugInstance (DebugMiddleware $debugInstance) {
708 Registry::getRegistry()->addInstance('debug', $debugInstance);
712 * Getter for debug instance
714 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
716 public final function getDebugInstance () {
717 // Get debug instance
718 $debugInstance = Registry::getRegistry()->getInstance('debug');
721 return $debugInstance;
725 * Setter for web output instance
727 * @param $webInstance The instance for web output class
730 public final function setWebOutputInstance (OutputStreamer $webInstance) {
731 Registry::getRegistry()->addInstance('web_output', $webInstance);
735 * Getter for web output instance
737 * @return $webOutputInstance - Instance to class WebOutput
739 public final function getWebOutputInstance () {
740 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
741 return $webOutputInstance;
745 * Setter for database instance
747 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
750 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
751 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
755 * Getter for database layer
757 * @return $databaseInstance The database layer instance
759 public final function getDatabaseInstance () {
761 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
764 return $databaseInstance;
768 * Setter for compressor channel
770 * @param $compressorInstance An instance of CompressorChannel
773 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
774 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
778 * Getter for compressor channel
780 * @return $compressorInstance The compressor channel
782 public final function getCompressorChannel () {
783 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
784 return $compressorInstance;
788 * Protected getter for a manageable application helper class
790 * @return $applicationInstance An instance of a manageable application helper class
792 protected final function getApplicationInstance () {
793 $applicationInstance = Registry::getRegistry()->getInstance('application');
794 return $applicationInstance;
798 * Setter for a manageable application helper class
800 * @param $applicationInstance An instance of a manageable application helper class
803 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
804 Registry::getRegistry()->addInstance('application', $applicationInstance);
808 * Setter for request instance
810 * @param $requestInstance An instance of a Requestable class
813 public final function setRequestInstance (Requestable $requestInstance) {
814 $this->requestInstance = $requestInstance;
818 * Getter for request instance
820 * @return $requestInstance An instance of a Requestable class
822 public final function getRequestInstance () {
823 return $this->requestInstance;
827 * Setter for response instance
829 * @param $responseInstance An instance of a Responseable class
832 public final function setResponseInstance (Responseable $responseInstance) {
833 $this->responseInstance = $responseInstance;
837 * Getter for response instance
839 * @return $responseInstance An instance of a Responseable class
841 public final function getResponseInstance () {
842 return $this->responseInstance;
846 * Private getter for language instance
848 * @return $langInstance An instance to the language sub-system
850 protected final function getLanguageInstance () {
851 $langInstance = Registry::getRegistry()->getInstance('language');
852 return $langInstance;
856 * Setter for language instance
858 * @param $langInstance An instance to the language sub-system
860 * @see LanguageSystem
862 public final function setLanguageInstance (ManageableLanguage $langInstance) {
863 Registry::getRegistry()->addInstance('language', $langInstance);
867 * Private getter for file IO instance
869 * @return $fileIoInstance An instance to the file I/O sub-system
871 protected final function getFileIoInstance () {
872 return $this->fileIoInstance;
876 * Setter for file I/O instance
878 * @param $fileIoInstance An instance to the file I/O sub-system
881 public final function setFileIoInstance (IoHandler $fileIoInstance) {
882 $this->fileIoInstance = $fileIoInstance;
886 * Protected setter for user instance
888 * @param $userInstance An instance of a user class
891 protected final function setUserInstance (ManageableAccount $userInstance) {
892 $this->userInstance = $userInstance;
896 * Getter for user instance
898 * @return $userInstance An instance of a user class
900 public final function getUserInstance () {
901 return $this->userInstance;
905 * Setter for controller instance (this surely breaks a bit the MVC patterm)
907 * @param $controllerInstance An instance of the controller
910 public final function setControllerInstance (Controller $controllerInstance) {
911 $this->controllerInstance = $controllerInstance;
915 * Getter for controller instance (this surely breaks a bit the MVC patterm)
917 * @return $controllerInstance An instance of the controller
919 public final function getControllerInstance () {
920 return $this->controllerInstance;
924 * Setter for RNG instance
926 * @param $rngInstance An instance of a random number generator (RNG)
929 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
930 $this->rngInstance = $rngInstance;
934 * Getter for RNG instance
936 * @return $rngInstance An instance of a random number generator (RNG)
938 public final function getRngInstance () {
939 return $this->rngInstance;
943 * Setter for Cryptable instance
945 * @param $cryptoInstance An instance of a Cryptable class
948 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
949 $this->cryptoInstance = $cryptoInstance;
953 * Getter for Cryptable instance
955 * @return $cryptoInstance An instance of a Cryptable class
957 public final function getCryptoInstance () {
958 return $this->cryptoInstance;
962 * Setter for the list instance
964 * @param $listInstance A list of Listable
967 protected final function setListInstance (Listable $listInstance) {
968 $this->listInstance = $listInstance;
972 * Getter for the list instance
974 * @return $listInstance A list of Listable
976 protected final function getListInstance () {
977 return $this->listInstance;
981 * Setter for the menu instance
983 * @param $menuInstance A RenderableMenu instance
986 protected final function setMenuInstance (RenderableMenu $menuInstance) {
987 $this->menuInstance = $menuInstance;
991 * Getter for the menu instance
993 * @return $menuInstance A RenderableMenu instance
995 protected final function getMenuInstance () {
996 return $this->menuInstance;
1000 * Setter for image instance
1002 * @param $imageInstance An instance of an image
1005 public final function setImageInstance (BaseImage $imageInstance) {
1006 $this->imageInstance = $imageInstance;
1010 * Getter for image instance
1012 * @return $imageInstance An instance of an image
1014 public final function getImageInstance () {
1015 return $this->imageInstance;
1019 * Setter for stacker instance
1021 * @param $stackerInstance An instance of an stacker
1024 public final function setStackerInstance (Stackable $stackerInstance) {
1025 $this->stackerInstance = $stackerInstance;
1029 * Getter for stacker instance
1031 * @return $stackerInstance An instance of an stacker
1033 public final function getStackerInstance () {
1034 return $this->stackerInstance;
1038 * Setter for compressor instance
1040 * @param $compressorInstance An instance of an compressor
1043 public final function setCompressorInstance (Compressor $compressorInstance) {
1044 $this->compressorInstance = $compressorInstance;
1048 * Getter for compressor instance
1050 * @return $compressorInstance An instance of an compressor
1052 public final function getCompressorInstance () {
1053 return $this->compressorInstance;
1057 * Setter for Parseable instance
1059 * @param $parserInstance An instance of an Parseable
1062 public final function setParserInstance (Parseable $parserInstance) {
1063 $this->parserInstance = $parserInstance;
1067 * Getter for Parseable instance
1069 * @return $parserInstance An instance of an Parseable
1071 public final function getParserInstance () {
1072 return $this->parserInstance;
1076 * Setter for ProtocolHandler instance
1078 * @param $protocolInstance An instance of an ProtocolHandler
1081 public final function setProtocolInstance (ProtocolHandler $protocolInstance = NULL) {
1082 $this->protocolInstance = $protocolInstance;
1086 * Getter for ProtocolHandler instance
1088 * @return $protocolInstance An instance of an ProtocolHandler
1090 public final function getProtocolInstance () {
1091 return $this->protocolInstance;
1095 * Setter for DatabaseWrapper instance
1097 * @param $wrapperInstance An instance of an DatabaseWrapper
1100 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1101 $this->wrapperInstance = $wrapperInstance;
1105 * Getter for DatabaseWrapper instance
1107 * @return $wrapperInstance An instance of an DatabaseWrapper
1109 public final function getWrapperInstance () {
1110 return $this->wrapperInstance;
1114 * Setter for socket resource
1116 * @param $socketResource A valid socket resource
1119 public final function setSocketResource ($socketResource) {
1120 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1121 $this->socketResource = $socketResource;
1125 * Getter for socket resource
1127 * @return $socketResource A valid socket resource
1129 public final function getSocketResource () {
1130 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1131 return $this->socketResource;
1135 * Setter for helper instance
1137 * @param $helperInstance An instance of a helper class
1140 protected final function setHelperInstance (Helper $helperInstance) {
1141 $this->helperInstance = $helperInstance;
1145 * Getter for helper instance
1147 * @return $helperInstance An instance of a helper class
1149 public final function getHelperInstance () {
1150 return $this->helperInstance;
1154 * Setter for a Sourceable instance
1156 * @param $sourceInstance The Sourceable instance
1159 protected final function setSourceInstance (Sourceable $sourceInstance) {
1160 $this->sourceInstance = $sourceInstance;
1164 * Getter for a Sourceable instance
1166 * @return $sourceInstance The Sourceable instance
1168 protected final function getSourceInstance () {
1169 return $this->sourceInstance;
1173 * Getter for a InputStream instance
1175 * @param $inputStreamInstance The InputStream instance
1177 protected final function getInputStreamInstance () {
1178 return $this->inputStreamInstance;
1182 * Setter for a InputStream instance
1184 * @param $inputStreamInstance The InputStream instance
1187 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1188 $this->inputStreamInstance = $inputStreamInstance;
1192 * Getter for a OutputStream instance
1194 * @param $outputStreamInstance The OutputStream instance
1196 protected final function getOutputStreamInstance () {
1197 return $this->outputStreamInstance;
1201 * Setter for a OutputStream instance
1203 * @param $outputStreamInstance The OutputStream instance
1206 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1207 $this->outputStreamInstance = $outputStreamInstance;
1211 * Setter for handler instance
1213 * @param $handlerInstance An instance of a Handleable class
1216 protected final function setHandlerInstance (Handleable $handlerInstance) {
1217 $this->handlerInstance = $handlerInstance;
1221 * Getter for handler instance
1223 * @return $handlerInstance A Networkable instance
1225 protected final function getHandlerInstance () {
1226 return $this->handlerInstance;
1230 * Setter for visitor instance
1232 * @param $visitorInstance A Visitor instance
1235 protected final function setVisitorInstance (Visitor $visitorInstance) {
1236 $this->visitorInstance = $visitorInstance;
1240 * Getter for visitor instance
1242 * @return $visitorInstance A Visitor instance
1244 protected final function getVisitorInstance () {
1245 return $this->visitorInstance;
1249 * Setter for DHT instance
1251 * @param $dhtInstance A Distributable instance
1254 protected final function setDhtInstance (Distributable $dhtInstance) {
1255 $this->dhtInstance = $dhtInstance;
1259 * Getter for DHT instance
1261 * @return $dhtInstance A Distributable instance
1263 protected final function getDhtInstance () {
1264 return $this->dhtInstance;
1268 * Setter for raw package Data
1270 * @param $packageData Raw package Data
1273 public final function setPackageData (array $packageData) {
1274 $this->packageData = $packageData;
1278 * Getter for raw package Data
1280 * @return $packageData Raw package Data
1282 public function getPackageData () {
1283 return $this->packageData;
1288 * Setter for Iterator instance
1290 * @param $iteratorInstance An instance of an Iterator
1293 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1294 $this->iteratorInstance = $iteratorInstance;
1298 * Getter for Iterator instance
1300 * @return $iteratorInstance An instance of an Iterator
1302 public final function getIteratorInstance () {
1303 return $this->iteratorInstance;
1307 * Setter for InputOutputPointer instance
1309 * @param $pointerInstance An instance of an InputOutputPointer class
1312 protected final function setPointerInstance (InputOutputPointer $pointerInstance) {
1313 $this->pointerInstance = $pointerInstance;
1317 * Getter for InputOutputPointer instance
1319 * @return $pointerInstance An instance of an InputOutputPointer class
1321 public final function getPointerInstance () {
1322 return $this->pointerInstance;
1326 * Setter for Indexable instance
1328 * @param $indexInstance An instance of an Indexable class
1331 protected final function setIndexInstance (Indexable $indexInstance) {
1332 $this->indexInstance = $indexInstance;
1336 * Getter for Indexable instance
1338 * @return $indexInstance An instance of an Indexable class
1340 public final function getIndexInstance () {
1341 return $this->indexInstance;
1345 * Setter for CalculatableBlock instance
1347 * @param $blockInstance An instance of an CalculatableBlock class
1350 protected final function setBlockInstance (CalculatableBlock $blockInstance) {
1351 $this->blockInstance = $blockInstance;
1355 * Getter for CalculatableBlock instance
1357 * @return $blockInstance An instance of an CalculatableBlock class
1359 public final function getBlockInstance () {
1360 return $this->blockInstance;
1364 * Checks whether an object equals this object. You should overwrite this
1365 * method to implement own equality checks
1367 * @param $objectInstance An instance of a FrameworkInterface object
1368 * @return $equals Whether both objects equals
1370 public function equals (FrameworkInterface $objectInstance) {
1373 $this->__toString() == $objectInstance->__toString()
1375 $this->hashCode() == $objectInstance->hashCode()
1378 // Return the result
1383 * Generates a generic hash code of this class. You should really overwrite
1384 * this method with your own hash code generator code. But keep KISS in mind.
1386 * @return $hashCode A generic hash code respresenting this whole class
1388 public function hashCode () {
1390 return crc32($this->__toString());
1394 * Formats computer generated price values into human-understandable formats
1395 * with thousand and decimal separators.
1397 * @param $value The in computer format value for a price
1398 * @param $currency The currency symbol (use HTML-valid characters!)
1399 * @param $decNum Number of decimals after commata
1400 * @return $price The for the current language formated price string
1401 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1402 * thousands separator
1405 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1406 // Are all required attriutes set?
1407 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1408 // Throw an exception
1409 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1413 $value = (float) $value;
1415 // Reformat the US number
1416 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1418 // Return as string...
1423 * Appends a trailing slash to a string
1425 * @param $str A string (maybe) without trailing slash
1426 * @return $str A string with an auto-appended trailing slash
1428 public final function addMissingTrailingSlash ($str) {
1429 // Is there a trailing slash?
1430 if (substr($str, -1, 1) != '/') {
1434 // Return string with trailing slash
1439 * Prepare the template engine (WebTemplateEngine by default) for a given
1440 * application helper instance (ApplicationHelper by default).
1442 * @param $applicationInstance An application helper instance or
1443 * null if we shall use the default
1444 * @return $templateInstance The template engine instance
1445 * @throws NullPointerException If the discovered application
1446 * instance is still null
1448 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1449 // Is the application instance set?
1450 if (is_null($applicationInstance)) {
1451 // Get the current instance
1452 $applicationInstance = $this->getApplicationInstance();
1455 if (is_null($applicationInstance)) {
1456 // Thrown an exception
1457 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1461 // Initialize the template engine
1462 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
1464 // Return the prepared instance
1465 return $templateInstance;
1469 * Debugs this instance by putting out it's full content
1471 * @param $message Optional message to show in debug output
1474 public final function debugInstance ($message = '') {
1475 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1476 restore_error_handler();
1481 // Is a message set?
1482 if (!empty($message)) {
1483 // Construct message
1484 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1487 // Generate the output
1488 $content .= sprintf('<pre>%s</pre>',
1491 print_r($this, TRUE)
1497 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>',
1498 $this->__toString(),
1500 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1505 * Replaces control characters with printable output
1507 * @param $str String with control characters
1508 * @return $str Replaced string
1510 protected function replaceControlCharacters ($str) {
1513 chr(13), '[r]', str_replace(
1514 chr(10), '[n]', str_replace(
1524 * Output a partial stub message for the caller method
1526 * @param $message An optional message to display
1529 protected function partialStub ($message = '') {
1530 // Get the backtrace
1531 $backtrace = debug_backtrace();
1533 // Generate the class::method string
1534 $methodName = 'UnknownClass->unknownMethod';
1535 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1536 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1539 // Construct the full message
1540 $stubMessage = sprintf('[%s:] Partial stub!',
1544 // Is the extra message given?
1545 if (!empty($message)) {
1546 // Then add it as well
1547 $stubMessage .= ' Message: ' . $message;
1550 // Debug instance is there?
1551 if (!is_null($this->getDebugInstance())) {
1552 // Output stub message
1553 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1556 trigger_error($stubMessage);
1562 * Outputs a debug backtrace and stops further script execution
1564 * @param $message An optional message to output
1565 * @param $doExit Whether exit the program (TRUE is default)
1568 public function debugBackTrace ($message = '', $doExit = TRUE) {
1569 // Sorry, there is no other way getting this nice backtrace
1570 if (!empty($message)) {
1572 printf('Message: %s<br />' . chr(10), $message);
1576 debug_print_backtrace();
1580 if ($doExit === TRUE) {
1586 * Creates an instance of a debugger instance
1588 * @param $className Name of the class (currently unsupported)
1589 * @return $debugInstance An instance of a debugger class
1591 public final static function createDebugInstance ($className) {
1592 // Is the instance set?
1593 if (!Registry::getRegistry()->instanceExists('debug')) {
1594 // Init debug instance
1595 $debugInstance = NULL;
1599 // Get a debugger instance
1600 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_class'));
1601 } catch (NullPointerException $e) {
1602 // Didn't work, no instance there
1603 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1606 // Empty string should be ignored and used for testing the middleware
1607 DebugMiddleware::getSelfInstance()->output('');
1609 // Set it in its own class. This will set it in the registry
1610 $debugInstance->setDebugInstance($debugInstance);
1612 // Get instance from registry
1613 $debugInstance = Registry::getRegistry()->getDebugInstance();
1617 return $debugInstance;
1621 * Simple output of a message with line-break
1623 * @param $message Message to output
1626 public function outputLine ($message) {
1628 print($message . PHP_EOL);
1632 * Outputs a debug message whether to debug instance (should be set!) or
1633 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1634 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1636 * @param $message Message we shall send out...
1637 * @param $doPrint Whether print or die here (default: print)
1638 * @paran $stripTags Whether to strip tags (default: FALSE)
1641 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1642 // Set debug instance to NULL
1643 $debugInstance = NULL;
1647 // Get debug instance
1648 $debugInstance = $this->getDebugInstance();
1649 } catch (NullPointerException $e) {
1650 // The debug instance is not set (yet)
1653 // Is the debug instance there?
1654 if (is_object($debugInstance)) {
1655 // Use debug output handler
1656 $debugInstance->output($message, $stripTags);
1658 if ($doPrint === FALSE) {
1659 // Die here if not printed
1663 // Are debug times enabled?
1664 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1666 $message = $this->getPrintableExecutionTime() . $message;
1670 if ($doPrint === TRUE) {
1672 $this->outputLine($message);
1681 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1683 * @param $str The string, what ever it is needs to be converted
1684 * @return $className Generated class name
1686 public function convertToClassName ($str) {
1690 // Convert all dashes in underscores
1691 $str = $this->convertDashesToUnderscores($str);
1693 // Now use that underscores to get classname parts for hungarian style
1694 foreach (explode('_', $str) as $strPart) {
1695 // Make the class name part lower case and first upper case
1696 $className .= ucfirst(strtolower($strPart));
1699 // Return class name
1704 * Converts dashes to underscores, e.g. useable for configuration entries
1706 * @param $str The string with maybe dashes inside
1707 * @return $str The converted string with no dashed, but underscores
1709 public final function convertDashesToUnderscores ($str) {
1711 $str = str_replace('-', '_', $str);
1713 // Return converted string
1718 * Marks up the code by adding e.g. line numbers
1720 * @param $phpCode Unmarked PHP code
1721 * @return $markedCode Marked PHP code
1723 public function markupCode ($phpCode) {
1728 $errorArray = error_get_last();
1730 // Init the code with error message
1731 if (is_array($errorArray)) {
1733 $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>',
1734 basename($errorArray['file']),
1735 $errorArray['line'],
1736 $errorArray['message'],
1741 // Add line number to the code
1742 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1744 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1746 htmlentities($code, ENT_QUOTES)
1755 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1756 * beatiful for web-based front-ends. If null is given a message id
1757 * null_timestamp will be resolved and returned.
1759 * @param $timestamp Timestamp to prepare (filter) for display
1760 * @return $readable A readable timestamp
1762 public function doFilterFormatTimestamp ($timestamp) {
1763 // Default value to return
1766 // Is the timestamp null?
1767 if (is_null($timestamp)) {
1768 // Get a message string
1769 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1771 switch ($this->getLanguageInstance()->getLanguageCode()) {
1772 case 'de': // German format is a bit different to default
1773 // Split the GMT stamp up
1774 $dateTime = explode(' ', $timestamp );
1775 $dateArray = explode('-', $dateTime[0]);
1776 $timeArray = explode(':', $dateTime[1]);
1778 // Construct the timestamp
1779 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1789 default: // Default is pass-through
1790 $readable = $timestamp;
1800 * Filter a given number into a localized number
1802 * @param $value The raw value from e.g. database
1803 * @return $localized Localized value
1805 public function doFilterFormatNumber ($value) {
1806 // Generate it from config and localize dependencies
1807 switch ($this->getLanguageInstance()->getLanguageCode()) {
1808 case 'de': // German format is a bit different to default
1809 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1812 default: // US, etc.
1813 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1822 * "Getter" for databse entry
1824 * @return $entry An array with database entries
1825 * @throws NullPointerException If the database result is not found
1826 * @throws InvalidDatabaseResultException If the database result is invalid
1828 protected final function getDatabaseEntry () {
1829 // Is there an instance?
1830 if (is_null($this->getResultInstance())) {
1831 // Throw an exception here
1832 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1836 $this->getResultInstance()->rewind();
1838 // Do we have an entry?
1839 if ($this->getResultInstance()->valid() === FALSE) {
1840 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1844 $this->getResultInstance()->next();
1847 $entry = $this->getResultInstance()->current();
1854 * Getter for field name
1856 * @param $fieldName Field name which we shall get
1857 * @return $fieldValue Field value from the user
1858 * @throws NullPointerException If the result instance is null
1860 public final function getField ($fieldName) {
1861 // Default field value
1864 // Get result instance
1865 $resultInstance = $this->getResultInstance();
1867 // Is this instance null?
1868 if (is_null($resultInstance)) {
1869 // Then the user instance is no longer valid (expired cookies?)
1870 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1873 // Get current array
1874 $fieldArray = $resultInstance->current();
1875 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
1877 // Convert dashes to underscore
1878 $fieldName = $this->convertDashesToUnderscores($fieldName);
1880 // Does the field exist?
1881 if (isset($fieldArray[$fieldName])) {
1883 $fieldValue = $fieldArray[$fieldName];
1885 // Missing field entry, may require debugging
1886 self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ':fieldname=' . $fieldName . ' not found!');
1894 * Flushs all pending updates to the database layer
1898 public function flushPendingUpdates () {
1899 // Get result instance
1900 $resultInstance = $this->getResultInstance();
1902 // Do we have data to update?
1903 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1904 // Get wrapper class name config entry
1905 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1907 // Create object instance
1908 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1910 // Yes, then send the whole result to the database layer
1911 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1916 * Outputs a deprecation warning to the developer.
1918 * @param $message The message we shall output to the developer
1920 * @todo Write a logging mechanism for productive mode
1922 public function deprecationWarning ($message) {
1923 // Is developer mode active?
1924 if (defined('DEVELOPER')) {
1925 // Debug instance is there?
1926 if (!is_null($this->getDebugInstance())) {
1927 // Output stub message
1928 self::createDebugInstance(__CLASS__)->debugOutput($message);
1931 trigger_error($message . "<br />\n");
1935 // @TODO Finish this part!
1936 $this->partialStub('Developer mode inactive. Message:' . $message);
1941 * Checks whether the given PHP extension is loaded
1943 * @param $phpExtension The PHP extension we shall check
1944 * @return $isLoaded Whether the PHP extension is loaded
1946 public final function isPhpExtensionLoaded ($phpExtension) {
1948 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1955 * "Getter" as a time() replacement but with milliseconds. You should use this
1956 * method instead of the encapsulated getimeofday() function.
1958 * @return $milliTime Timestamp with milliseconds
1960 public function getMilliTime () {
1961 // Get the time of day as float
1962 $milliTime = gettimeofday(TRUE);
1969 * Idles (sleeps) for given milliseconds
1971 * @return $hasSlept Whether it goes fine
1973 public function idle ($milliSeconds) {
1974 // Sleep is fine by default
1977 // Idle so long with found function
1978 if (function_exists('time_sleep_until')) {
1979 // Get current time and add idle time
1980 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1982 // New PHP 5.1.0 function found, ignore errors
1983 $hasSlept = @time_sleep_until($sleepUntil);
1986 * My Sun station doesn't have that function even with latest PHP
1989 usleep($milliSeconds * 1000);
1996 * Converts a hexadecimal string, even with negative sign as first string to
1997 * a decimal number using BC functions.
1999 * This work is based on comment #86673 on php.net documentation page at:
2000 * <http://de.php.net/manual/en/function.dechex.php#86673>
2002 * @param $hex Hexadecimal string
2003 * @return $dec Decimal number
2005 protected function hex2dec ($hex) {
2006 // Convert to all lower-case
2007 $hex = strtolower($hex);
2009 // Detect sign (negative/positive numbers)
2011 if (substr($hex, 0, 1) == '-') {
2013 $hex = substr($hex, 1);
2016 // Decode the hexadecimal string into a decimal number
2018 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2019 $factor = self::$hexdec[substr($hex, $i, 1)];
2020 $dec = bcadd($dec, bcmul($factor, $e));
2023 // Return the decimal number
2024 return $sign . $dec;
2028 * Converts even very large decimal numbers, also signed, to a hexadecimal
2031 * This work is based on comment #97756 on php.net documentation page at:
2032 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2034 * @param $dec Decimal number, even with negative sign
2035 * @param $maxLength Optional maximum length of the string
2036 * @return $hex Hexadecimal string
2038 protected function dec2hex ($dec, $maxLength = 0) {
2039 // maxLength can be zero or devideable by 2
2040 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2042 // Detect sign (negative/positive numbers)
2049 // Encode the decimal number into a hexadecimal string
2052 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2054 } while ($dec >= 1);
2057 * Leading zeros are required for hex-decimal "numbers". In some
2058 * situations more leading zeros are wanted, so check for both
2061 if ($maxLength > 0) {
2062 // Prepend more zeros
2063 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2064 } elseif ((strlen($hex) % 2) != 0) {
2065 // Only make string's length dividable by 2
2069 // Return the hexadecimal string
2070 return $sign . $hex;
2074 * Converts a ASCII string (0 to 255) into a decimal number.
2076 * @param $asc The ASCII string to be converted
2077 * @return $dec Decimal number
2079 protected function asc2dec ($asc) {
2080 // Convert it into a hexadecimal number
2081 $hex = bin2hex($asc);
2083 // And back into a decimal number
2084 $dec = $this->hex2dec($hex);
2091 * Converts a decimal number into an ASCII string.
2093 * @param $dec Decimal number
2094 * @return $asc An ASCII string
2096 protected function dec2asc ($dec) {
2097 // First convert the number into a hexadecimal string
2098 $hex = $this->dec2hex($dec);
2100 // Then convert it into the ASCII string
2101 $asc = $this->hex2asc($hex);
2108 * Converts a hexadecimal number into an ASCII string. Negative numbers
2111 * @param $hex Hexadecimal string
2112 * @return $asc An ASCII string
2114 protected function hex2asc ($hex) {
2115 // Check for length, it must be devideable by 2
2116 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2117 assert((strlen($hex) % 2) == 0);
2121 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2122 // Get the decimal number of the chunk
2123 $part = hexdec(substr($hex, $idx, 2));
2125 // Add it to the final string
2129 // Return the final string
2134 * Checks whether the given encoded data was encoded with Base64
2136 * @param $encodedData Encoded data we shall check
2137 * @return $isBase64 Whether the encoded data is Base64
2139 protected function isBase64Encoded ($encodedData) {
2141 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2148 * "Getter" to get response/request type from analysis of the system.
2150 * @return $responseType Analyzed response type
2152 protected function getResponseTypeFromSystem () {
2153 // Default is console
2154 $responseType = 'console';
2156 // Is 'HTTP_HOST' set?
2157 if (isset($_SERVER['HTTP_HOST'])) {
2158 // Then it is a HTTP response/request
2159 $responseType = 'http';
2163 return $responseType;
2167 * Gets a cache key from Criteria instance
2169 * @param $criteriaInstance An instance of a Criteria class
2170 * @param $onlyKeys Only use these keys for a cache key
2171 * @return $cacheKey A cache key suitable for lookup/storage purposes
2173 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2175 $cacheKey = sprintf('%s@%s',
2176 $this->__toString(),
2177 $criteriaInstance->getCacheKey($onlyKeys)
2181 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2186 * Getter for startup time in miliseconds
2188 * @return $startupTime Startup time in miliseconds
2190 protected function getStartupTime () {
2191 return self::$startupTime;
2195 * "Getter" for a printable currently execution time in nice braces
2197 * @return $executionTime Current execution time in nice braces
2199 protected function getPrintableExecutionTime () {
2200 // Caculate the execution time
2201 $executionTime = microtime(TRUE) - $this->getStartupTime();
2203 // Pack it in nice braces
2204 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2207 return $executionTime;
2211 * Hashes a given string with a simple but stronger hash function (no salt)
2212 * and hex-encode it.
2214 * @param $str The string to be hashed
2215 * @return $hash The hash from string $str
2217 public static final function hash ($str) {
2218 // Hash given string with (better secure) hasher
2219 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2226 * "Getter" for length of hash() output. This will be "cached" to speed up
2229 * @return $length Length of hash() output
2231 public static final function getHashLength () {
2233 if (is_null(self::$hashLength)) {
2234 // No, then hash a string and save its length.
2235 self::$hashLength = strlen(self::hash('abc123'));
2239 return self::$hashLength;
2243 * Checks whether the given number is really a number (only chars 0-9).
2245 * @param $num A string consisting only chars between 0 and 9
2246 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2247 * @param $assertMismatch Whether to assert mismatches
2248 * @return $ret The (hopefully) secured numbered value
2250 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2251 // Filter all numbers out
2252 $ret = preg_replace('/[^0123456789]/', '', $num);
2255 if ($castValue === TRUE) {
2256 // Cast to biggest numeric type
2257 $ret = (double) $ret;
2260 // Assert only if requested
2261 if ($assertMismatch === TRUE) {
2262 // Has the whole value changed?
2263 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2271 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2273 * @param $num A string consisting only chars between 0 and 9
2274 * @param $assertMismatch Whether to assert mismatches
2275 * @return $ret The (hopefully) secured hext-numbered value
2277 public function hexval ($num, $assertMismatch = FALSE) {
2278 // Filter all numbers out
2279 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2281 // Assert only if requested
2282 if ($assertMismatch === TRUE) {
2283 // Has the whole value changed?
2284 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2292 * Checks whether start/end marker are set
2294 * @param $data Data to be checked
2295 * @return $isset Whether start/end marker are set
2297 public final function ifStartEndMarkersSet ($data) {
2299 $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));
2301 // ... and return it
2306 * Determines if an element is set in the generic array
2308 * @param $keyGroup Main group for the key
2309 * @param $subGroup Sub group for the key
2310 * @param $key Key to check
2311 * @param $element Element to check
2312 * @return $isset Whether the given key is set
2314 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2316 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2319 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2325 * Determines if a key is set in the generic array
2327 * @param $keyGroup Main group for the key
2328 * @param $subGroup Sub group for the key
2329 * @param $key Key to check
2330 * @return $isset Whether the given key is set
2332 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2334 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2337 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2345 * Determines if a group is set in the generic array
2347 * @param $keyGroup Main group
2348 * @param $subGroup Sub group
2349 * @return $isset Whether the given group is set
2351 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2353 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2356 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2363 * Getter for sub key group
2365 * @param $keyGroup Main key group
2366 * @param $subGroup Sub key group
2367 * @return $array An array with all array elements
2369 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2371 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2372 // No, then abort here
2373 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2378 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2381 return $this->genericArray[$keyGroup][$subGroup];
2385 * Unsets a given key in generic array
2387 * @param $keyGroup Main group for the key
2388 * @param $subGroup Sub group for the key
2389 * @param $key Key to unset
2392 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2394 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2397 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2401 * Unsets a given element in generic array
2403 * @param $keyGroup Main group for the key
2404 * @param $subGroup Sub group for the key
2405 * @param $key Key to unset
2406 * @param $element Element to unset
2409 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2411 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2414 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2418 * Append a string to a given generic array key
2420 * @param $keyGroup Main group for the key
2421 * @param $subGroup Sub group for the key
2422 * @param $key Key to unset
2423 * @param $value Value to add/append
2426 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2428 //* 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);
2430 // Is it already there?
2431 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2433 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2436 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2441 * Append a string to a given generic array element
2443 * @param $keyGroup Main group for the key
2444 * @param $subGroup Sub group for the key
2445 * @param $key Key to unset
2446 * @param $element Element to check
2447 * @param $value Value to add/append
2450 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2452 //* 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);
2454 // Is it already there?
2455 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2457 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2460 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2465 * Initializes given generic array group
2467 * @param $keyGroup Main group for the key
2468 * @param $subGroup Sub group for the key
2469 * @param $key Key to use
2470 * @param $forceInit Optionally force initialization
2473 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2475 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2477 // Is it already set?
2478 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2479 // Already initialized
2480 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2485 $this->genericArray[$keyGroup][$subGroup] = array();
2489 * Initializes given generic array key
2491 * @param $keyGroup Main group for the key
2492 * @param $subGroup Sub group for the key
2493 * @param $key Key to use
2494 * @param $forceInit Optionally force initialization
2497 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2499 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2501 // Is it already set?
2502 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2503 // Already initialized
2504 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2509 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2513 * Initializes given generic array element
2515 * @param $keyGroup Main group for the key
2516 * @param $subGroup Sub group for the key
2517 * @param $key Key to use
2518 * @param $element Element to use
2519 * @param $forceInit Optionally force initialization
2522 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2524 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2526 // Is it already set?
2527 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2528 // Already initialized
2529 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2534 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2538 * Pushes an element to a generic key
2540 * @param $keyGroup Main group for the key
2541 * @param $subGroup Sub group for the key
2542 * @param $key Key to use
2543 * @param $value Value to add/append
2544 * @return $count Number of array elements
2546 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2548 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2551 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2553 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2557 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2560 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2561 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2566 * Pushes an element to a generic array element
2568 * @param $keyGroup Main group for the key
2569 * @param $subGroup Sub group for the key
2570 * @param $key Key to use
2571 * @param $element Element to check
2572 * @param $value Value to add/append
2573 * @return $count Number of array elements
2575 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2577 //* 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));
2580 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2582 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2586 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2589 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2590 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2595 * Pops an element from a generic group
2597 * @param $keyGroup Main group for the key
2598 * @param $subGroup Sub group for the key
2599 * @param $key Key to unset
2600 * @return $value Last "popped" value
2602 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2604 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2607 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2609 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2614 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2617 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2618 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2623 * Shifts an element from a generic group
2625 * @param $keyGroup Main group for the key
2626 * @param $subGroup Sub group for the key
2627 * @param $key Key to unset
2628 * @return $value Last "popped" value
2630 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2632 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2635 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2637 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2642 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2645 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2646 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2651 * Count generic array group
2653 * @param $keyGroup Main group for the key
2654 * @return $count Count of given group
2656 protected final function countGenericArray ($keyGroup) {
2658 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2661 if (!isset($this->genericArray[$keyGroup])) {
2663 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2668 $count = count($this->genericArray[$keyGroup]);
2671 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2678 * Count generic array sub group
2680 * @param $keyGroup Main group for the key
2681 * @param $subGroup Sub group for the key
2682 * @return $count Count of given group
2684 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2686 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2689 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2691 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2696 $count = count($this->genericArray[$keyGroup][$subGroup]);
2699 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2706 * Count generic array elements
2708 * @param $keyGroup Main group for the key
2709 * @param $subGroup Sub group for the key
2710 * @para $key Key to count
2711 * @return $count Count of given key
2713 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2715 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2718 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2720 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2722 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2724 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2729 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2732 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2739 * Getter for whole generic group array
2741 * @param $keyGroup Key group to get
2742 * @return $array Whole generic array group
2744 protected final function getGenericArray ($keyGroup) {
2746 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2749 if (!isset($this->genericArray[$keyGroup])) {
2751 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2756 return $this->genericArray[$keyGroup];
2760 * Setter for generic array key
2762 * @param $keyGroup Key group to get
2763 * @param $subGroup Sub group for the key
2764 * @param $key Key to unset
2765 * @param $value Mixed value from generic array element
2768 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2770 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2773 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2777 * Getter for generic array key
2779 * @param $keyGroup Key group to get
2780 * @param $subGroup Sub group for the key
2781 * @param $key Key to unset
2782 * @return $value Mixed value from generic array element
2784 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2786 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2789 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2791 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2796 return $this->genericArray[$keyGroup][$subGroup][$key];
2800 * Sets a value in given generic array key/element
2802 * @param $keyGroup Main group for the key
2803 * @param $subGroup Sub group for the key
2804 * @param $key Key to set
2805 * @param $element Element to set
2806 * @param $value Value to set
2809 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2811 //* 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));
2814 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2818 * Getter for generic array element
2820 * @param $keyGroup Key group to get
2821 * @param $subGroup Sub group for the key
2822 * @param $key Key to look for
2823 * @param $element Element to look for
2824 * @return $value Mixed value from generic array element
2826 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2828 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2831 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2833 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2838 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2842 * Checks if a given sub group is valid (array)
2844 * @param $keyGroup Key group to get
2845 * @param $subGroup Sub group for the key
2846 * @return $isValid Whether given sub group is valid
2848 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2850 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2853 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
2860 * Checks if a given key is valid (array)
2862 * @param $keyGroup Key group to get
2863 * @param $subGroup Sub group for the key
2864 * @param $key Key to check
2865 * @return $isValid Whether given sub group is valid
2867 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
2869 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2872 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
2879 * Translates boolean TRUE to 'Y' and FALSE to 'N'
2881 * @param $boolean Boolean value
2882 * @return $translated Translated boolean value
2884 public static final function translateBooleanToYesNo ($boolean) {
2885 // Make sure it is really boolean
2886 assert(is_bool($boolean));
2889 $translated = ($boolean === TRUE) ? 'Y' : 'N';
2891 // ... and return it
2896 * Initializes counter for valid entries, arrays for damaged entries and
2897 * an array for gap seek positions. If you call this method on your own,
2898 * please re-analyze the file structure. So you are better to call
2899 * analyzeFile() instead of this method.
2903 protected function initCountersGapsArray () {
2904 // Init counter and seek position
2905 $this->setCounter(0);
2906 $this->setSeekPosition(0);
2909 $this->gaps = array();
2910 $this->damagedEntries = array();
2914 * Getter for total entries
2916 * @return $totalEntries Total entries in this file
2918 protected final function getCounter () {
2920 return $this->totalEntries;
2924 * Setter for total entries
2926 * @param $totalEntries Total entries in this file
2929 protected final function setCounter ($counter) {
2931 $this->totalEntries = $counter;
2939 protected final function incrementCounter () {
2941 $this->totalEntries++;
2945 * Getter for header size
2947 * @return $totalEntries Size of file header
2949 public final function getHeaderSize () {
2951 return $this->headerSize;
2955 * Setter for header size
2957 * @param $headerSize Size of file header
2960 protected final function setHeaderSize ($headerSize) {
2962 $this->headerSize = $headerSize;
2966 * Getter for header array
2968 * @return $totalEntries Size of file header
2970 protected final function getHeade () {
2972 return $this->header;
2978 * @param $header Array for a file header
2981 protected final function setHeader (array $header) {
2983 $this->header = $header;
2987 * Getter for seek position
2989 * @return $seekPosition Current seek position (stored here in object)
2991 protected final function getSeekPosition () {
2993 return $this->seekPosition;
2997 * Setter for seek position
2999 * @param $seekPosition Current seek position (stored here in object)
3002 protected final function setSeekPosition ($seekPosition) {
3004 $this->seekPosition = $seekPosition;
3008 * Updates seekPosition attribute from file to avoid to much access on file.
3012 protected function updateSeekPosition () {
3013 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3015 // Get key (= seek position)
3016 $seekPosition = $this->getIteratorInstance()->key();
3017 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Setting seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
3020 $this->setSeekPosition($seekPosition);
3022 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
3026 * Checks whether the file header is initialized
3028 * @return $isInitialized Whether the file header is initialized
3030 protected function isFileHeaderInitialized () {
3031 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3033 // Is the method there?
3034 assert(is_callable(array($this, 'readFileHeader')));
3036 // Default is not initialized
3037 $isInitialized = FALSE;
3039 // Is the file initialized?
3040 if ($this->isFileInitialized()) {
3041 // Some bytes has been written, so rewind to start of it.
3042 $rewindStatus = $this->getIteratorInstance()->rewind();
3043 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] rewindStatus=%s', __METHOD__, __LINE__, $rewindStatus));
3045 // Is the rewind() call successfull?
3046 if ($rewindStatus != 1) {
3047 // Something bad happened
3048 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Could not rewind().', __METHOD__, __LINE__));
3052 $this->readFileHeader();
3054 // The above method does already check the header
3055 $isInitialized = TRUE;
3059 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
3060 return $isInitialized;
3064 * Checks whether the assigned file has been initialized
3066 * @return $isInitialized Whether the file's size is zero
3068 protected function isFileInitialized () {
3069 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3071 // Get it from iterator which holds the pointer instance. If FALSE is returned
3072 $fileSize = $this->getIteratorInstance()->size();
3073 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] fileSize=%s', __METHOD__, __LINE__, $fileSize));
3076 * The returned file size should not be FALSE or NULL as this means
3077 * that the pointer class does not work correctly.
3079 assert(is_int($fileSize));
3081 // Is more than 0 returned?
3082 $isInitialized = ($fileSize > 0);
3085 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
3086 return $isInitialized;
3090 * Creates the assigned file
3094 protected function createFileHeader () {
3095 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3097 // The method flushFileHeader() must be callable
3098 assert(is_callable(array($this, 'flushFileHeader')));
3100 // The file's header should not be initialized here
3101 assert(!$this->isFileHeaderInitialized());
3103 // Simple flush file header which will create it.
3104 $this->flushFileHeader();
3106 // Rewind seek position (to beginning of file) and update/flush file header
3107 $this->rewineUpdateSeekPosition();
3109 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!!', __METHOD__, __LINE__));
3113 * Seeks to beginning of file, updates seek position in this object and
3114 * flushes the header.
3118 protected function rewineUpdateSeekPosition () {
3119 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3121 // Seek to beginning of file
3122 $this->getIteratorInstance()->rewind();
3124 // And update seek position ...
3125 $this->updateSeekPosition();
3127 // ... to write it back into the file
3128 $this->flushFileHeader();
3130 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!!', __METHOD__, __LINE__));
3134 * Seeks to old position
3138 protected function seekToOldPosition () {
3139 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3141 // Seek to currently ("old") saved position
3142 $this->getIteratorInstance()->seek($this->getSeekPosition());
3144 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!!', __METHOD__, __LINE__));
3148 * Writes data at given position
3150 * @param $seekPosition Seek position
3151 * @param $data Data to be written
3152 * @param $flushHeader Whether to flush the header (default: flush)
3155 protected function writeData ($seekPosition, $data, $flushHeader = TRUE) {
3156 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data()=%s - CALLED!', __METHOD__, __LINE__, $seekPosition, strlen($data)));
3158 // Write data at given position
3159 $this->getIteratorInstance()->writeAtPosition($seekPosition, $data);
3161 // Update seek position
3162 $this->updateSeekPosition();
3164 // Flush the header?
3165 if ($flushHeader === TRUE) {
3167 $this->flushFileHeader();
3169 // Seek to old position
3170 $this->seekToOldPosition();
3173 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
3177 * Pre-allocates file (if enabled) with some space for later faster write access.
3179 * @param $type Type of the file
3182 protected function preAllocateFile ($type) {
3183 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3185 // caluclateMinimumBlockLength() must be callable
3186 assert(is_callable(array($this, 'caluclateMinimumBlockLength')));
3189 if ($this->getConfigInstance()->getConfigEntry($type . '_pre_allocate_enabled') != 'Y') {
3191 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Not pre-allocating file.', __METHOD__, __LINE__));
3193 // Don't continue here.
3198 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Pre-allocating file ...', __METHOD__, __LINE__));
3200 // Calculate minimum length for one entry
3201 $minLengthEntry = $this->caluclateMinimumBlockLength();
3202 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] minLengthEntry=%s', __METHOD__, __LINE__, $minLengthEntry));
3204 // Calulcate seek position
3205 $seekPosition = $minLengthEntry * $this->getConfigInstance()->getConfigEntry($type . '_pre_allocate_count');
3206 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
3208 // Now simply write a NUL there. This will pre-allocate the file.
3209 $this->writeData($seekPosition, chr(0));
3211 // Rewind seek position (to beginning of file) and update/flush file header
3212 $this->rewineUpdateSeekPosition();
3214 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
3218 * Checks whether the block separator has been found
3220 * @param $str String to look in
3221 * @return $isFound Whether the block separator has been found
3223 public function isBlockSeparatorFound ($str) {
3225 $isFound = (strpos($str, self::getBlockSeparator()) !== FALSE);
3232 * Getter for block separator character(s)
3234 * @return $blockSeparator A separator for blocks
3236 protected static final function getBlockSeparator () {
3237 return chr(self::SEPARATOR_ENTRIES);