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 index
194 private $indexInstance = NULL;
197 * Thousands separator
199 private $thousands = '.'; // German
204 private $decimals = ','; // German
209 private $socketResource = FALSE;
214 private $packageData = array();
219 private $genericArray = array();
222 * Length of output from hash()
224 private static $hashLength = NULL;
227 * Counter for total entries
229 private $totalEntries = 0;
232 * Current seek position
234 private $seekPosition = 0;
239 private $headerSize = 0;
244 private $header = array();
247 * Seek positions for gaps ("fragmentation")
249 private $gaps = array();
252 * Seek positions for damaged entries (e.g. mismatching hash sum, ...)
254 private $damagedEntries = array();
256 /***********************
257 * Exception codes.... *
258 ***********************/
260 // @todo Try to clean these constants up
261 const EXCEPTION_IS_NULL_POINTER = 0x001;
262 const EXCEPTION_IS_NO_OBJECT = 0x002;
263 const EXCEPTION_IS_NO_ARRAY = 0x003;
264 const EXCEPTION_MISSING_METHOD = 0x004;
265 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
266 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
267 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
268 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
269 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
270 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
271 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
272 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
273 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
274 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
275 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
276 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
277 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
278 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
279 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
280 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
281 const EXCEPTION_PATH_NOT_FOUND = 0x015;
282 const EXCEPTION_INVALID_PATH_NAME = 0x016;
283 const EXCEPTION_READ_PROTECED_PATH = 0x017;
284 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
285 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
286 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
287 const EXCEPTION_INVALID_RESOURCE = 0x01b;
288 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
289 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
290 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
291 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
292 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
293 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
294 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
295 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
296 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
297 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
298 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
299 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
300 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
301 const EXCEPTION_INVALID_STRING = 0x029;
302 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
303 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
304 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
305 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
306 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
307 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
308 const EXCEPTION_MISSING_ELEMENT = 0x030;
309 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
310 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
311 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
312 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
313 const EXCEPTION_FATAL_ERROR = 0x035;
314 const EXCEPTION_FILE_NOT_FOUND = 0x036;
315 const EXCEPTION_ASSERTION_FAILED = 0x037;
316 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
317 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
318 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03a;
321 * Hexadecimal->Decimal translation array
323 private static $hexdec = array(
343 * Decimal->hexadecimal translation array
345 private static $dechex = array(
365 * Startup time in miliseconds
367 private static $startupTime = 0;
370 * Protected super constructor
372 * @param $className Name of the class
375 protected function __construct ($className) {
377 $this->setRealClass($className);
379 // Set configuration instance if no registry ...
380 if (!$this instanceof Register) {
381 // ... because registries doesn't need to be configured
382 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
385 // Is the startup time set? (0 cannot be TRUE anymore)
386 if (self::$startupTime == 0) {
388 self::$startupTime = microtime(TRUE);
393 * Destructor for all classes
397 public function __destruct () {
398 // Flush any updated entries to the database
399 $this->flushPendingUpdates();
401 // Is this object already destroyed?
402 if ($this->__toString() != 'DestructedObject') {
403 // Destroy all informations about this class but keep some text about it alive
404 $this->setRealClass('DestructedObject');
405 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
406 // Already destructed object
407 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
412 // Do not call this twice
413 trigger_error(__METHOD__ . ': Called twice.');
419 * The __call() method where all non-implemented methods end up
421 * @param $methodName Name of the missing method
422 * @args $args Arguments passed to the method
425 public final function __call ($methodName, $args) {
426 return self::__callStatic($methodName, $args);
430 * The __callStatic() method where all non-implemented static methods end up
432 * @param $methodName Name of the missing method
433 * @args $args Arguments passed to the method
436 public static final function __callStatic ($methodName, $args) {
437 // Init argument string
440 // Is it empty or an array?
443 $argsString = 'NULL';
444 } elseif (is_array($args)) {
445 // Some arguments are there
446 foreach ($args as $arg) {
447 // Add the value itself if not array. This prevents 'array to string conversion' message
448 if (is_array($arg)) {
449 $argsString .= 'Array';
454 // Add data about the argument
455 $argsString .= ' (' . gettype($arg);
457 if (is_string($arg)) {
458 // Add length for strings
459 $argsString .= ', ' . strlen($arg);
460 } elseif (is_array($arg)) {
461 // .. or size if array
462 $argsString .= ', ' . count($arg);
463 } elseif ($arg === TRUE) {
464 // ... is boolean 'TRUE'
465 $argsString .= ', TRUE';
466 } elseif ($arg === FALSE) {
467 // ... is boolean 'FALSE'
468 $argsString .= ', FALSE';
472 $argsString .= '), ';
476 if (substr($argsString, -2, 1) == ',') {
477 $argsString = substr($argsString, 0, -2);
480 // Invalid arguments!
481 $argsString = '!INVALID:' . gettype($args) . '!';
484 // Output stub message
485 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
486 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
496 * Getter for $realClass
498 * @return $realClass The name of the real class (not BaseFrameworkSystem)
500 public function __toString () {
501 return $this->realClass;
505 * Magic function to catch setting of missing but set class fields/attributes
507 * @param $name Name of the field/attribute
508 * @param $value Value to store
511 public final function __set ($name, $value) {
512 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
520 * Magic function to catch getting of missing fields/attributes
522 * @param $name Name of the field/attribute
525 public final function __get ($name) {
526 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
532 * Magic function to catch unsetting of missing fields/attributes
534 * @param $name Name of the field/attribute
537 public final function __unset ($name) {
538 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
544 * Setter for the real class name
546 * @param $realClass Class name (string)
549 public final function setRealClass ($realClass) {
551 $this->realClass = (string) $realClass;
555 * Setter for database result instance
557 * @param $resultInstance An instance of a database result class
559 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
561 protected final function setResultInstance (SearchableResult $resultInstance) {
562 $this->resultInstance = $resultInstance;
566 * Getter for database result instance
568 * @return $resultInstance An instance of a database result class
570 public final function getResultInstance () {
571 return $this->resultInstance;
575 * Setter for template engine instances
577 * @param $templateInstance An instance of a template engine class
580 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
581 $this->templateInstance = $templateInstance;
585 * Getter for template engine instances
587 * @return $templateInstance An instance of a template engine class
589 protected final function getTemplateInstance () {
590 return $this->templateInstance;
594 * Setter for search instance
596 * @param $searchInstance Searchable criteria instance
599 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
600 $this->searchInstance = $searchInstance;
604 * Getter for search instance
606 * @return $searchInstance Searchable criteria instance
608 public final function getSearchInstance () {
609 return $this->searchInstance;
613 * Setter for update instance
615 * @param $updateInstance Searchable criteria instance
618 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
619 $this->updateInstance = $updateInstance;
623 * Getter for update instance
625 * @return $updateInstance Updateable criteria instance
627 public final function getUpdateInstance () {
628 return $this->updateInstance;
632 * Setter for resolver instance
634 * @param $resolverInstance Instance of a command resolver class
637 public final function setResolverInstance (Resolver $resolverInstance) {
638 $this->resolverInstance = $resolverInstance;
642 * Getter for resolver instance
644 * @return $resolverInstance Instance of a command resolver class
646 public final function getResolverInstance () {
647 return $this->resolverInstance;
651 * Setter for language instance
653 * @param $configInstance The configuration instance which shall
654 * be FrameworkConfiguration
657 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
658 Registry::getRegistry()->addInstance('config', $configInstance);
662 * Getter for configuration instance
664 * @return $configInstance Configuration instance
666 public final function getConfigInstance () {
667 $configInstance = Registry::getRegistry()->getInstance('config');
668 return $configInstance;
672 * Setter for debug instance
674 * @param $debugInstance The instance for debug output class
677 public final function setDebugInstance (DebugMiddleware $debugInstance) {
678 Registry::getRegistry()->addInstance('debug', $debugInstance);
682 * Getter for debug instance
684 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
686 public final function getDebugInstance () {
687 // Get debug instance
688 $debugInstance = Registry::getRegistry()->getInstance('debug');
691 return $debugInstance;
695 * Setter for web output instance
697 * @param $webInstance The instance for web output class
700 public final function setWebOutputInstance (OutputStreamer $webInstance) {
701 Registry::getRegistry()->addInstance('web_output', $webInstance);
705 * Getter for web output instance
707 * @return $webOutputInstance - Instance to class WebOutput
709 public final function getWebOutputInstance () {
710 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
711 return $webOutputInstance;
715 * Setter for database instance
717 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
720 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
721 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
725 * Getter for database layer
727 * @return $databaseInstance The database layer instance
729 public final function getDatabaseInstance () {
731 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
734 return $databaseInstance;
738 * Setter for compressor channel
740 * @param $compressorInstance An instance of CompressorChannel
743 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
744 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
748 * Getter for compressor channel
750 * @return $compressorInstance The compressor channel
752 public final function getCompressorChannel () {
753 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
754 return $compressorInstance;
758 * Protected getter for a manageable application helper class
760 * @return $applicationInstance An instance of a manageable application helper class
762 protected final function getApplicationInstance () {
763 $applicationInstance = Registry::getRegistry()->getInstance('application');
764 return $applicationInstance;
768 * Setter for a manageable application helper class
770 * @param $applicationInstance An instance of a manageable application helper class
773 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
774 Registry::getRegistry()->addInstance('application', $applicationInstance);
778 * Setter for request instance
780 * @param $requestInstance An instance of a Requestable class
783 public final function setRequestInstance (Requestable $requestInstance) {
784 $this->requestInstance = $requestInstance;
788 * Getter for request instance
790 * @return $requestInstance An instance of a Requestable class
792 public final function getRequestInstance () {
793 return $this->requestInstance;
797 * Setter for response instance
799 * @param $responseInstance An instance of a Responseable class
802 public final function setResponseInstance (Responseable $responseInstance) {
803 $this->responseInstance = $responseInstance;
807 * Getter for response instance
809 * @return $responseInstance An instance of a Responseable class
811 public final function getResponseInstance () {
812 return $this->responseInstance;
816 * Private getter for language instance
818 * @return $langInstance An instance to the language sub-system
820 protected final function getLanguageInstance () {
821 $langInstance = Registry::getRegistry()->getInstance('language');
822 return $langInstance;
826 * Setter for language instance
828 * @param $langInstance An instance to the language sub-system
830 * @see LanguageSystem
832 public final function setLanguageInstance (ManageableLanguage $langInstance) {
833 Registry::getRegistry()->addInstance('language', $langInstance);
837 * Private getter for file IO instance
839 * @return $fileIoInstance An instance to the file I/O sub-system
841 protected final function getFileIoInstance () {
842 return $this->fileIoInstance;
846 * Setter for file I/O instance
848 * @param $fileIoInstance An instance to the file I/O sub-system
851 public final function setFileIoInstance (IoHandler $fileIoInstance) {
852 $this->fileIoInstance = $fileIoInstance;
856 * Protected setter for user instance
858 * @param $userInstance An instance of a user class
861 protected final function setUserInstance (ManageableAccount $userInstance) {
862 $this->userInstance = $userInstance;
866 * Getter for user instance
868 * @return $userInstance An instance of a user class
870 public final function getUserInstance () {
871 return $this->userInstance;
875 * Setter for controller instance (this surely breaks a bit the MVC patterm)
877 * @param $controllerInstance An instance of the controller
880 public final function setControllerInstance (Controller $controllerInstance) {
881 $this->controllerInstance = $controllerInstance;
885 * Getter for controller instance (this surely breaks a bit the MVC patterm)
887 * @return $controllerInstance An instance of the controller
889 public final function getControllerInstance () {
890 return $this->controllerInstance;
894 * Setter for RNG instance
896 * @param $rngInstance An instance of a random number generator (RNG)
899 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
900 $this->rngInstance = $rngInstance;
904 * Getter for RNG instance
906 * @return $rngInstance An instance of a random number generator (RNG)
908 public final function getRngInstance () {
909 return $this->rngInstance;
913 * Setter for Cryptable instance
915 * @param $cryptoInstance An instance of a Cryptable class
918 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
919 $this->cryptoInstance = $cryptoInstance;
923 * Getter for Cryptable instance
925 * @return $cryptoInstance An instance of a Cryptable class
927 public final function getCryptoInstance () {
928 return $this->cryptoInstance;
932 * Setter for the list instance
934 * @param $listInstance A list of Listable
937 protected final function setListInstance (Listable $listInstance) {
938 $this->listInstance = $listInstance;
942 * Getter for the list instance
944 * @return $listInstance A list of Listable
946 protected final function getListInstance () {
947 return $this->listInstance;
951 * Setter for the menu instance
953 * @param $menuInstance A RenderableMenu instance
956 protected final function setMenuInstance (RenderableMenu $menuInstance) {
957 $this->menuInstance = $menuInstance;
961 * Getter for the menu instance
963 * @return $menuInstance A RenderableMenu instance
965 protected final function getMenuInstance () {
966 return $this->menuInstance;
970 * Setter for image instance
972 * @param $imageInstance An instance of an image
975 public final function setImageInstance (BaseImage $imageInstance) {
976 $this->imageInstance = $imageInstance;
980 * Getter for image instance
982 * @return $imageInstance An instance of an image
984 public final function getImageInstance () {
985 return $this->imageInstance;
989 * Setter for stacker instance
991 * @param $stackerInstance An instance of an stacker
994 public final function setStackerInstance (Stackable $stackerInstance) {
995 $this->stackerInstance = $stackerInstance;
999 * Getter for stacker instance
1001 * @return $stackerInstance An instance of an stacker
1003 public final function getStackerInstance () {
1004 return $this->stackerInstance;
1008 * Setter for compressor instance
1010 * @param $compressorInstance An instance of an compressor
1013 public final function setCompressorInstance (Compressor $compressorInstance) {
1014 $this->compressorInstance = $compressorInstance;
1018 * Getter for compressor instance
1020 * @return $compressorInstance An instance of an compressor
1022 public final function getCompressorInstance () {
1023 return $this->compressorInstance;
1027 * Setter for Parseable instance
1029 * @param $parserInstance An instance of an Parseable
1032 public final function setParserInstance (Parseable $parserInstance) {
1033 $this->parserInstance = $parserInstance;
1037 * Getter for Parseable instance
1039 * @return $parserInstance An instance of an Parseable
1041 public final function getParserInstance () {
1042 return $this->parserInstance;
1046 * Setter for ProtocolHandler instance
1048 * @param $protocolInstance An instance of an ProtocolHandler
1051 public final function setProtocolInstance (ProtocolHandler $protocolInstance = NULL) {
1052 $this->protocolInstance = $protocolInstance;
1056 * Getter for ProtocolHandler instance
1058 * @return $protocolInstance An instance of an ProtocolHandler
1060 public final function getProtocolInstance () {
1061 return $this->protocolInstance;
1065 * Setter for DatabaseWrapper instance
1067 * @param $wrapperInstance An instance of an DatabaseWrapper
1070 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1071 $this->wrapperInstance = $wrapperInstance;
1075 * Getter for DatabaseWrapper instance
1077 * @return $wrapperInstance An instance of an DatabaseWrapper
1079 public final function getWrapperInstance () {
1080 return $this->wrapperInstance;
1084 * Setter for socket resource
1086 * @param $socketResource A valid socket resource
1089 public final function setSocketResource ($socketResource) {
1090 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1091 $this->socketResource = $socketResource;
1095 * Getter for socket resource
1097 * @return $socketResource A valid socket resource
1099 public final function getSocketResource () {
1100 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1101 return $this->socketResource;
1105 * Setter for helper instance
1107 * @param $helperInstance An instance of a helper class
1110 protected final function setHelperInstance (Helper $helperInstance) {
1111 $this->helperInstance = $helperInstance;
1115 * Getter for helper instance
1117 * @return $helperInstance An instance of a helper class
1119 public final function getHelperInstance () {
1120 return $this->helperInstance;
1124 * Setter for a Sourceable instance
1126 * @param $sourceInstance The Sourceable instance
1129 protected final function setSourceInstance (Sourceable $sourceInstance) {
1130 $this->sourceInstance = $sourceInstance;
1134 * Getter for a Sourceable instance
1136 * @return $sourceInstance The Sourceable instance
1138 protected final function getSourceInstance () {
1139 return $this->sourceInstance;
1143 * Getter for a InputStream instance
1145 * @param $inputStreamInstance The InputStream instance
1147 protected final function getInputStreamInstance () {
1148 return $this->inputStreamInstance;
1152 * Setter for a InputStream instance
1154 * @param $inputStreamInstance The InputStream instance
1157 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1158 $this->inputStreamInstance = $inputStreamInstance;
1162 * Getter for a OutputStream instance
1164 * @param $outputStreamInstance The OutputStream instance
1166 protected final function getOutputStreamInstance () {
1167 return $this->outputStreamInstance;
1171 * Setter for a OutputStream instance
1173 * @param $outputStreamInstance The OutputStream instance
1176 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1177 $this->outputStreamInstance = $outputStreamInstance;
1181 * Setter for handler instance
1183 * @param $handlerInstance An instance of a Handleable class
1186 protected final function setHandlerInstance (Handleable $handlerInstance) {
1187 $this->handlerInstance = $handlerInstance;
1191 * Getter for handler instance
1193 * @return $handlerInstance A Networkable instance
1195 protected final function getHandlerInstance () {
1196 return $this->handlerInstance;
1200 * Setter for visitor instance
1202 * @param $visitorInstance A Visitor instance
1205 protected final function setVisitorInstance (Visitor $visitorInstance) {
1206 $this->visitorInstance = $visitorInstance;
1210 * Getter for visitor instance
1212 * @return $visitorInstance A Visitor instance
1214 protected final function getVisitorInstance () {
1215 return $this->visitorInstance;
1219 * Setter for DHT instance
1221 * @param $dhtInstance A Distributable instance
1224 protected final function setDhtInstance (Distributable $dhtInstance) {
1225 $this->dhtInstance = $dhtInstance;
1229 * Getter for DHT instance
1231 * @return $dhtInstance A Distributable instance
1233 protected final function getDhtInstance () {
1234 return $this->dhtInstance;
1238 * Setter for raw package Data
1240 * @param $packageData Raw package Data
1243 public final function setPackageData (array $packageData) {
1244 $this->packageData = $packageData;
1248 * Getter for raw package Data
1250 * @return $packageData Raw package Data
1252 public function getPackageData () {
1253 return $this->packageData;
1258 * Setter for Iterator instance
1260 * @param $iteratorInstance An instance of an Iterator
1263 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1264 $this->iteratorInstance = $iteratorInstance;
1268 * Getter for Iterator instance
1270 * @return $iteratorInstance An instance of an Iterator
1272 public final function getIteratorInstance () {
1273 return $this->iteratorInstance;
1277 * Setter for InputOutputPointer instance
1279 * @param $pointerInstance An instance of an InputOutputPointer class
1282 protected final function setPointerInstance (InputOutputPointer $pointerInstance) {
1283 $this->pointerInstance = $pointerInstance;
1287 * Getter for InputOutputPointer instance
1289 * @return $pointerInstance An instance of an InputOutputPointer class
1291 public final function getPointerInstance () {
1292 return $this->pointerInstance;
1296 * Setter for Indexable instance
1298 * @param $indexInstance An instance of an Indexable class
1301 protected final function setIndexInstance (Indexable $indexInstance) {
1302 $this->indexInstance = $indexInstance;
1306 * Getter for Indexable instance
1308 * @return $indexInstance An instance of an Indexable class
1310 public final function getIndexInstance () {
1311 return $this->indexInstance;
1315 * Checks whether an object equals this object. You should overwrite this
1316 * method to implement own equality checks
1318 * @param $objectInstance An instance of a FrameworkInterface object
1319 * @return $equals Whether both objects equals
1321 public function equals (FrameworkInterface $objectInstance) {
1324 $this->__toString() == $objectInstance->__toString()
1326 $this->hashCode() == $objectInstance->hashCode()
1329 // Return the result
1334 * Generates a generic hash code of this class. You should really overwrite
1335 * this method with your own hash code generator code. But keep KISS in mind.
1337 * @return $hashCode A generic hash code respresenting this whole class
1339 public function hashCode () {
1341 return crc32($this->__toString());
1345 * Formats computer generated price values into human-understandable formats
1346 * with thousand and decimal separators.
1348 * @param $value The in computer format value for a price
1349 * @param $currency The currency symbol (use HTML-valid characters!)
1350 * @param $decNum Number of decimals after commata
1351 * @return $price The for the current language formated price string
1352 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1353 * thousands separator
1356 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1357 // Are all required attriutes set?
1358 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1359 // Throw an exception
1360 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1364 $value = (float) $value;
1366 // Reformat the US number
1367 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1369 // Return as string...
1374 * Appends a trailing slash to a string
1376 * @param $str A string (maybe) without trailing slash
1377 * @return $str A string with an auto-appended trailing slash
1379 public final function addMissingTrailingSlash ($str) {
1380 // Is there a trailing slash?
1381 if (substr($str, -1, 1) != '/') {
1385 // Return string with trailing slash
1390 * Prepare the template engine (WebTemplateEngine by default) for a given
1391 * application helper instance (ApplicationHelper by default).
1393 * @param $applicationInstance An application helper instance or
1394 * null if we shall use the default
1395 * @return $templateInstance The template engine instance
1396 * @throws NullPointerException If the discovered application
1397 * instance is still null
1399 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1400 // Is the application instance set?
1401 if (is_null($applicationInstance)) {
1402 // Get the current instance
1403 $applicationInstance = $this->getApplicationInstance();
1406 if (is_null($applicationInstance)) {
1407 // Thrown an exception
1408 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1412 // Initialize the template engine
1413 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
1415 // Return the prepared instance
1416 return $templateInstance;
1420 * Debugs this instance by putting out it's full content
1422 * @param $message Optional message to show in debug output
1425 public final function debugInstance ($message = '') {
1426 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1427 restore_error_handler();
1432 // Is a message set?
1433 if (!empty($message)) {
1434 // Construct message
1435 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1438 // Generate the output
1439 $content .= sprintf('<pre>%s</pre>',
1442 print_r($this, TRUE)
1448 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>',
1449 $this->__toString(),
1451 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1456 * Replaces control characters with printable output
1458 * @param $str String with control characters
1459 * @return $str Replaced string
1461 protected function replaceControlCharacters ($str) {
1464 chr(13), '[r]', str_replace(
1465 chr(10), '[n]', str_replace(
1475 * Output a partial stub message for the caller method
1477 * @param $message An optional message to display
1480 protected function partialStub ($message = '') {
1481 // Get the backtrace
1482 $backtrace = debug_backtrace();
1484 // Generate the class::method string
1485 $methodName = 'UnknownClass->unknownMethod';
1486 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1487 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1490 // Construct the full message
1491 $stubMessage = sprintf('[%s:] Partial stub!',
1495 // Is the extra message given?
1496 if (!empty($message)) {
1497 // Then add it as well
1498 $stubMessage .= ' Message: ' . $message;
1501 // Debug instance is there?
1502 if (!is_null($this->getDebugInstance())) {
1503 // Output stub message
1504 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1507 trigger_error($stubMessage);
1513 * Outputs a debug backtrace and stops further script execution
1515 * @param $message An optional message to output
1516 * @param $doExit Whether exit the program (TRUE is default)
1519 public function debugBackTrace ($message = '', $doExit = TRUE) {
1520 // Sorry, there is no other way getting this nice backtrace
1521 if (!empty($message)) {
1523 printf('Message: %s<br />' . chr(10), $message);
1527 debug_print_backtrace();
1531 if ($doExit === TRUE) {
1537 * Creates an instance of a debugger instance
1539 * @param $className Name of the class (currently unsupported)
1540 * @return $debugInstance An instance of a debugger class
1542 public final static function createDebugInstance ($className) {
1543 // Is the instance set?
1544 if (!Registry::getRegistry()->instanceExists('debug')) {
1545 // Init debug instance
1546 $debugInstance = NULL;
1550 // Get a debugger instance
1551 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_class'));
1552 } catch (NullPointerException $e) {
1553 // Didn't work, no instance there
1554 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1557 // Empty string should be ignored and used for testing the middleware
1558 DebugMiddleware::getSelfInstance()->output('');
1560 // Set it in its own class. This will set it in the registry
1561 $debugInstance->setDebugInstance($debugInstance);
1563 // Get instance from registry
1564 $debugInstance = Registry::getRegistry()->getDebugInstance();
1568 return $debugInstance;
1572 * Simple output of a message with line-break
1574 * @param $message Message to output
1577 public function outputLine ($message) {
1579 print($message . PHP_EOL);
1583 * Outputs a debug message whether to debug instance (should be set!) or
1584 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1585 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1587 * @param $message Message we shall send out...
1588 * @param $doPrint Whether print or die here (default: print)
1589 * @paran $stripTags Whether to strip tags (default: FALSE)
1592 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1593 // Set debug instance to NULL
1594 $debugInstance = NULL;
1598 // Get debug instance
1599 $debugInstance = $this->getDebugInstance();
1600 } catch (NullPointerException $e) {
1601 // The debug instance is not set (yet)
1604 // Is the debug instance there?
1605 if (is_object($debugInstance)) {
1606 // Use debug output handler
1607 $debugInstance->output($message, $stripTags);
1609 if ($doPrint === FALSE) {
1610 // Die here if not printed
1614 // Are debug times enabled?
1615 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1617 $message = $this->getPrintableExecutionTime() . $message;
1621 if ($doPrint === TRUE) {
1623 $this->outputLine($message);
1632 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1634 * @param $str The string, what ever it is needs to be converted
1635 * @return $className Generated class name
1637 public function convertToClassName ($str) {
1641 // Convert all dashes in underscores
1642 $str = $this->convertDashesToUnderscores($str);
1644 // Now use that underscores to get classname parts for hungarian style
1645 foreach (explode('_', $str) as $strPart) {
1646 // Make the class name part lower case and first upper case
1647 $className .= ucfirst(strtolower($strPart));
1650 // Return class name
1655 * Converts dashes to underscores, e.g. useable for configuration entries
1657 * @param $str The string with maybe dashes inside
1658 * @return $str The converted string with no dashed, but underscores
1660 public final function convertDashesToUnderscores ($str) {
1662 $str = str_replace('-', '_', $str);
1664 // Return converted string
1669 * Marks up the code by adding e.g. line numbers
1671 * @param $phpCode Unmarked PHP code
1672 * @return $markedCode Marked PHP code
1674 public function markupCode ($phpCode) {
1679 $errorArray = error_get_last();
1681 // Init the code with error message
1682 if (is_array($errorArray)) {
1684 $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>',
1685 basename($errorArray['file']),
1686 $errorArray['line'],
1687 $errorArray['message'],
1692 // Add line number to the code
1693 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1695 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1697 htmlentities($code, ENT_QUOTES)
1706 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1707 * beatiful for web-based front-ends. If null is given a message id
1708 * null_timestamp will be resolved and returned.
1710 * @param $timestamp Timestamp to prepare (filter) for display
1711 * @return $readable A readable timestamp
1713 public function doFilterFormatTimestamp ($timestamp) {
1714 // Default value to return
1717 // Is the timestamp null?
1718 if (is_null($timestamp)) {
1719 // Get a message string
1720 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1722 switch ($this->getLanguageInstance()->getLanguageCode()) {
1723 case 'de': // German format is a bit different to default
1724 // Split the GMT stamp up
1725 $dateTime = explode(' ', $timestamp );
1726 $dateArray = explode('-', $dateTime[0]);
1727 $timeArray = explode(':', $dateTime[1]);
1729 // Construct the timestamp
1730 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1740 default: // Default is pass-through
1741 $readable = $timestamp;
1751 * Filter a given number into a localized number
1753 * @param $value The raw value from e.g. database
1754 * @return $localized Localized value
1756 public function doFilterFormatNumber ($value) {
1757 // Generate it from config and localize dependencies
1758 switch ($this->getLanguageInstance()->getLanguageCode()) {
1759 case 'de': // German format is a bit different to default
1760 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1763 default: // US, etc.
1764 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1773 * "Getter" for databse entry
1775 * @return $entry An array with database entries
1776 * @throws NullPointerException If the database result is not found
1777 * @throws InvalidDatabaseResultException If the database result is invalid
1779 protected final function getDatabaseEntry () {
1780 // Is there an instance?
1781 if (is_null($this->getResultInstance())) {
1782 // Throw an exception here
1783 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1787 $this->getResultInstance()->rewind();
1789 // Do we have an entry?
1790 if ($this->getResultInstance()->valid() === FALSE) {
1791 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1795 $this->getResultInstance()->next();
1798 $entry = $this->getResultInstance()->current();
1805 * Getter for field name
1807 * @param $fieldName Field name which we shall get
1808 * @return $fieldValue Field value from the user
1809 * @throws NullPointerException If the result instance is null
1811 public final function getField ($fieldName) {
1812 // Default field value
1815 // Get result instance
1816 $resultInstance = $this->getResultInstance();
1818 // Is this instance null?
1819 if (is_null($resultInstance)) {
1820 // Then the user instance is no longer valid (expired cookies?)
1821 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1824 // Get current array
1825 $fieldArray = $resultInstance->current();
1826 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
1828 // Convert dashes to underscore
1829 $fieldName = $this->convertDashesToUnderscores($fieldName);
1831 // Does the field exist?
1832 if (isset($fieldArray[$fieldName])) {
1834 $fieldValue = $fieldArray[$fieldName];
1836 // Missing field entry, may require debugging
1837 self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ':fieldname=' . $fieldName . ' not found!');
1845 * Flushs all pending updates to the database layer
1849 public function flushPendingUpdates () {
1850 // Get result instance
1851 $resultInstance = $this->getResultInstance();
1853 // Do we have data to update?
1854 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1855 // Get wrapper class name config entry
1856 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1858 // Create object instance
1859 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1861 // Yes, then send the whole result to the database layer
1862 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1867 * Outputs a deprecation warning to the developer.
1869 * @param $message The message we shall output to the developer
1871 * @todo Write a logging mechanism for productive mode
1873 public function deprecationWarning ($message) {
1874 // Is developer mode active?
1875 if (defined('DEVELOPER')) {
1876 // Debug instance is there?
1877 if (!is_null($this->getDebugInstance())) {
1878 // Output stub message
1879 self::createDebugInstance(__CLASS__)->debugOutput($message);
1882 trigger_error($message . "<br />\n");
1886 // @TODO Finish this part!
1887 $this->partialStub('Developer mode inactive. Message:' . $message);
1892 * Checks whether the given PHP extension is loaded
1894 * @param $phpExtension The PHP extension we shall check
1895 * @return $isLoaded Whether the PHP extension is loaded
1897 public final function isPhpExtensionLoaded ($phpExtension) {
1899 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1906 * "Getter" as a time() replacement but with milliseconds. You should use this
1907 * method instead of the encapsulated getimeofday() function.
1909 * @return $milliTime Timestamp with milliseconds
1911 public function getMilliTime () {
1912 // Get the time of day as float
1913 $milliTime = gettimeofday(TRUE);
1920 * Idles (sleeps) for given milliseconds
1922 * @return $hasSlept Whether it goes fine
1924 public function idle ($milliSeconds) {
1925 // Sleep is fine by default
1928 // Idle so long with found function
1929 if (function_exists('time_sleep_until')) {
1930 // Get current time and add idle time
1931 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1933 // New PHP 5.1.0 function found, ignore errors
1934 $hasSlept = @time_sleep_until($sleepUntil);
1937 * My Sun station doesn't have that function even with latest PHP
1940 usleep($milliSeconds * 1000);
1947 * Converts a hexadecimal string, even with negative sign as first string to
1948 * a decimal number using BC functions.
1950 * This work is based on comment #86673 on php.net documentation page at:
1951 * <http://de.php.net/manual/en/function.dechex.php#86673>
1953 * @param $hex Hexadecimal string
1954 * @return $dec Decimal number
1956 protected function hex2dec ($hex) {
1957 // Convert to all lower-case
1958 $hex = strtolower($hex);
1960 // Detect sign (negative/positive numbers)
1962 if (substr($hex, 0, 1) == '-') {
1964 $hex = substr($hex, 1);
1967 // Decode the hexadecimal string into a decimal number
1969 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1970 $factor = self::$hexdec[substr($hex, $i, 1)];
1971 $dec = bcadd($dec, bcmul($factor, $e));
1974 // Return the decimal number
1975 return $sign . $dec;
1979 * Converts even very large decimal numbers, also signed, to a hexadecimal
1982 * This work is based on comment #97756 on php.net documentation page at:
1983 * <http://de.php.net/manual/en/function.hexdec.php#97756>
1985 * @param $dec Decimal number, even with negative sign
1986 * @param $maxLength Optional maximum length of the string
1987 * @return $hex Hexadecimal string
1989 protected function dec2hex ($dec, $maxLength = 0) {
1990 // maxLength can be zero or devideable by 2
1991 assert(($maxLength == 0) || (($maxLength % 2) == 0));
1993 // Detect sign (negative/positive numbers)
2000 // Encode the decimal number into a hexadecimal string
2003 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2005 } while ($dec >= 1);
2008 * Leading zeros are required for hex-decimal "numbers". In some
2009 * situations more leading zeros are wanted, so check for both
2012 if ($maxLength > 0) {
2013 // Prepend more zeros
2014 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2015 } elseif ((strlen($hex) % 2) != 0) {
2016 // Only make string's length dividable by 2
2020 // Return the hexadecimal string
2021 return $sign . $hex;
2025 * Converts a ASCII string (0 to 255) into a decimal number.
2027 * @param $asc The ASCII string to be converted
2028 * @return $dec Decimal number
2030 protected function asc2dec ($asc) {
2031 // Convert it into a hexadecimal number
2032 $hex = bin2hex($asc);
2034 // And back into a decimal number
2035 $dec = $this->hex2dec($hex);
2042 * Converts a decimal number into an ASCII string.
2044 * @param $dec Decimal number
2045 * @return $asc An ASCII string
2047 protected function dec2asc ($dec) {
2048 // First convert the number into a hexadecimal string
2049 $hex = $this->dec2hex($dec);
2051 // Then convert it into the ASCII string
2052 $asc = $this->hex2asc($hex);
2059 * Converts a hexadecimal number into an ASCII string. Negative numbers
2062 * @param $hex Hexadecimal string
2063 * @return $asc An ASCII string
2065 protected function hex2asc ($hex) {
2066 // Check for length, it must be devideable by 2
2067 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2068 assert((strlen($hex) % 2) == 0);
2072 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2073 // Get the decimal number of the chunk
2074 $part = hexdec(substr($hex, $idx, 2));
2076 // Add it to the final string
2080 // Return the final string
2085 * Checks whether the given encoded data was encoded with Base64
2087 * @param $encodedData Encoded data we shall check
2088 * @return $isBase64 Whether the encoded data is Base64
2090 protected function isBase64Encoded ($encodedData) {
2092 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2099 * "Getter" to get response/request type from analysis of the system.
2101 * @return $responseType Analyzed response type
2103 protected function getResponseTypeFromSystem () {
2104 // Default is console
2105 $responseType = 'console';
2107 // Is 'HTTP_HOST' set?
2108 if (isset($_SERVER['HTTP_HOST'])) {
2109 // Then it is a HTTP response/request
2110 $responseType = 'http';
2114 return $responseType;
2118 * Gets a cache key from Criteria instance
2120 * @param $criteriaInstance An instance of a Criteria class
2121 * @param $onlyKeys Only use these keys for a cache key
2122 * @return $cacheKey A cache key suitable for lookup/storage purposes
2124 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2126 $cacheKey = sprintf('%s@%s',
2127 $this->__toString(),
2128 $criteriaInstance->getCacheKey($onlyKeys)
2132 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2137 * Getter for startup time in miliseconds
2139 * @return $startupTime Startup time in miliseconds
2141 protected function getStartupTime () {
2142 return self::$startupTime;
2146 * "Getter" for a printable currently execution time in nice braces
2148 * @return $executionTime Current execution time in nice braces
2150 protected function getPrintableExecutionTime () {
2151 // Caculate the execution time
2152 $executionTime = microtime(TRUE) - $this->getStartupTime();
2154 // Pack it in nice braces
2155 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2158 return $executionTime;
2162 * Hashes a given string with a simple but stronger hash function (no salt)
2163 * and hex-encode it.
2165 * @param $str The string to be hashed
2166 * @return $hash The hash from string $str
2168 public static final function hash ($str) {
2169 // Hash given string with (better secure) hasher
2170 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2177 * "Getter" for length of hash() output. This will be "cached" to speed up
2180 * @return $length Length of hash() output
2182 public static final function getHashLength () {
2184 if (is_null(self::$hashLength)) {
2185 // No, then hash a string and save its length.
2186 self::$hashLength = strlen(self::hash('abc123'));
2190 return self::$hashLength;
2194 * Checks whether the given number is really a number (only chars 0-9).
2196 * @param $num A string consisting only chars between 0 and 9
2197 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2198 * @param $assertMismatch Whether to assert mismatches
2199 * @return $ret The (hopefully) secured numbered value
2201 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2202 // Filter all numbers out
2203 $ret = preg_replace('/[^0123456789]/', '', $num);
2206 if ($castValue === TRUE) {
2207 // Cast to biggest numeric type
2208 $ret = (double) $ret;
2211 // Assert only if requested
2212 if ($assertMismatch === TRUE) {
2213 // Has the whole value changed?
2214 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2222 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2224 * @param $num A string consisting only chars between 0 and 9
2225 * @param $assertMismatch Whether to assert mismatches
2226 * @return $ret The (hopefully) secured hext-numbered value
2228 public function hexval ($num, $assertMismatch = FALSE) {
2229 // Filter all numbers out
2230 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2232 // Assert only if requested
2233 if ($assertMismatch === TRUE) {
2234 // Has the whole value changed?
2235 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2243 * Checks whether start/end marker are set
2245 * @param $data Data to be checked
2246 * @return $isset Whether start/end marker are set
2248 public final function ifStartEndMarkersSet ($data) {
2250 $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));
2252 // ... and return it
2257 * Determines if an element is set in the generic array
2259 * @param $keyGroup Main group for the key
2260 * @param $subGroup Sub group for the key
2261 * @param $key Key to check
2262 * @param $element Element to check
2263 * @return $isset Whether the given key is set
2265 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2267 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2270 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2276 * Determines if a key is set in the generic array
2278 * @param $keyGroup Main group for the key
2279 * @param $subGroup Sub group for the key
2280 * @param $key Key to check
2281 * @return $isset Whether the given key is set
2283 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2285 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2288 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2296 * Determines if a group is set in the generic array
2298 * @param $keyGroup Main group
2299 * @param $subGroup Sub group
2300 * @return $isset Whether the given group is set
2302 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2304 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2307 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2314 * Getter for sub key group
2316 * @param $keyGroup Main key group
2317 * @param $subGroup Sub key group
2318 * @return $array An array with all array elements
2320 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2322 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2323 // No, then abort here
2324 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2329 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2332 return $this->genericArray[$keyGroup][$subGroup];
2336 * Unsets a given key in generic array
2338 * @param $keyGroup Main group for the key
2339 * @param $subGroup Sub group for the key
2340 * @param $key Key to unset
2343 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2345 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2348 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2352 * Unsets a given element in generic array
2354 * @param $keyGroup Main group for the key
2355 * @param $subGroup Sub group for the key
2356 * @param $key Key to unset
2357 * @param $element Element to unset
2360 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2362 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2365 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2369 * Append a string to a given generic array key
2371 * @param $keyGroup Main group for the key
2372 * @param $subGroup Sub group for the key
2373 * @param $key Key to unset
2374 * @param $value Value to add/append
2377 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2379 //* 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);
2381 // Is it already there?
2382 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2384 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2387 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2392 * Append a string to a given generic array element
2394 * @param $keyGroup Main group for the key
2395 * @param $subGroup Sub group for the key
2396 * @param $key Key to unset
2397 * @param $element Element to check
2398 * @param $value Value to add/append
2401 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2403 //* 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);
2405 // Is it already there?
2406 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2408 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2411 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2416 * Initializes given generic array group
2418 * @param $keyGroup Main group for the key
2419 * @param $subGroup Sub group for the key
2420 * @param $key Key to use
2421 * @param $forceInit Optionally force initialization
2424 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2426 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2428 // Is it already set?
2429 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2430 // Already initialized
2431 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2436 $this->genericArray[$keyGroup][$subGroup] = array();
2440 * Initializes given generic array key
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 initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2450 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2452 // Is it already set?
2453 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2454 // Already initialized
2455 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2460 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2464 * Initializes given generic array element
2466 * @param $keyGroup Main group for the key
2467 * @param $subGroup Sub group for the key
2468 * @param $key Key to use
2469 * @param $element Element to use
2470 * @param $forceInit Optionally force initialization
2473 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2475 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2477 // Is it already set?
2478 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2479 // Already initialized
2480 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2485 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2489 * Pushes an element to a generic 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 $value Value to add/append
2495 * @return $count Number of array elements
2497 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2499 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2502 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2504 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2508 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2511 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2512 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2517 * Pushes an element to a generic array element
2519 * @param $keyGroup Main group for the key
2520 * @param $subGroup Sub group for the key
2521 * @param $key Key to use
2522 * @param $element Element to check
2523 * @param $value Value to add/append
2524 * @return $count Number of array elements
2526 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2528 //* 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));
2531 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2533 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2537 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2540 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2541 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2546 * Pops an element from a generic group
2548 * @param $keyGroup Main group for the key
2549 * @param $subGroup Sub group for the key
2550 * @param $key Key to unset
2551 * @return $value Last "popped" value
2553 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2555 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2558 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2560 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2565 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2568 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2569 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2574 * Shifts an element from a generic group
2576 * @param $keyGroup Main group for the key
2577 * @param $subGroup Sub group for the key
2578 * @param $key Key to unset
2579 * @return $value Last "popped" value
2581 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2583 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2586 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2588 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2593 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2596 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2597 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2602 * Count generic array group
2604 * @param $keyGroup Main group for the key
2605 * @return $count Count of given group
2607 protected final function countGenericArray ($keyGroup) {
2609 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2612 if (!isset($this->genericArray[$keyGroup])) {
2614 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2619 $count = count($this->genericArray[$keyGroup]);
2622 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2629 * Count generic array sub group
2631 * @param $keyGroup Main group for the key
2632 * @param $subGroup Sub group for the key
2633 * @return $count Count of given group
2635 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2637 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2640 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2642 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2647 $count = count($this->genericArray[$keyGroup][$subGroup]);
2650 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2657 * Count generic array elements
2659 * @param $keyGroup Main group for the key
2660 * @param $subGroup Sub group for the key
2661 * @para $key Key to count
2662 * @return $count Count of given key
2664 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2666 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2669 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2671 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2673 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2675 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2680 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2683 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2690 * Getter for whole generic group array
2692 * @param $keyGroup Key group to get
2693 * @return $array Whole generic array group
2695 protected final function getGenericArray ($keyGroup) {
2697 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2700 if (!isset($this->genericArray[$keyGroup])) {
2702 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2707 return $this->genericArray[$keyGroup];
2711 * Setter for generic array key
2713 * @param $keyGroup Key group to get
2714 * @param $subGroup Sub group for the key
2715 * @param $key Key to unset
2716 * @param $value Mixed value from generic array element
2719 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2721 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2724 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2728 * Getter for generic array key
2730 * @param $keyGroup Key group to get
2731 * @param $subGroup Sub group for the key
2732 * @param $key Key to unset
2733 * @return $value Mixed value from generic array element
2735 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2737 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2740 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2742 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2747 return $this->genericArray[$keyGroup][$subGroup][$key];
2751 * Sets a value in given generic array key/element
2753 * @param $keyGroup Main group for the key
2754 * @param $subGroup Sub group for the key
2755 * @param $key Key to set
2756 * @param $element Element to set
2757 * @param $value Value to set
2760 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2762 //* 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));
2765 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2769 * Getter for generic array element
2771 * @param $keyGroup Key group to get
2772 * @param $subGroup Sub group for the key
2773 * @param $key Key to look for
2774 * @param $element Element to look for
2775 * @return $value Mixed value from generic array element
2777 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2779 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2782 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2784 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2789 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2793 * Checks if a given sub group is valid (array)
2795 * @param $keyGroup Key group to get
2796 * @param $subGroup Sub group for the key
2797 * @return $isValid Whether given sub group is valid
2799 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2801 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2804 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
2811 * Checks if a given key is valid (array)
2813 * @param $keyGroup Key group to get
2814 * @param $subGroup Sub group for the key
2815 * @param $key Key to check
2816 * @return $isValid Whether given sub group is valid
2818 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
2820 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2823 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
2830 * Translates boolean TRUE to 'Y' and FALSE to 'N'
2832 * @param $boolean Boolean value
2833 * @return $translated Translated boolean value
2835 public static final function translateBooleanToYesNo ($boolean) {
2836 // Make sure it is really boolean
2837 assert(is_bool($boolean));
2840 $translated = ($boolean === TRUE) ? 'Y' : 'N';
2842 // ... and return it
2847 * Initializes counter for valid entries, arrays for damaged entries and
2848 * an array for gap seek positions. If you call this method on your own,
2849 * please re-analyze the file structure. So you are better to call
2850 * analyzeFile() instead of this method.
2854 protected function initCountersGapsArray () {
2855 // Init counter and seek position
2856 $this->setCounter(0);
2857 $this->setSeekPosition(0);
2860 $this->gaps = array();
2861 $this->damagedEntries = array();
2865 * Getter for total entries
2867 * @return $totalEntries Total entries in this file
2869 protected final function getCounter () {
2871 return $this->totalEntries;
2875 * Setter for total entries
2877 * @param $totalEntries Total entries in this file
2880 protected final function setCounter ($counter) {
2882 $this->totalEntries = $counter;
2890 protected final function incrementCounter () {
2892 $this->totalEntries++;
2896 * Getter for header size
2898 * @return $totalEntries Size of file header
2900 protected final function getHeaderSize () {
2902 return $this->headerSize;
2906 * Setter for header size
2908 * @param $headerSize Size of file header
2911 protected final function setHeaderSize ($headerSize) {
2913 $this->headerSize = $headerSize;
2917 * Getter for seek position
2919 * @return $seekPosition Current seek position (stored here in object)
2921 protected final function getSeekPosition () {
2923 return $this->seekPosition;
2927 * Setter for seek position
2929 * @param $seekPosition Current seek position (stored here in object)
2932 protected final function setSeekPosition ($seekPosition) {
2934 $this->seekPosition = $seekPosition;
2938 * Updates seekPosition attribute from file to avoid to much access on file.
2942 protected function updateSeekPosition () {
2943 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
2945 // Get key (= seek position)
2946 $seekPosition = $this->getIteratorInstance()->key();
2947 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Setting seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
2950 $this->setSeekPosition($seekPosition);
2952 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
2956 * Reads the file header
2960 protected function readFileHeader () {
2961 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
2963 // First rewind to beginning as the header sits at the beginning ...
2964 $this->getIteratorInstance()->rewind();
2966 // Then read it (see constructor for calculation)
2967 $data = $this->getIteratorInstance()->read($this->getHeaderSize());
2968 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getHeaderSize()));
2970 // Have all requested bytes been read?
2971 assert(strlen($data) == $this->getHeaderSize());
2972 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
2974 // Last character must be the separator
2975 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
2976 assert(substr($data, -1, 1) == chr(self::SEPARATOR_HEADER_ENTRIES));
2977 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
2979 // Okay, then remove it
2980 $data = substr($data, 0, -1);
2982 // And update seek position
2983 $this->updateSeekPosition();
2989 * 1 => Total entries
2990 * 2 => Current seek position
2992 $this->header = explode(chr(self::SEPARATOR_HEADER_DATA), $data);
2994 // Check if the array has only 3 elements
2995 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($this->header), print_r($this->header, TRUE)));
2996 assert(count($this->header) == 3);
2997 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
3000 assert($this->header[0] == self::STACK_MAGIC);
3001 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
3003 // Check length of count and seek position
3004 assert(strlen($this->header[1]) == self::LENGTH_COUNT);
3005 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
3006 assert(strlen($this->header[2]) == self::LENGTH_POSITION);
3007 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
3009 // Decode count and seek position
3010 $this->header[1] = hex2bin($this->header[1]);
3011 $this->header[2] = hex2bin($this->header[2]);
3013 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
<