3 * The simulator system class is the super class of all other classes. This
4 * class handles saving of games etc.
6 * @author Roland Haeder <webmaster@shipsimu.org>
8 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2013 Core Developer Team
9 * @license GNU GPL 3.0 or any newer version
10 * @link http://www.shipsimu.org
12 * This program is free software: you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation, either version 3 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
29 const LENGTH_COUNT = 20;
34 const LENGTH_POSITION = 20;
39 private $realClass = 'BaseFrameworkSystem';
42 * Instance of a request class
44 private $requestInstance = NULL;
47 * Instance of a response class
49 private $responseInstance = NULL;
52 * Search criteria instance
54 private $searchInstance = NULL;
57 * Update criteria instance
59 private $updateInstance = NULL;
62 * The file I/O instance for the template loader
64 private $fileIoInstance = NULL;
69 private $resolverInstance = NULL;
72 * Template engine instance
74 private $templateInstance = NULL;
77 * Database result instance
79 private $resultInstance = NULL;
82 * Instance for user class
84 private $userInstance = NULL;
87 * A controller instance
89 private $controllerInstance = NULL;
94 private $rngInstance = NULL;
97 * Instance of a crypto helper
99 private $cryptoInstance = NULL;
102 * Instance of an Iterator class
104 private $iteratorInstance = NULL;
107 * Instance of the list
109 private $listInstance = NULL;
114 private $menuInstance = NULL;
117 * Instance of the image
119 private $imageInstance = NULL;
122 * Instance of the stacker
124 private $stackerInstance = NULL;
127 * A Compressor instance
129 private $compressorInstance = NULL;
132 * A Parseable instance
134 private $parserInstance = NULL;
137 * A ProtocolHandler instance
139 private $protocolInstance = NULL;
142 * A database wrapper instance
144 private $databaseInstance = NULL;
147 * A helper instance for the form
149 private $helperInstance = NULL;
152 * An instance of a Sourceable class
154 private $sourceInstance = NULL;
157 * An instance of a InputStream class
159 private $inputStreamInstance = NULL;
162 * An instance of a OutputStream class
164 private $outputStreamInstance = NULL;
167 * Networkable handler instance
169 private $handlerInstance = NULL;
172 * Visitor handler instance
174 private $visitorInstance = NULL;
179 private $dhtInstance = NULL;
182 * An instance of a database wrapper class
184 private $wrapperInstance = NULL;
187 * An instance of a file I/O pointer class (not handler)
189 private $pointerInstance = NULL;
192 * An instance of an Indexable class
194 private $indexInstance = NULL;
197 * An instance of a CalculatableBlock class
199 private $blockInstance = NULL;
202 * Thousands separator
204 private $thousands = '.'; // German
209 private $decimals = ','; // German
214 private $socketResource = FALSE;
219 private $packageData = array();
224 private $genericArray = array();
227 * Length of output from hash()
229 private static $hashLength = NULL;
232 * Counter for total entries
234 private $totalEntries = 0;
237 * Current seek position
239 private $seekPosition = 0;
244 private $headerSize = 0;
249 private $header = array();
252 * Seek positions for gaps ("fragmentation")
254 private $gaps = array();
257 * Seek positions for damaged entries (e.g. mismatching hash sum, ...)
259 private $damagedEntries = array();
261 /***********************
262 * Exception codes.... *
263 ***********************/
265 // @todo Try to clean these constants up
266 const EXCEPTION_IS_NULL_POINTER = 0x001;
267 const EXCEPTION_IS_NO_OBJECT = 0x002;
268 const EXCEPTION_IS_NO_ARRAY = 0x003;
269 const EXCEPTION_MISSING_METHOD = 0x004;
270 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
271 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
272 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
273 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
274 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
275 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
276 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
277 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
278 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
279 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
280 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
281 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
282 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
283 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
284 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
285 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
286 const EXCEPTION_PATH_NOT_FOUND = 0x015;
287 const EXCEPTION_INVALID_PATH_NAME = 0x016;
288 const EXCEPTION_READ_PROTECED_PATH = 0x017;
289 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
290 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
291 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
292 const EXCEPTION_INVALID_RESOURCE = 0x01b;
293 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
294 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
295 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
296 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
297 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
298 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
299 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
300 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
301 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
302 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
303 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
304 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
305 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
306 const EXCEPTION_INVALID_STRING = 0x029;
307 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
308 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
309 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
310 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
311 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
312 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
313 const EXCEPTION_MISSING_ELEMENT = 0x030;
314 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
315 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
316 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
317 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
318 const EXCEPTION_FATAL_ERROR = 0x035;
319 const EXCEPTION_FILE_NOT_FOUND = 0x036;
320 const EXCEPTION_ASSERTION_FAILED = 0x037;
321 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
322 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
323 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03a;
326 * Hexadecimal->Decimal translation array
328 private static $hexdec = array(
348 * Decimal->hexadecimal translation array
350 private static $dechex = array(
370 * Startup time in miliseconds
372 private static $startupTime = 0;
375 * Protected super constructor
377 * @param $className Name of the class
380 protected function __construct ($className) {
382 $this->setRealClass($className);
384 // Set configuration instance if no registry ...
385 if (!$this instanceof Register) {
386 // ... because registries doesn't need to be configured
387 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
390 // Is the startup time set? (0 cannot be TRUE anymore)
391 if (self::$startupTime == 0) {
393 self::$startupTime = microtime(TRUE);
398 * Destructor for all classes
402 public function __destruct () {
403 // Flush any updated entries to the database
404 $this->flushPendingUpdates();
406 // Is this object already destroyed?
407 if ($this->__toString() != 'DestructedObject') {
408 // Destroy all informations about this class but keep some text about it alive
409 $this->setRealClass('DestructedObject');
410 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
411 // Already destructed object
412 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
417 // Do not call this twice
418 trigger_error(__METHOD__ . ': Called twice.');
424 * The __call() method where all non-implemented methods end up
426 * @param $methodName Name of the missing method
427 * @args $args Arguments passed to the method
430 public final function __call ($methodName, $args) {
431 return self::__callStatic($methodName, $args);
435 * The __callStatic() method where all non-implemented static methods end up
437 * @param $methodName Name of the missing method
438 * @args $args Arguments passed to the method
441 public static final function __callStatic ($methodName, $args) {
442 // Init argument string
445 // Is it empty or an array?
448 $argsString = 'NULL';
449 } elseif (is_array($args)) {
450 // Some arguments are there
451 foreach ($args as $arg) {
452 // Add the value itself if not array. This prevents 'array to string conversion' message
453 if (is_array($arg)) {
454 $argsString .= 'Array';
459 // Add data about the argument
460 $argsString .= ' (' . gettype($arg);
462 if (is_string($arg)) {
463 // Add length for strings
464 $argsString .= ', ' . strlen($arg);
465 } elseif (is_array($arg)) {
466 // .. or size if array
467 $argsString .= ', ' . count($arg);
468 } elseif ($arg === TRUE) {
469 // ... is boolean 'TRUE'
470 $argsString .= ', TRUE';
471 } elseif ($arg === FALSE) {
472 // ... is boolean 'FALSE'
473 $argsString .= ', FALSE';
477 $argsString .= '), ';
481 if (substr($argsString, -2, 1) == ',') {
482 $argsString = substr($argsString, 0, -2);
485 // Invalid arguments!
486 $argsString = '!INVALID:' . gettype($args) . '!';
489 // Output stub message
490 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
491 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
501 * Getter for $realClass
503 * @return $realClass The name of the real class (not BaseFrameworkSystem)
505 public function __toString () {
506 return $this->realClass;
510 * Magic function to catch setting of missing but set class fields/attributes
512 * @param $name Name of the field/attribute
513 * @param $value Value to store
516 public final function __set ($name, $value) {
517 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
520 print_r($value, TRUE)
525 * Magic function to catch getting of missing fields/attributes
527 * @param $name Name of the field/attribute
530 public final function __get ($name) {
531 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
537 * Magic function to catch unsetting of missing fields/attributes
539 * @param $name Name of the field/attribute
542 public final function __unset ($name) {
543 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
549 * Setter for the real class name
551 * @param $realClass Class name (string)
554 public final function setRealClass ($realClass) {
556 $this->realClass = (string) $realClass;
560 * Setter for database result instance
562 * @param $resultInstance An instance of a database result class
564 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
566 protected final function setResultInstance (SearchableResult $resultInstance) {
567 $this->resultInstance = $resultInstance;
571 * Getter for database result instance
573 * @return $resultInstance An instance of a database result class
575 public final function getResultInstance () {
576 return $this->resultInstance;
580 * Setter for template engine instances
582 * @param $templateInstance An instance of a template engine class
585 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
586 $this->templateInstance = $templateInstance;
590 * Getter for template engine instances
592 * @return $templateInstance An instance of a template engine class
594 protected final function getTemplateInstance () {
595 return $this->templateInstance;
599 * Setter for search instance
601 * @param $searchInstance Searchable criteria instance
604 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
605 $this->searchInstance = $searchInstance;
609 * Getter for search instance
611 * @return $searchInstance Searchable criteria instance
613 public final function getSearchInstance () {
614 return $this->searchInstance;
618 * Setter for update instance
620 * @param $updateInstance Searchable criteria instance
623 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
624 $this->updateInstance = $updateInstance;
628 * Getter for update instance
630 * @return $updateInstance Updateable criteria instance
632 public final function getUpdateInstance () {
633 return $this->updateInstance;
637 * Setter for resolver instance
639 * @param $resolverInstance Instance of a command resolver class
642 public final function setResolverInstance (Resolver $resolverInstance) {
643 $this->resolverInstance = $resolverInstance;
647 * Getter for resolver instance
649 * @return $resolverInstance Instance of a command resolver class
651 public final function getResolverInstance () {
652 return $this->resolverInstance;
656 * Setter for language instance
658 * @param $configInstance The configuration instance which shall
659 * be FrameworkConfiguration
662 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
663 Registry::getRegistry()->addInstance('config', $configInstance);
667 * Getter for configuration instance
669 * @return $configInstance Configuration instance
671 public final function getConfigInstance () {
672 $configInstance = Registry::getRegistry()->getInstance('config');
673 return $configInstance;
677 * Setter for debug instance
679 * @param $debugInstance The instance for debug output class
682 public final function setDebugInstance (DebugMiddleware $debugInstance) {
683 Registry::getRegistry()->addInstance('debug', $debugInstance);
687 * Getter for debug instance
689 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
691 public final function getDebugInstance () {
692 // Get debug instance
693 $debugInstance = Registry::getRegistry()->getInstance('debug');
696 return $debugInstance;
700 * Setter for web output instance
702 * @param $webInstance The instance for web output class
705 public final function setWebOutputInstance (OutputStreamer $webInstance) {
706 Registry::getRegistry()->addInstance('web_output', $webInstance);
710 * Getter for web output instance
712 * @return $webOutputInstance - Instance to class WebOutput
714 public final function getWebOutputInstance () {
715 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
716 return $webOutputInstance;
720 * Setter for database instance
722 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
725 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
726 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
730 * Getter for database layer
732 * @return $databaseInstance The database layer instance
734 public final function getDatabaseInstance () {
736 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
739 return $databaseInstance;
743 * Setter for compressor channel
745 * @param $compressorInstance An instance of CompressorChannel
748 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
749 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
753 * Getter for compressor channel
755 * @return $compressorInstance The compressor channel
757 public final function getCompressorChannel () {
758 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
759 return $compressorInstance;
763 * Protected getter for a manageable application helper class
765 * @return $applicationInstance An instance of a manageable application helper class
767 protected final function getApplicationInstance () {
768 $applicationInstance = Registry::getRegistry()->getInstance('application');
769 return $applicationInstance;
773 * Setter for a manageable application helper class
775 * @param $applicationInstance An instance of a manageable application helper class
778 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
779 Registry::getRegistry()->addInstance('application', $applicationInstance);
783 * Setter for request instance
785 * @param $requestInstance An instance of a Requestable class
788 public final function setRequestInstance (Requestable $requestInstance) {
789 $this->requestInstance = $requestInstance;
793 * Getter for request instance
795 * @return $requestInstance An instance of a Requestable class
797 public final function getRequestInstance () {
798 return $this->requestInstance;
802 * Setter for response instance
804 * @param $responseInstance An instance of a Responseable class
807 public final function setResponseInstance (Responseable $responseInstance) {
808 $this->responseInstance = $responseInstance;
812 * Getter for response instance
814 * @return $responseInstance An instance of a Responseable class
816 public final function getResponseInstance () {
817 return $this->responseInstance;
821 * Private getter for language instance
823 * @return $langInstance An instance to the language sub-system
825 protected final function getLanguageInstance () {
826 $langInstance = Registry::getRegistry()->getInstance('language');
827 return $langInstance;
831 * Setter for language instance
833 * @param $langInstance An instance to the language sub-system
835 * @see LanguageSystem
837 public final function setLanguageInstance (ManageableLanguage $langInstance) {
838 Registry::getRegistry()->addInstance('language', $langInstance);
842 * Private getter for file IO instance
844 * @return $fileIoInstance An instance to the file I/O sub-system
846 protected final function getFileIoInstance () {
847 return $this->fileIoInstance;
851 * Setter for file I/O instance
853 * @param $fileIoInstance An instance to the file I/O sub-system
856 public final function setFileIoInstance (IoHandler $fileIoInstance) {
857 $this->fileIoInstance = $fileIoInstance;
861 * Protected setter for user instance
863 * @param $userInstance An instance of a user class
866 protected final function setUserInstance (ManageableAccount $userInstance) {
867 $this->userInstance = $userInstance;
871 * Getter for user instance
873 * @return $userInstance An instance of a user class
875 public final function getUserInstance () {
876 return $this->userInstance;
880 * Setter for controller instance (this surely breaks a bit the MVC patterm)
882 * @param $controllerInstance An instance of the controller
885 public final function setControllerInstance (Controller $controllerInstance) {
886 $this->controllerInstance = $controllerInstance;
890 * Getter for controller instance (this surely breaks a bit the MVC patterm)
892 * @return $controllerInstance An instance of the controller
894 public final function getControllerInstance () {
895 return $this->controllerInstance;
899 * Setter for RNG instance
901 * @param $rngInstance An instance of a random number generator (RNG)
904 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
905 $this->rngInstance = $rngInstance;
909 * Getter for RNG instance
911 * @return $rngInstance An instance of a random number generator (RNG)
913 public final function getRngInstance () {
914 return $this->rngInstance;
918 * Setter for Cryptable instance
920 * @param $cryptoInstance An instance of a Cryptable class
923 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
924 $this->cryptoInstance = $cryptoInstance;
928 * Getter for Cryptable instance
930 * @return $cryptoInstance An instance of a Cryptable class
932 public final function getCryptoInstance () {
933 return $this->cryptoInstance;
937 * Setter for the list instance
939 * @param $listInstance A list of Listable
942 protected final function setListInstance (Listable $listInstance) {
943 $this->listInstance = $listInstance;
947 * Getter for the list instance
949 * @return $listInstance A list of Listable
951 protected final function getListInstance () {
952 return $this->listInstance;
956 * Setter for the menu instance
958 * @param $menuInstance A RenderableMenu instance
961 protected final function setMenuInstance (RenderableMenu $menuInstance) {
962 $this->menuInstance = $menuInstance;
966 * Getter for the menu instance
968 * @return $menuInstance A RenderableMenu instance
970 protected final function getMenuInstance () {
971 return $this->menuInstance;
975 * Setter for image instance
977 * @param $imageInstance An instance of an image
980 public final function setImageInstance (BaseImage $imageInstance) {
981 $this->imageInstance = $imageInstance;
985 * Getter for image instance
987 * @return $imageInstance An instance of an image
989 public final function getImageInstance () {
990 return $this->imageInstance;
994 * Setter for stacker instance
996 * @param $stackerInstance An instance of an stacker
999 public final function setStackerInstance (Stackable $stackerInstance) {
1000 $this->stackerInstance = $stackerInstance;
1004 * Getter for stacker instance
1006 * @return $stackerInstance An instance of an stacker
1008 public final function getStackerInstance () {
1009 return $this->stackerInstance;
1013 * Setter for compressor instance
1015 * @param $compressorInstance An instance of an compressor
1018 public final function setCompressorInstance (Compressor $compressorInstance) {
1019 $this->compressorInstance = $compressorInstance;
1023 * Getter for compressor instance
1025 * @return $compressorInstance An instance of an compressor
1027 public final function getCompressorInstance () {
1028 return $this->compressorInstance;
1032 * Setter for Parseable instance
1034 * @param $parserInstance An instance of an Parseable
1037 public final function setParserInstance (Parseable $parserInstance) {
1038 $this->parserInstance = $parserInstance;
1042 * Getter for Parseable instance
1044 * @return $parserInstance An instance of an Parseable
1046 public final function getParserInstance () {
1047 return $this->parserInstance;
1051 * Setter for ProtocolHandler instance
1053 * @param $protocolInstance An instance of an ProtocolHandler
1056 public final function setProtocolInstance (ProtocolHandler $protocolInstance = NULL) {
1057 $this->protocolInstance = $protocolInstance;
1061 * Getter for ProtocolHandler instance
1063 * @return $protocolInstance An instance of an ProtocolHandler
1065 public final function getProtocolInstance () {
1066 return $this->protocolInstance;
1070 * Setter for DatabaseWrapper instance
1072 * @param $wrapperInstance An instance of an DatabaseWrapper
1075 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1076 $this->wrapperInstance = $wrapperInstance;
1080 * Getter for DatabaseWrapper instance
1082 * @return $wrapperInstance An instance of an DatabaseWrapper
1084 public final function getWrapperInstance () {
1085 return $this->wrapperInstance;
1089 * Setter for socket resource
1091 * @param $socketResource A valid socket resource
1094 public final function setSocketResource ($socketResource) {
1095 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1096 $this->socketResource = $socketResource;
1100 * Getter for socket resource
1102 * @return $socketResource A valid socket resource
1104 public final function getSocketResource () {
1105 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1106 return $this->socketResource;
1110 * Setter for helper instance
1112 * @param $helperInstance An instance of a helper class
1115 protected final function setHelperInstance (Helper $helperInstance) {
1116 $this->helperInstance = $helperInstance;
1120 * Getter for helper instance
1122 * @return $helperInstance An instance of a helper class
1124 public final function getHelperInstance () {
1125 return $this->helperInstance;
1129 * Setter for a Sourceable instance
1131 * @param $sourceInstance The Sourceable instance
1134 protected final function setSourceInstance (Sourceable $sourceInstance) {
1135 $this->sourceInstance = $sourceInstance;
1139 * Getter for a Sourceable instance
1141 * @return $sourceInstance The Sourceable instance
1143 protected final function getSourceInstance () {
1144 return $this->sourceInstance;
1148 * Getter for a InputStream instance
1150 * @param $inputStreamInstance The InputStream instance
1152 protected final function getInputStreamInstance () {
1153 return $this->inputStreamInstance;
1157 * Setter for a InputStream instance
1159 * @param $inputStreamInstance The InputStream instance
1162 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1163 $this->inputStreamInstance = $inputStreamInstance;
1167 * Getter for a OutputStream instance
1169 * @param $outputStreamInstance The OutputStream instance
1171 protected final function getOutputStreamInstance () {
1172 return $this->outputStreamInstance;
1176 * Setter for a OutputStream instance
1178 * @param $outputStreamInstance The OutputStream instance
1181 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1182 $this->outputStreamInstance = $outputStreamInstance;
1186 * Setter for handler instance
1188 * @param $handlerInstance An instance of a Handleable class
1191 protected final function setHandlerInstance (Handleable $handlerInstance) {
1192 $this->handlerInstance = $handlerInstance;
1196 * Getter for handler instance
1198 * @return $handlerInstance A Networkable instance
1200 protected final function getHandlerInstance () {
1201 return $this->handlerInstance;
1205 * Setter for visitor instance
1207 * @param $visitorInstance A Visitor instance
1210 protected final function setVisitorInstance (Visitor $visitorInstance) {
1211 $this->visitorInstance = $visitorInstance;
1215 * Getter for visitor instance
1217 * @return $visitorInstance A Visitor instance
1219 protected final function getVisitorInstance () {
1220 return $this->visitorInstance;
1224 * Setter for DHT instance
1226 * @param $dhtInstance A Distributable instance
1229 protected final function setDhtInstance (Distributable $dhtInstance) {
1230 $this->dhtInstance = $dhtInstance;
1234 * Getter for DHT instance
1236 * @return $dhtInstance A Distributable instance
1238 protected final function getDhtInstance () {
1239 return $this->dhtInstance;
1243 * Setter for raw package Data
1245 * @param $packageData Raw package Data
1248 public final function setPackageData (array $packageData) {
1249 $this->packageData = $packageData;
1253 * Getter for raw package Data
1255 * @return $packageData Raw package Data
1257 public function getPackageData () {
1258 return $this->packageData;
1263 * Setter for Iterator instance
1265 * @param $iteratorInstance An instance of an Iterator
1268 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1269 $this->iteratorInstance = $iteratorInstance;
1273 * Getter for Iterator instance
1275 * @return $iteratorInstance An instance of an Iterator
1277 public final function getIteratorInstance () {
1278 return $this->iteratorInstance;
1282 * Setter for InputOutputPointer instance
1284 * @param $pointerInstance An instance of an InputOutputPointer class
1287 protected final function setPointerInstance (InputOutputPointer $pointerInstance) {
1288 $this->pointerInstance = $pointerInstance;
1292 * Getter for InputOutputPointer instance
1294 * @return $pointerInstance An instance of an InputOutputPointer class
1296 public final function getPointerInstance () {
1297 return $this->pointerInstance;
1301 * Setter for Indexable instance
1303 * @param $indexInstance An instance of an Indexable class
1306 protected final function setIndexInstance (Indexable $indexInstance) {
1307 $this->indexInstance = $indexInstance;
1311 * Getter for Indexable instance
1313 * @return $indexInstance An instance of an Indexable class
1315 public final function getIndexInstance () {
1316 return $this->indexInstance;
1320 * Setter for CalculatableBlock instance
1322 * @param $blockInstance An instance of an CalculatableBlock class
1325 protected final function setBlockInstance (CalculatableBlock $blockInstance) {
1326 $this->blockInstance = $blockInstance;
1330 * Getter for CalculatableBlock instance
1332 * @return $blockInstance An instance of an CalculatableBlock class
1334 public final function getBlockInstance () {
1335 return $this->blockInstance;
1339 * Checks whether an object equals this object. You should overwrite this
1340 * method to implement own equality checks
1342 * @param $objectInstance An instance of a FrameworkInterface object
1343 * @return $equals Whether both objects equals
1345 public function equals (FrameworkInterface $objectInstance) {
1348 $this->__toString() == $objectInstance->__toString()
1350 $this->hashCode() == $objectInstance->hashCode()
1353 // Return the result
1358 * Generates a generic hash code of this class. You should really overwrite
1359 * this method with your own hash code generator code. But keep KISS in mind.
1361 * @return $hashCode A generic hash code respresenting this whole class
1363 public function hashCode () {
1365 return crc32($this->__toString());
1369 * Formats computer generated price values into human-understandable formats
1370 * with thousand and decimal separators.
1372 * @param $value The in computer format value for a price
1373 * @param $currency The currency symbol (use HTML-valid characters!)
1374 * @param $decNum Number of decimals after commata
1375 * @return $price The for the current language formated price string
1376 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1377 * thousands separator
1380 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1381 // Are all required attriutes set?
1382 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1383 // Throw an exception
1384 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1388 $value = (float) $value;
1390 // Reformat the US number
1391 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1393 // Return as string...
1398 * Appends a trailing slash to a string
1400 * @param $str A string (maybe) without trailing slash
1401 * @return $str A string with an auto-appended trailing slash
1403 public final function addMissingTrailingSlash ($str) {
1404 // Is there a trailing slash?
1405 if (substr($str, -1, 1) != '/') {
1409 // Return string with trailing slash
1414 * Prepare the template engine (WebTemplateEngine by default) for a given
1415 * application helper instance (ApplicationHelper by default).
1417 * @param $applicationInstance An application helper instance or
1418 * null if we shall use the default
1419 * @return $templateInstance The template engine instance
1420 * @throws NullPointerException If the discovered application
1421 * instance is still null
1423 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1424 // Is the application instance set?
1425 if (is_null($applicationInstance)) {
1426 // Get the current instance
1427 $applicationInstance = $this->getApplicationInstance();
1430 if (is_null($applicationInstance)) {
1431 // Thrown an exception
1432 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1436 // Initialize the template engine
1437 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
1439 // Return the prepared instance
1440 return $templateInstance;
1444 * Debugs this instance by putting out it's full content
1446 * @param $message Optional message to show in debug output
1449 public final function debugInstance ($message = '') {
1450 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1451 restore_error_handler();
1456 // Is a message set?
1457 if (!empty($message)) {
1458 // Construct message
1459 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1462 // Generate the output
1463 $content .= sprintf('<pre>%s</pre>',
1466 print_r($this, TRUE)
1472 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>',
1473 $this->__toString(),
1475 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1480 * Replaces control characters with printable output
1482 * @param $str String with control characters
1483 * @return $str Replaced string
1485 protected function replaceControlCharacters ($str) {
1488 chr(13), '[r]', str_replace(
1489 chr(10), '[n]', str_replace(
1499 * Output a partial stub message for the caller method
1501 * @param $message An optional message to display
1504 protected function partialStub ($message = '') {
1505 // Get the backtrace
1506 $backtrace = debug_backtrace();
1508 // Generate the class::method string
1509 $methodName = 'UnknownClass->unknownMethod';
1510 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1511 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1514 // Construct the full message
1515 $stubMessage = sprintf('[%s:] Partial stub!',
1519 // Is the extra message given?
1520 if (!empty($message)) {
1521 // Then add it as well
1522 $stubMessage .= ' Message: ' . $message;
1525 // Debug instance is there?
1526 if (!is_null($this->getDebugInstance())) {
1527 // Output stub message
1528 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1531 trigger_error($stubMessage);
1537 * Outputs a debug backtrace and stops further script execution
1539 * @param $message An optional message to output
1540 * @param $doExit Whether exit the program (TRUE is default)
1543 public function debugBackTrace ($message = '', $doExit = TRUE) {
1544 // Sorry, there is no other way getting this nice backtrace
1545 if (!empty($message)) {
1547 printf('Message: %s<br />' . chr(10), $message);
1551 debug_print_backtrace();
1555 if ($doExit === TRUE) {
1561 * Creates an instance of a debugger instance
1563 * @param $className Name of the class (currently unsupported)
1564 * @return $debugInstance An instance of a debugger class
1566 public final static function createDebugInstance ($className) {
1567 // Is the instance set?
1568 if (!Registry::getRegistry()->instanceExists('debug')) {
1569 // Init debug instance
1570 $debugInstance = NULL;
1574 // Get a debugger instance
1575 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_class'));
1576 } catch (NullPointerException $e) {
1577 // Didn't work, no instance there
1578 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1581 // Empty string should be ignored and used for testing the middleware
1582 DebugMiddleware::getSelfInstance()->output('');
1584 // Set it in its own class. This will set it in the registry
1585 $debugInstance->setDebugInstance($debugInstance);
1587 // Get instance from registry
1588 $debugInstance = Registry::getRegistry()->getDebugInstance();
1592 return $debugInstance;
1596 * Simple output of a message with line-break
1598 * @param $message Message to output
1601 public function outputLine ($message) {
1603 print($message . PHP_EOL);
1607 * Outputs a debug message whether to debug instance (should be set!) or
1608 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1609 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1611 * @param $message Message we shall send out...
1612 * @param $doPrint Whether print or die here (default: print)
1613 * @paran $stripTags Whether to strip tags (default: FALSE)
1616 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1617 // Set debug instance to NULL
1618 $debugInstance = NULL;
1622 // Get debug instance
1623 $debugInstance = $this->getDebugInstance();
1624 } catch (NullPointerException $e) {
1625 // The debug instance is not set (yet)
1628 // Is the debug instance there?
1629 if (is_object($debugInstance)) {
1630 // Use debug output handler
1631 $debugInstance->output($message, $stripTags);
1633 if ($doPrint === FALSE) {
1634 // Die here if not printed
1638 // Are debug times enabled?
1639 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1641 $message = $this->getPrintableExecutionTime() . $message;
1645 if ($doPrint === TRUE) {
1647 $this->outputLine($message);
1656 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1658 * @param $str The string, what ever it is needs to be converted
1659 * @return $className Generated class name
1661 public function convertToClassName ($str) {
1665 // Convert all dashes in underscores
1666 $str = $this->convertDashesToUnderscores($str);
1668 // Now use that underscores to get classname parts for hungarian style
1669 foreach (explode('_', $str) as $strPart) {
1670 // Make the class name part lower case and first upper case
1671 $className .= ucfirst(strtolower($strPart));
1674 // Return class name
1679 * Converts dashes to underscores, e.g. useable for configuration entries
1681 * @param $str The string with maybe dashes inside
1682 * @return $str The converted string with no dashed, but underscores
1684 public final function convertDashesToUnderscores ($str) {
1686 $str = str_replace('-', '_', $str);
1688 // Return converted string
1693 * Marks up the code by adding e.g. line numbers
1695 * @param $phpCode Unmarked PHP code
1696 * @return $markedCode Marked PHP code
1698 public function markupCode ($phpCode) {
1703 $errorArray = error_get_last();
1705 // Init the code with error message
1706 if (is_array($errorArray)) {
1708 $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>',
1709 basename($errorArray['file']),
1710 $errorArray['line'],
1711 $errorArray['message'],
1716 // Add line number to the code
1717 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1719 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1721 htmlentities($code, ENT_QUOTES)
1730 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1731 * beatiful for web-based front-ends. If null is given a message id
1732 * null_timestamp will be resolved and returned.
1734 * @param $timestamp Timestamp to prepare (filter) for display
1735 * @return $readable A readable timestamp
1737 public function doFilterFormatTimestamp ($timestamp) {
1738 // Default value to return
1741 // Is the timestamp null?
1742 if (is_null($timestamp)) {
1743 // Get a message string
1744 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1746 switch ($this->getLanguageInstance()->getLanguageCode()) {
1747 case 'de': // German format is a bit different to default
1748 // Split the GMT stamp up
1749 $dateTime = explode(' ', $timestamp );
1750 $dateArray = explode('-', $dateTime[0]);
1751 $timeArray = explode(':', $dateTime[1]);
1753 // Construct the timestamp
1754 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1764 default: // Default is pass-through
1765 $readable = $timestamp;
1775 * Filter a given number into a localized number
1777 * @param $value The raw value from e.g. database
1778 * @return $localized Localized value
1780 public function doFilterFormatNumber ($value) {
1781 // Generate it from config and localize dependencies
1782 switch ($this->getLanguageInstance()->getLanguageCode()) {
1783 case 'de': // German format is a bit different to default
1784 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1787 default: // US, etc.
1788 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1797 * "Getter" for databse entry
1799 * @return $entry An array with database entries
1800 * @throws NullPointerException If the database result is not found
1801 * @throws InvalidDatabaseResultException If the database result is invalid
1803 protected final function getDatabaseEntry () {
1804 // Is there an instance?
1805 if (is_null($this->getResultInstance())) {
1806 // Throw an exception here
1807 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1811 $this->getResultInstance()->rewind();
1813 // Do we have an entry?
1814 if ($this->getResultInstance()->valid() === FALSE) {
1815 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1819 $this->getResultInstance()->next();
1822 $entry = $this->getResultInstance()->current();
1829 * Getter for field name
1831 * @param $fieldName Field name which we shall get
1832 * @return $fieldValue Field value from the user
1833 * @throws NullPointerException If the result instance is null
1835 public final function getField ($fieldName) {
1836 // Default field value
1839 // Get result instance
1840 $resultInstance = $this->getResultInstance();
1842 // Is this instance null?
1843 if (is_null($resultInstance)) {
1844 // Then the user instance is no longer valid (expired cookies?)
1845 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1848 // Get current array
1849 $fieldArray = $resultInstance->current();
1850 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
1852 // Convert dashes to underscore
1853 $fieldName = $this->convertDashesToUnderscores($fieldName);
1855 // Does the field exist?
1856 if (isset($fieldArray[$fieldName])) {
1858 $fieldValue = $fieldArray[$fieldName];
1860 // Missing field entry, may require debugging
1861 self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ':fieldname=' . $fieldName . ' not found!');
1869 * Flushs all pending updates to the database layer
1873 public function flushPendingUpdates () {
1874 // Get result instance
1875 $resultInstance = $this->getResultInstance();
1877 // Do we have data to update?
1878 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1879 // Get wrapper class name config entry
1880 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1882 // Create object instance
1883 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1885 // Yes, then send the whole result to the database layer
1886 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1891 * Outputs a deprecation warning to the developer.
1893 * @param $message The message we shall output to the developer
1895 * @todo Write a logging mechanism for productive mode
1897 public function deprecationWarning ($message) {
1898 // Is developer mode active?
1899 if (defined('DEVELOPER')) {
1900 // Debug instance is there?
1901 if (!is_null($this->getDebugInstance())) {
1902 // Output stub message
1903 self::createDebugInstance(__CLASS__)->debugOutput($message);
1906 trigger_error($message . "<br />\n");
1910 // @TODO Finish this part!
1911 $this->partialStub('Developer mode inactive. Message:' . $message);
1916 * Checks whether the given PHP extension is loaded
1918 * @param $phpExtension The PHP extension we shall check
1919 * @return $isLoaded Whether the PHP extension is loaded
1921 public final function isPhpExtensionLoaded ($phpExtension) {
1923 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1930 * "Getter" as a time() replacement but with milliseconds. You should use this
1931 * method instead of the encapsulated getimeofday() function.
1933 * @return $milliTime Timestamp with milliseconds
1935 public function getMilliTime () {
1936 // Get the time of day as float
1937 $milliTime = gettimeofday(TRUE);
1944 * Idles (sleeps) for given milliseconds
1946 * @return $hasSlept Whether it goes fine
1948 public function idle ($milliSeconds) {
1949 // Sleep is fine by default
1952 // Idle so long with found function
1953 if (function_exists('time_sleep_until')) {
1954 // Get current time and add idle time
1955 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1957 // New PHP 5.1.0 function found, ignore errors
1958 $hasSlept = @time_sleep_until($sleepUntil);
1961 * My Sun station doesn't have that function even with latest PHP
1964 usleep($milliSeconds * 1000);
1971 * Converts a hexadecimal string, even with negative sign as first string to
1972 * a decimal number using BC functions.
1974 * This work is based on comment #86673 on php.net documentation page at:
1975 * <http://de.php.net/manual/en/function.dechex.php#86673>
1977 * @param $hex Hexadecimal string
1978 * @return $dec Decimal number
1980 protected function hex2dec ($hex) {
1981 // Convert to all lower-case
1982 $hex = strtolower($hex);
1984 // Detect sign (negative/positive numbers)
1986 if (substr($hex, 0, 1) == '-') {
1988 $hex = substr($hex, 1);
1991 // Decode the hexadecimal string into a decimal number
1993 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1994 $factor = self::$hexdec[substr($hex, $i, 1)];
1995 $dec = bcadd($dec, bcmul($factor, $e));
1998 // Return the decimal number
1999 return $sign . $dec;
2003 * Converts even very large decimal numbers, also signed, to a hexadecimal
2006 * This work is based on comment #97756 on php.net documentation page at:
2007 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2009 * @param $dec Decimal number, even with negative sign
2010 * @param $maxLength Optional maximum length of the string
2011 * @return $hex Hexadecimal string
2013 protected function dec2hex ($dec, $maxLength = 0) {
2014 // maxLength can be zero or devideable by 2
2015 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2017 // Detect sign (negative/positive numbers)
2024 // Encode the decimal number into a hexadecimal string
2027 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2029 } while ($dec >= 1);
2032 * Leading zeros are required for hex-decimal "numbers". In some
2033 * situations more leading zeros are wanted, so check for both
2036 if ($maxLength > 0) {
2037 // Prepend more zeros
2038 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2039 } elseif ((strlen($hex) % 2) != 0) {
2040 // Only make string's length dividable by 2
2044 // Return the hexadecimal string
2045 return $sign . $hex;
2049 * Converts a ASCII string (0 to 255) into a decimal number.
2051 * @param $asc The ASCII string to be converted
2052 * @return $dec Decimal number
2054 protected function asc2dec ($asc) {
2055 // Convert it into a hexadecimal number
2056 $hex = bin2hex($asc);
2058 // And back into a decimal number
2059 $dec = $this->hex2dec($hex);
2066 * Converts a decimal number into an ASCII string.
2068 * @param $dec Decimal number
2069 * @return $asc An ASCII string
2071 protected function dec2asc ($dec) {
2072 // First convert the number into a hexadecimal string
2073 $hex = $this->dec2hex($dec);
2075 // Then convert it into the ASCII string
2076 $asc = $this->hex2asc($hex);
2083 * Converts a hexadecimal number into an ASCII string. Negative numbers
2086 * @param $hex Hexadecimal string
2087 * @return $asc An ASCII string
2089 protected function hex2asc ($hex) {
2090 // Check for length, it must be devideable by 2
2091 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2092 assert((strlen($hex) % 2) == 0);
2096 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2097 // Get the decimal number of the chunk
2098 $part = hexdec(substr($hex, $idx, 2));
2100 // Add it to the final string
2104 // Return the final string
2109 * Checks whether the given encoded data was encoded with Base64
2111 * @param $encodedData Encoded data we shall check
2112 * @return $isBase64 Whether the encoded data is Base64
2114 protected function isBase64Encoded ($encodedData) {
2116 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2123 * "Getter" to get response/request type from analysis of the system.
2125 * @return $responseType Analyzed response type
2127 protected function getResponseTypeFromSystem () {
2128 // Default is console
2129 $responseType = 'console';
2131 // Is 'HTTP_HOST' set?
2132 if (isset($_SERVER['HTTP_HOST'])) {
2133 // Then it is a HTTP response/request
2134 $responseType = 'http';
2138 return $responseType;
2142 * Gets a cache key from Criteria instance
2144 * @param $criteriaInstance An instance of a Criteria class
2145 * @param $onlyKeys Only use these keys for a cache key
2146 * @return $cacheKey A cache key suitable for lookup/storage purposes
2148 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2150 $cacheKey = sprintf('%s@%s',
2151 $this->__toString(),
2152 $criteriaInstance->getCacheKey($onlyKeys)
2156 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2161 * Getter for startup time in miliseconds
2163 * @return $startupTime Startup time in miliseconds
2165 protected function getStartupTime () {
2166 return self::$startupTime;
2170 * "Getter" for a printable currently execution time in nice braces
2172 * @return $executionTime Current execution time in nice braces
2174 protected function getPrintableExecutionTime () {
2175 // Caculate the execution time
2176 $executionTime = microtime(TRUE) - $this->getStartupTime();
2178 // Pack it in nice braces
2179 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2182 return $executionTime;
2186 * Hashes a given string with a simple but stronger hash function (no salt)
2187 * and hex-encode it.
2189 * @param $str The string to be hashed
2190 * @return $hash The hash from string $str
2192 public static final function hash ($str) {
2193 // Hash given string with (better secure) hasher
2194 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2201 * "Getter" for length of hash() output. This will be "cached" to speed up
2204 * @return $length Length of hash() output
2206 public static final function getHashLength () {
2208 if (is_null(self::$hashLength)) {
2209 // No, then hash a string and save its length.
2210 self::$hashLength = strlen(self::hash('abc123'));
2214 return self::$hashLength;
2218 * Checks whether the given number is really a number (only chars 0-9).
2220 * @param $num A string consisting only chars between 0 and 9
2221 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2222 * @param $assertMismatch Whether to assert mismatches
2223 * @return $ret The (hopefully) secured numbered value
2225 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2226 // Filter all numbers out
2227 $ret = preg_replace('/[^0123456789]/', '', $num);
2230 if ($castValue === TRUE) {
2231 // Cast to biggest numeric type
2232 $ret = (double) $ret;
2235 // Assert only if requested
2236 if ($assertMismatch === TRUE) {
2237 // Has the whole value changed?
2238 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2246 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2248 * @param $num A string consisting only chars between 0 and 9
2249 * @param $assertMismatch Whether to assert mismatches
2250 * @return $ret The (hopefully) secured hext-numbered value
2252 public function hexval ($num, $assertMismatch = FALSE) {
2253 // Filter all numbers out
2254 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2256 // Assert only if requested
2257 if ($assertMismatch === TRUE) {
2258 // Has the whole value changed?
2259 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2267 * Checks whether start/end marker are set
2269 * @param $data Data to be checked
2270 * @return $isset Whether start/end marker are set
2272 public final function ifStartEndMarkersSet ($data) {
2274 $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));
2276 // ... and return it
2281 * Determines if an element is set in the generic array
2283 * @param $keyGroup Main group for the key
2284 * @param $subGroup Sub group for the key
2285 * @param $key Key to check
2286 * @param $element Element to check
2287 * @return $isset Whether the given key is set
2289 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2291 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2294 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2300 * Determines if a key is set in the generic array
2302 * @param $keyGroup Main group for the key
2303 * @param $subGroup Sub group for the key
2304 * @param $key Key to check
2305 * @return $isset Whether the given key is set
2307 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2309 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2312 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2320 * Determines if a group is set in the generic array
2322 * @param $keyGroup Main group
2323 * @param $subGroup Sub group
2324 * @return $isset Whether the given group is set
2326 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2328 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2331 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2338 * Getter for sub key group
2340 * @param $keyGroup Main key group
2341 * @param $subGroup Sub key group
2342 * @return $array An array with all array elements
2344 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2346 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2347 // No, then abort here
2348 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2353 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2356 return $this->genericArray[$keyGroup][$subGroup];
2360 * Unsets a given key in generic array
2362 * @param $keyGroup Main group for the key
2363 * @param $subGroup Sub group for the key
2364 * @param $key Key to unset
2367 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2369 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2372 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2376 * Unsets a given element in generic array
2378 * @param $keyGroup Main group for the key
2379 * @param $subGroup Sub group for the key
2380 * @param $key Key to unset
2381 * @param $element Element to unset
2384 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2386 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2389 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2393 * Append a string to a given generic array key
2395 * @param $keyGroup Main group for the key
2396 * @param $subGroup Sub group for the key
2397 * @param $key Key to unset
2398 * @param $value Value to add/append
2401 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2403 //* 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);
2405 // Is it already there?
2406 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2408 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2411 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2416 * Append a string to a given generic array element
2418 * @param $keyGroup Main group for the key
2419 * @param $subGroup Sub group for the key
2420 * @param $key Key to unset
2421 * @param $element Element to check
2422 * @param $value Value to add/append
2425 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2427 //* 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);
2429 // Is it already there?
2430 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2432 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2435 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2440 * Initializes given generic array group
2442 * @param $keyGroup Main group for the key
2443 * @param $subGroup Sub group for the key
2444 * @param $key Key to use
2445 * @param $forceInit Optionally force initialization
2448 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2450 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2452 // Is it already set?
2453 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2454 // Already initialized
2455 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2460 $this->genericArray[$keyGroup][$subGroup] = array();
2464 * Initializes given generic array key
2466 * @param $keyGroup Main group for the key
2467 * @param $subGroup Sub group for the key
2468 * @param $key Key to use
2469 * @param $forceInit Optionally force initialization
2472 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2474 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2476 // Is it already set?
2477 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2478 // Already initialized
2479 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2484 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2488 * Initializes given generic array element
2490 * @param $keyGroup Main group for the key
2491 * @param $subGroup Sub group for the key
2492 * @param $key Key to use
2493 * @param $element Element to use
2494 * @param $forceInit Optionally force initialization
2497 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2499 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2501 // Is it already set?
2502 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2503 // Already initialized
2504 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2509 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2513 * Pushes an element to a generic key
2515 * @param $keyGroup Main group for the key
2516 * @param $subGroup Sub group for the key
2517 * @param $key Key to use
2518 * @param $value Value to add/append
2519 * @return $count Number of array elements
2521 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2523 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2526 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2528 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2532 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2535 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2536 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2541 * Pushes an element to a generic array element
2543 * @param $keyGroup Main group for the key
2544 * @param $subGroup Sub group for the key
2545 * @param $key Key to use
2546 * @param $element Element to check
2547 * @param $value Value to add/append
2548 * @return $count Number of array elements
2550 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2552 //* 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));
2555 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2557 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2561 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2564 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2565 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2570 * Pops an element from a generic group
2572 * @param $keyGroup Main group for the key
2573 * @param $subGroup Sub group for the key
2574 * @param $key Key to unset
2575 * @return $value Last "popped" value
2577 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2579 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2582 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2584 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2589 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2592 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2593 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2598 * Shifts an element from a generic group
2600 * @param $keyGroup Main group for the key
2601 * @param $subGroup Sub group for the key
2602 * @param $key Key to unset
2603 * @return $value Last "popped" value
2605 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2607 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2610 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2612 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2617 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2620 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2621 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2626 * Count generic array group
2628 * @param $keyGroup Main group for the key
2629 * @return $count Count of given group
2631 protected final function countGenericArray ($keyGroup) {
2633 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2636 if (!isset($this->genericArray[$keyGroup])) {
2638 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2643 $count = count($this->genericArray[$keyGroup]);
2646 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2653 * Count generic array sub group
2655 * @param $keyGroup Main group for the key
2656 * @param $subGroup Sub group for the key
2657 * @return $count Count of given group
2659 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2661 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2664 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2666 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2671 $count = count($this->genericArray[$keyGroup][$subGroup]);
2674 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2681 * Count generic array elements
2683 * @param $keyGroup Main group for the key
2684 * @param $subGroup Sub group for the key
2685 * @para $key Key to count
2686 * @return $count Count of given key
2688 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2690 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2693 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2695 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2697 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2699 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2704 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2707 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2714 * Getter for whole generic group array
2716 * @param $keyGroup Key group to get
2717 * @return $array Whole generic array group
2719 protected final function getGenericArray ($keyGroup) {
2721 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2724 if (!isset($this->genericArray[$keyGroup])) {
2726 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2731 return $this->genericArray[$keyGroup];
2735 * Setter for generic array key
2737 * @param $keyGroup Key group to get
2738 * @param $subGroup Sub group for the key
2739 * @param $key Key to unset
2740 * @param $value Mixed value from generic array element
2743 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2745 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2748 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2752 * Getter for generic array key
2754 * @param $keyGroup Key group to get
2755 * @param $subGroup Sub group for the key
2756 * @param $key Key to unset
2757 * @return $value Mixed value from generic array element
2759 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2761 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2764 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2766 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2771 return $this->genericArray[$keyGroup][$subGroup][$key];
2775 * Sets a value in given generic array key/element
2777 * @param $keyGroup Main group for the key
2778 * @param $subGroup Sub group for the key
2779 * @param $key Key to set
2780 * @param $element Element to set
2781 * @param $value Value to set
2784 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2786 //* 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));
2789 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2793 * Getter for generic array element
2795 * @param $keyGroup Key group to get
2796 * @param $subGroup Sub group for the key
2797 * @param $key Key to look for
2798 * @param $element Element to look for
2799 * @return $value Mixed value from generic array element
2801 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2803 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2806 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2808 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2813 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2817 * Checks if a given sub group is valid (array)
2819 * @param $keyGroup Key group to get
2820 * @param $subGroup Sub group for the key
2821 * @return $isValid Whether given sub group is valid
2823 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2825 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2828 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
2835 * Checks if a given key is valid (array)
2837 * @param $keyGroup Key group to get
2838 * @param $subGroup Sub group for the key
2839 * @param $key Key to check
2840 * @return $isValid Whether given sub group is valid
2842 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
2844 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2847 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
2854 * Translates boolean TRUE to 'Y' and FALSE to 'N'
2856 * @param $boolean Boolean value
2857 * @return $translated Translated boolean value
2859 public static final function translateBooleanToYesNo ($boolean) {
2860 // Make sure it is really boolean
2861 assert(is_bool($boolean));
2864 $translated = ($boolean === TRUE) ? 'Y' : 'N';
2866 // ... and return it
2871 * Initializes counter for valid entries, arrays for damaged entries and
2872 * an array for gap seek positions. If you call this method on your own,
2873 * please re-analyze the file structure. So you are better to call
2874 * analyzeFile() instead of this method.
2878 protected function initCountersGapsArray () {
2879 // Init counter and seek position
2880 $this->setCounter(0);
2881 $this->setSeekPosition(0);
2884 $this->gaps = array();
2885 $this->damagedEntries = array();
2889 * Getter for total entries
2891 * @return $totalEntries Total entries in this file
2893 protected final function getCounter () {
2895 return $this->totalEntries;
2899 * Setter for total entries
2901 * @param $totalEntries Total entries in this file
2904 protected final function setCounter ($counter) {
2906 $this->totalEntries = $counter;
2914 protected final function incrementCounter () {
2916 $this->totalEntries++;
2920 * Getter for header size
2922 * @return $totalEntries Size of file header
2924 protected final function getHeaderSize () {
2926 return $this->headerSize;
2930 * Setter for header size
2932 * @param $headerSize Size of file header
2935 protected final function setHeaderSize ($headerSize) {
2937 $this->headerSize = $headerSize;
2941 * Getter for header array
2943 * @return $totalEntries Size of file header
2945 protected final function getHeade () {
2947 return $this->header;
2953 * @param $header Array for a file header
2956 protected final function setHeader (array $header) {
2958 $this->header = $header;
2962 * Getter for seek position
2964 * @return $seekPosition Current seek position (stored here in object)
2966 protected final function getSeekPosition () {
2968 return $this->seekPosition;
2972 * Setter for seek position
2974 * @param $seekPosition Current seek position (stored here in object)
2977 protected final function setSeekPosition ($seekPosition) {
2979 $this->seekPosition = $seekPosition;
2983 * Updates seekPosition attribute from file to avoid to much access on file.
2987 protected function updateSeekPosition () {
2988 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
2990 // Get key (= seek position)
2991 $seekPosition = $this->getIteratorInstance()->key();
2992 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Setting seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
2995 $this->setSeekPosition($seekPosition);
2997 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
3001 * Checks whether the file header is initialized
3003 * @return $isInitialized Whether the file header is initialized
3005 protected function isFileHeaderInitialized () {
3006 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3008 // Is the method there?
3009 assert(is_callable(array($this, 'readFileHeader')));
3011 // Default is not initialized
3012 $isInitialized = FALSE;
3014 // Is the file initialized?
3015 if ($this->isFileInitialized()) {
3016 // Some bytes has been written, so rewind to start of it.
3017 $rewindStatus = $this->getIteratorInstance()->rewind();
3018 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] rewindStatus=%s', __METHOD__, __LINE__, $rewindStatus));
3020 // Is the rewind() call successfull?
3021 if ($rewindStatus != 1) {
3022 // Something bad happened
3023 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Could not rewind().', __METHOD__, __LINE__));
3027 $this->readFileHeader();
3029 // The above method does already check the header
3030 $isInitialized = TRUE;
3034 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
3035 return $isInitialized;
3039 * Checks whether the assigned file has been initialized
3041 * @return $isInitialized Whether the file's size is zero
3043 protected function isFileInitialized () {
3044 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3046 // Get it from iterator which holds the pointer instance. If FALSE is returned
3047 $fileSize = $this->getIteratorInstance()->size();
3048 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] fileSize=%s', __METHOD__, __LINE__, $fileSize));
3051 * The returned file size should not be FALSE or NULL as this means
3052 * that the pointer class does not work correctly.
3054 assert(is_int($fileSize));
3056 // Is more than 0 returned?
3057 $isInitialized = ($fileSize > 0);
3060 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
3061 return $isInitialized;
3065 * Creates the assigned file
3069 protected function createFileHeader () {
3070 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3072 // The method flushFileHeader() must be callable
3073 assert(is_callable(array($this, 'flushFileHeader')));
3075 // The file's header should not be initialized here
3076 assert(!$this->isFileHeaderInitialized());
3078 // Simple flush file header which will create it.
3079 $this->flushFileHeader();
3081 // Rewind seek position (to beginning of file) and update/flush file header
3082 $this->rewineUpdateSeekPosition();
3084 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!!', __METHOD__, __LINE__));
3088 * Seeks to beginning of file, updates seek position in this object and
3089 * flushes the header.
3093 protected function rewineUpdateSeekPosition () {
3094 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3096 // Seek to beginning of file
3097 $this->getIteratorInstance()->rewind();
3099 // And update seek position ...
3100 $this->updateSeekPosition();
3102 // ... to write it back into the file
3103 $this->flushFileHeader();
3105 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!!', __METHOD__, __LINE__));
3109 * Seeks to old position
3113 protected function seekToOldPosition () {
3114 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3116 // Seek to currently ("old") saved position
3117 $this->getIteratorInstance()->seek($this->getSeekPosition());
3119 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!!', __METHOD__, __LINE__));
3123 * Writes data at given position
3125 * @param $seekPosition Seek position
3126 * @param $data Data to be written
3127 * @param $flushHeader Whether to flush the header (default: flush)
3130 protected function writeData ($seekPosition, $data, $flushHeader = TRUE) {
3131 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data()=%s - CALLED!', __METHOD__, __LINE__, $seekPosition, strlen($data)));
3133 // Write data at given position
3134 $this->getIteratorInstance()->writeAtPosition($seekPosition, $data);
3136 // Update seek position
3137 $this->updateSeekPosition();
3139 // Flush the header?
3140 if ($flushHeader === TRUE) {
3142 $this->flushFileHeader();
3144 // Seek to old position
3145 $this->seekToOldPosition();
3148 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
3152 * Pre-allocates file (if enabled) with some space for later faster write access.
3154 * @param $type Type of the file
3157 protected function preAllocateFile ($type) {
3158 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
3160 // caluclateMinimumBlockLength() must be callable
3161 assert(is_callable(array($this, 'caluclateMinimumBlockLength')));
3164 if ($this->getConfigInstance()->getConfigEntry($type . '_pre_allocate_enabled') != 'Y') {
3166 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Not pre-allocating file.', __METHOD__, __LINE__));
3168 // Don't continue here.
3173 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Pre-allocating file ...', __METHOD__, __LINE__));
3175 // Calculate minimum length for one entry
3176 $minLengthEntry = $this->caluclateMinimumBlockLength();
3177 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] minLengthEntry=%s', __METHOD__, __LINE__, $minLengthEntry));
3179 // Calulcate seek position
3180 $seekPosition = $minLengthEntry * $this->getConfigInstance()->getConfigEntry($type . '_pre_allocate_count');
3181 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
3183 // Now simply write a NUL there. This will pre-allocate the file.
3184 $this->writeData($seekPosition, chr(0));
3186 // Rewind seek position (to beginning of file) and update/flush file header
3187 $this->rewineUpdateSeekPosition();
3189 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));