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 - 2015 Core Developer Team
9 * @license GNU GPL 3.0 or any newer version
10 * @link http://www.shipsimu.org
12 * This program is free software: you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation, either version 3 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
27 * Length of output from hash()
29 private static $hashLength = NULL;
34 private $realClass = 'BaseFrameworkSystem';
37 * Instance of a request class
39 private $requestInstance = NULL;
42 * Instance of a response class
44 private $responseInstance = NULL;
47 * Search criteria instance
49 private $searchInstance = NULL;
52 * Update criteria instance
54 private $updateInstance = NULL;
57 * The file I/O instance for the template loader
59 private $fileIoInstance = NULL;
64 private $resolverInstance = NULL;
67 * Template engine instance
69 private $templateInstance = NULL;
72 * Database result instance
74 private $resultInstance = NULL;
77 * Instance for user class
79 private $userInstance = NULL;
82 * A controller instance
84 private $controllerInstance = NULL;
89 private $rngInstance = NULL;
92 * Instance of a crypto helper
94 private $cryptoInstance = NULL;
97 * Instance of an Iterator class
99 private $iteratorInstance = NULL;
102 * Instance of the list
104 private $listInstance = NULL;
109 private $menuInstance = NULL;
112 * Instance of the image
114 private $imageInstance = NULL;
117 * Instance of the stacker
119 private $stackInstance = NULL;
122 * A Compressor instance
124 private $compressorInstance = NULL;
127 * A Parseable instance
129 private $parserInstance = NULL;
132 * A HandleableProtocol instance
134 private $protocolInstance = NULL;
137 * A database wrapper instance
139 private $databaseInstance = NULL;
142 * A helper instance for the form
144 private $helperInstance = NULL;
147 * An instance of a Source class
149 private $sourceInstance = NULL;
152 * An instance of a UrlSource class
154 private $urlSourceInstance = 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 Block class
199 private $blockInstance = NULL;
204 private $minableInstance = NULL;
207 * A FrameworkDirectory instance
209 private $directoryInstance = NULL;
214 private $listenerInstance = NULL;
217 * Thousands separator
219 private $thousands = '.'; // German
224 private $decimals = ','; // German
229 private $socketResource = FALSE;
232 * Regular expression to use for validation
234 private $regularExpression = '';
239 private $packageData = array();
244 private $genericArray = array();
249 private $commandName = '';
254 private $controllerName = '';
257 * Array with bitmasks and such for pack/unpack methods to support both
258 * 32-bit and 64-bit systems
260 private $packingData = array(
263 'left' => 0xffff0000,
264 'right' => 0x0000ffff,
270 'left' => 0xffffffff00000000,
271 'right' => 0x00000000ffffffff,
278 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
280 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
282 private $archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
284 /***********************
285 * Exception codes.... *
286 ***********************/
288 // @todo Try to clean these constants up
289 const EXCEPTION_IS_NULL_POINTER = 0x001;
290 const EXCEPTION_IS_NO_OBJECT = 0x002;
291 const EXCEPTION_IS_NO_ARRAY = 0x003;
292 const EXCEPTION_MISSING_METHOD = 0x004;
293 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
294 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
295 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
296 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
297 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
298 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
299 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
300 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
301 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
302 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
303 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
304 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
305 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
306 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
307 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
308 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
309 const EXCEPTION_PATH_NOT_FOUND = 0x015;
310 const EXCEPTION_INVALID_PATH_NAME = 0x016;
311 const EXCEPTION_READ_PROTECED_PATH = 0x017;
312 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
313 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
314 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
315 const EXCEPTION_INVALID_RESOURCE = 0x01b;
316 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
317 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
318 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
319 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
320 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
321 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
322 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
323 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
324 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
325 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
326 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
327 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
328 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
329 const EXCEPTION_INVALID_STRING = 0x029;
330 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
331 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
332 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
333 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
334 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
335 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
336 const EXCEPTION_MISSING_ELEMENT = 0x030;
337 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
338 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
339 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
340 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
341 const EXCEPTION_FATAL_ERROR = 0x035;
342 const EXCEPTION_FILE_NOT_FOUND = 0x036;
343 const EXCEPTION_ASSERTION_FAILED = 0x037;
344 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
345 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
346 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03a;
349 * Hexadecimal->Decimal translation array
351 private static $hexdec = array(
371 * Decimal->hexadecimal translation array
373 private static $dechex = array(
393 * Startup time in miliseconds
395 private static $startupTime = 0;
398 * Protected super constructor
400 * @param $className Name of the class
403 protected function __construct ($className) {
405 $this->setRealClass($className);
407 // Set configuration instance if no registry ...
408 if (!$this instanceof Register) {
409 // ... because registries doesn't need to be configured
410 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
413 // Is the startup time set? (0 cannot be TRUE anymore)
414 if (self::$startupTime == 0) {
416 self::$startupTime = microtime(TRUE);
421 * Destructor for all classes
425 public function __destruct () {
426 // Flush any updated entries to the database
427 $this->flushPendingUpdates();
429 // Is this object already destroyed?
430 if ($this->__toString() != 'DestructedObject') {
431 // Destroy all informations about this class but keep some text about it alive
432 $this->setRealClass('DestructedObject');
433 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
434 // Already destructed object
435 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
440 // Do not call this twice
441 trigger_error(__METHOD__ . ': Called twice.');
447 * The __call() method where all non-implemented methods end up
449 * @param $methodName Name of the missing method
450 * @args $args Arguments passed to the method
453 public final function __call ($methodName, $args) {
454 return self::__callStatic($methodName, $args);
458 * The __callStatic() method where all non-implemented static methods end up
460 * @param $methodName Name of the missing method
461 * @args $args Arguments passed to the method
464 public static final function __callStatic ($methodName, $args) {
465 // Init argument string
468 // Is it empty or an array?
471 $argsString = 'NULL';
472 } elseif (is_array($args)) {
473 // Some arguments are there
474 foreach ($args as $arg) {
475 // Add the value itself if not array. This prevents 'array to string conversion' message
476 if (is_array($arg)) {
477 $argsString .= 'Array';
482 // Add data about the argument
483 $argsString .= ' (' . gettype($arg);
485 if (is_string($arg)) {
486 // Add length for strings
487 $argsString .= ', ' . strlen($arg);
488 } elseif (is_array($arg)) {
489 // .. or size if array
490 $argsString .= ', ' . count($arg);
491 } elseif ($arg === TRUE) {
492 // ... is boolean 'TRUE'
493 $argsString .= ', TRUE';
494 } elseif ($arg === FALSE) {
495 // ... is boolean 'FALSE'
496 $argsString .= ', FALSE';
500 $argsString .= '), ';
504 if (substr($argsString, -2, 1) == ',') {
505 $argsString = substr($argsString, 0, -2);
508 // Invalid arguments!
509 $argsString = '!INVALID:' . gettype($args) . '!';
512 // Output stub message
513 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
514 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
524 * Getter for $realClass
526 * @return $realClass The name of the real class (not BaseFrameworkSystem)
528 public function __toString () {
529 return $this->realClass;
533 * Magic method to catch setting of missing but set class fields/attributes
535 * @param $name Name of the field/attribute
536 * @param $value Value to store
539 public final function __set ($name, $value) {
540 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
543 print_r($value, TRUE)
548 * Magic method to catch getting of missing fields/attributes
550 * @param $name Name of the field/attribute
553 public final function __get ($name) {
554 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
560 * Magic method to catch unsetting of missing fields/attributes
562 * @param $name Name of the field/attribute
565 public final function __unset ($name) {
566 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
572 * Magic method to catch object serialization
574 * @return $unsupported Unsupported method
575 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
577 public final function __sleep () {
578 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
582 * Magic method to catch object deserialization
584 * @return $unsupported Unsupported method
585 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
587 public final function __wakeup () {
588 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
592 * Magic method to catch calls when an object instance is called
594 * @return $unsupported Unsupported method
595 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
597 public final function __invoke () {
598 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
602 * Setter for the real class name
604 * @param $realClass Class name (string)
607 public final function setRealClass ($realClass) {
609 $this->realClass = (string) $realClass;
613 * Setter for database result instance
615 * @param $resultInstance An instance of a database result class
617 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
619 protected final function setResultInstance (SearchableResult $resultInstance) {
620 $this->resultInstance = $resultInstance;
624 * Getter for database result instance
626 * @return $resultInstance An instance of a database result class
628 public final function getResultInstance () {
629 return $this->resultInstance;
633 * Setter for template engine instances
635 * @param $templateInstance An instance of a template engine class
638 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
639 $this->templateInstance = $templateInstance;
643 * Getter for template engine instances
645 * @return $templateInstance An instance of a template engine class
647 protected final function getTemplateInstance () {
648 return $this->templateInstance;
652 * Setter for search instance
654 * @param $searchInstance Searchable criteria instance
657 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
658 $this->searchInstance = $searchInstance;
662 * Getter for search instance
664 * @return $searchInstance Searchable criteria instance
666 public final function getSearchInstance () {
667 return $this->searchInstance;
671 * Setter for update instance
673 * @param $updateInstance Searchable criteria instance
676 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
677 $this->updateInstance = $updateInstance;
681 * Getter for update instance
683 * @return $updateInstance Updateable criteria instance
685 public final function getUpdateInstance () {
686 return $this->updateInstance;
690 * Setter for resolver instance
692 * @param $resolverInstance Instance of a command resolver class
695 public final function setResolverInstance (Resolver $resolverInstance) {
696 $this->resolverInstance = $resolverInstance;
700 * Getter for resolver instance
702 * @return $resolverInstance Instance of a command resolver class
704 public final function getResolverInstance () {
705 return $this->resolverInstance;
709 * Setter for language instance
711 * @param $configInstance The configuration instance which shall
712 * be FrameworkConfiguration
715 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
716 Registry::getRegistry()->addInstance('config', $configInstance);
720 * Getter for configuration instance
722 * @return $configInstance Configuration instance
724 public final function getConfigInstance () {
725 $configInstance = Registry::getRegistry()->getInstance('config');
726 return $configInstance;
730 * Setter for debug instance
732 * @param $debugInstance The instance for debug output class
735 public final function setDebugInstance (DebugMiddleware $debugInstance) {
736 Registry::getRegistry()->addInstance('debug', $debugInstance);
740 * Getter for debug instance
742 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
744 public final function getDebugInstance () {
745 // Get debug instance
746 $debugInstance = Registry::getRegistry()->getInstance('debug');
749 return $debugInstance;
753 * Setter for web output instance
755 * @param $webInstance The instance for web output class
758 public final function setWebOutputInstance (OutputStreamer $webInstance) {
759 Registry::getRegistry()->addInstance('web_output', $webInstance);
763 * Getter for web output instance
765 * @return $webOutputInstance - Instance to class WebOutput
767 public final function getWebOutputInstance () {
768 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
769 return $webOutputInstance;
773 * Setter for database instance
775 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
778 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
779 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
783 * Getter for database layer
785 * @return $databaseInstance The database layer instance
787 public final function getDatabaseInstance () {
789 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
792 return $databaseInstance;
796 * Setter for compressor channel
798 * @param $compressorInstance An instance of CompressorChannel
801 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
802 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
806 * Getter for compressor channel
808 * @return $compressorInstance The compressor channel
810 public final function getCompressorChannel () {
811 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
812 return $compressorInstance;
816 * Protected getter for a manageable application helper class
818 * @return $applicationInstance An instance of a manageable application helper class
820 protected final function getApplicationInstance () {
821 $applicationInstance = Registry::getRegistry()->getInstance('application');
822 return $applicationInstance;
826 * Setter for a manageable application helper class
828 * @param $applicationInstance An instance of a manageable application helper class
831 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
832 Registry::getRegistry()->addInstance('application', $applicationInstance);
836 * Setter for request instance
838 * @param $requestInstance An instance of a Requestable class
841 public final function setRequestInstance (Requestable $requestInstance) {
842 $this->requestInstance = $requestInstance;
846 * Getter for request instance
848 * @return $requestInstance An instance of a Requestable class
850 public final function getRequestInstance () {
851 return $this->requestInstance;
855 * Setter for response instance
857 * @param $responseInstance An instance of a Responseable class
860 public final function setResponseInstance (Responseable $responseInstance) {
861 $this->responseInstance = $responseInstance;
865 * Getter for response instance
867 * @return $responseInstance An instance of a Responseable class
869 public final function getResponseInstance () {
870 return $this->responseInstance;
874 * Private getter for language instance
876 * @return $langInstance An instance to the language sub-system
878 protected final function getLanguageInstance () {
879 $langInstance = Registry::getRegistry()->getInstance('language');
880 return $langInstance;
884 * Setter for language instance
886 * @param $langInstance An instance to the language sub-system
888 * @see LanguageSystem
890 public final function setLanguageInstance (ManageableLanguage $langInstance) {
891 Registry::getRegistry()->addInstance('language', $langInstance);
895 * Private getter for file IO instance
897 * @return $fileIoInstance An instance to the file I/O sub-system
899 protected final function getFileIoInstance () {
900 return $this->fileIoInstance;
904 * Setter for file I/O instance
906 * @param $fileIoInstance An instance to the file I/O sub-system
909 public final function setFileIoInstance (IoHandler $fileIoInstance) {
910 $this->fileIoInstance = $fileIoInstance;
914 * Protected setter for user instance
916 * @param $userInstance An instance of a user class
919 protected final function setUserInstance (ManageableAccount $userInstance) {
920 $this->userInstance = $userInstance;
924 * Getter for user instance
926 * @return $userInstance An instance of a user class
928 public final function getUserInstance () {
929 return $this->userInstance;
933 * Setter for controller instance (this surely breaks a bit the MVC patterm)
935 * @param $controllerInstance An instance of the controller
938 public final function setControllerInstance (Controller $controllerInstance) {
939 $this->controllerInstance = $controllerInstance;
943 * Getter for controller instance (this surely breaks a bit the MVC patterm)
945 * @return $controllerInstance An instance of the controller
947 public final function getControllerInstance () {
948 return $this->controllerInstance;
952 * Setter for RNG instance
954 * @param $rngInstance An instance of a random number generator (RNG)
957 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
958 $this->rngInstance = $rngInstance;
962 * Getter for RNG instance
964 * @return $rngInstance An instance of a random number generator (RNG)
966 public final function getRngInstance () {
967 return $this->rngInstance;
971 * Setter for Cryptable instance
973 * @param $cryptoInstance An instance of a Cryptable class
976 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
977 $this->cryptoInstance = $cryptoInstance;
981 * Getter for Cryptable instance
983 * @return $cryptoInstance An instance of a Cryptable class
985 public final function getCryptoInstance () {
986 return $this->cryptoInstance;
990 * Setter for the list instance
992 * @param $listInstance A list of Listable
995 protected final function setListInstance (Listable $listInstance) {
996 $this->listInstance = $listInstance;
1000 * Getter for the list instance
1002 * @return $listInstance A list of Listable
1004 protected final function getListInstance () {
1005 return $this->listInstance;
1009 * Setter for the menu instance
1011 * @param $menuInstance A RenderableMenu instance
1014 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1015 $this->menuInstance = $menuInstance;
1019 * Getter for the menu instance
1021 * @return $menuInstance A RenderableMenu instance
1023 protected final function getMenuInstance () {
1024 return $this->menuInstance;
1028 * Setter for image instance
1030 * @param $imageInstance An instance of an image
1033 public final function setImageInstance (BaseImage $imageInstance) {
1034 $this->imageInstance = $imageInstance;
1038 * Getter for image instance
1040 * @return $imageInstance An instance of an image
1042 public final function getImageInstance () {
1043 return $this->imageInstance;
1047 * Setter for stacker instance
1049 * @param $stackInstance An instance of an stacker
1052 public final function setStackInstance (Stackable $stackInstance) {
1053 $this->stackInstance = $stackInstance;
1057 * Getter for stacker instance
1059 * @return $stackInstance An instance of an stacker
1061 public final function getStackInstance () {
1062 return $this->stackInstance;
1066 * Setter for compressor instance
1068 * @param $compressorInstance An instance of an compressor
1071 public final function setCompressorInstance (Compressor $compressorInstance) {
1072 $this->compressorInstance = $compressorInstance;
1076 * Getter for compressor instance
1078 * @return $compressorInstance An instance of an compressor
1080 public final function getCompressorInstance () {
1081 return $this->compressorInstance;
1085 * Setter for Parseable instance
1087 * @param $parserInstance An instance of an Parseable
1090 public final function setParserInstance (Parseable $parserInstance) {
1091 $this->parserInstance = $parserInstance;
1095 * Getter for Parseable instance
1097 * @return $parserInstance An instance of an Parseable
1099 public final function getParserInstance () {
1100 return $this->parserInstance;
1104 * Setter for HandleableProtocol instance
1106 * @param $protocolInstance An instance of an HandleableProtocol
1109 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1110 $this->protocolInstance = $protocolInstance;
1114 * Getter for HandleableProtocol instance
1116 * @return $protocolInstance An instance of an HandleableProtocol
1118 public final function getProtocolInstance () {
1119 return $this->protocolInstance;
1123 * Setter for DatabaseWrapper instance
1125 * @param $wrapperInstance An instance of an DatabaseWrapper
1128 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1129 $this->wrapperInstance = $wrapperInstance;
1133 * Getter for DatabaseWrapper instance
1135 * @return $wrapperInstance An instance of an DatabaseWrapper
1137 public final function getWrapperInstance () {
1138 return $this->wrapperInstance;
1142 * Setter for socket resource
1144 * @param $socketResource A valid socket resource
1147 public final function setSocketResource ($socketResource) {
1148 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1149 $this->socketResource = $socketResource;
1153 * Getter for socket resource
1155 * @return $socketResource A valid socket resource
1157 public final function getSocketResource () {
1158 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1159 return $this->socketResource;
1163 * Setter for regular expression
1165 * @param $regularExpression A valid regular expression
1168 public final function setRegularExpression ($regularExpression) {
1169 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1170 $this->regularExpression = $regularExpression;
1174 * Getter for regular expression
1176 * @return $regularExpression A valid regular expression
1178 public final function getRegularExpression () {
1179 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1180 return $this->regularExpression;
1184 * Setter for helper instance
1186 * @param $helperInstance An instance of a helper class
1189 protected final function setHelperInstance (Helper $helperInstance) {
1190 $this->helperInstance = $helperInstance;
1194 * Getter for helper instance
1196 * @return $helperInstance An instance of a helper class
1198 public final function getHelperInstance () {
1199 return $this->helperInstance;
1203 * Setter for a Source instance
1205 * @param $sourceInstance An instance of a Source class
1208 protected final function setSourceInstance (Source $sourceInstance) {
1209 $this->sourceInstance = $sourceInstance;
1213 * Getter for a Source instance
1215 * @return $sourceInstance An instance of a Source class
1217 protected final function getSourceInstance () {
1218 return $this->sourceInstance;
1222 * Setter for a UrlSource instance
1224 * @param $sourceInstance An instance of a UrlSource class
1227 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1228 $this->urlSourceInstance = $urlSourceInstance;
1232 * Getter for a UrlSource instance
1234 * @return $urlSourceInstance An instance of a UrlSource class
1236 protected final function getUrlSourceInstance () {
1237 return $this->urlSourceInstance;
1241 * Getter for a InputStream instance
1243 * @param $inputStreamInstance The InputStream instance
1245 protected final function getInputStreamInstance () {
1246 return $this->inputStreamInstance;
1250 * Setter for a InputStream instance
1252 * @param $inputStreamInstance The InputStream instance
1255 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1256 $this->inputStreamInstance = $inputStreamInstance;
1260 * Getter for a OutputStream instance
1262 * @param $outputStreamInstance The OutputStream instance
1264 protected final function getOutputStreamInstance () {
1265 return $this->outputStreamInstance;
1269 * Setter for a OutputStream instance
1271 * @param $outputStreamInstance The OutputStream instance
1274 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1275 $this->outputStreamInstance = $outputStreamInstance;
1279 * Setter for handler instance
1281 * @param $handlerInstance An instance of a Handleable class
1284 protected final function setHandlerInstance (Handleable $handlerInstance) {
1285 $this->handlerInstance = $handlerInstance;
1289 * Getter for handler instance
1291 * @return $handlerInstance A Networkable instance
1293 protected final function getHandlerInstance () {
1294 return $this->handlerInstance;
1298 * Setter for visitor instance
1300 * @param $visitorInstance A Visitor instance
1303 protected final function setVisitorInstance (Visitor $visitorInstance) {
1304 $this->visitorInstance = $visitorInstance;
1308 * Getter for visitor instance
1310 * @return $visitorInstance A Visitor instance
1312 protected final function getVisitorInstance () {
1313 return $this->visitorInstance;
1317 * Setter for DHT instance
1319 * @param $dhtInstance A Distributable instance
1322 protected final function setDhtInstance (Distributable $dhtInstance) {
1323 $this->dhtInstance = $dhtInstance;
1327 * Getter for DHT instance
1329 * @return $dhtInstance A Distributable instance
1331 protected final function getDhtInstance () {
1332 return $this->dhtInstance;
1336 * Setter for raw package Data
1338 * @param $packageData Raw package Data
1341 public final function setPackageData (array $packageData) {
1342 $this->packageData = $packageData;
1346 * Getter for raw package Data
1348 * @return $packageData Raw package Data
1350 public function getPackageData () {
1351 return $this->packageData;
1356 * Setter for Iterator instance
1358 * @param $iteratorInstance An instance of an Iterator
1361 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1362 $this->iteratorInstance = $iteratorInstance;
1366 * Getter for Iterator instance
1368 * @return $iteratorInstance An instance of an Iterator
1370 public final function getIteratorInstance () {
1371 return $this->iteratorInstance;
1375 * Setter for FilePointer instance
1377 * @param $pointerInstance An instance of an FilePointer class
1380 protected final function setPointerInstance (FilePointer $pointerInstance) {
1381 $this->pointerInstance = $pointerInstance;
1385 * Getter for FilePointer instance
1387 * @return $pointerInstance An instance of an FilePointer class
1389 public final function getPointerInstance () {
1390 return $this->pointerInstance;
1394 * Unsets pointer instance which triggers a call of __destruct() if the
1395 * instance is still there. This is surely not fatal on already "closed"
1396 * file pointer instances.
1398 * I don't want to mess around with above setter by giving it a default
1399 * value NULL as setter should always explicitly only set (existing) object
1400 * instances and NULL is NULL.
1404 protected final function unsetPointerInstance () {
1405 // Simply it to NULL
1406 $this->pointerInstance = NULL;
1410 * Setter for Indexable instance
1412 * @param $indexInstance An instance of an Indexable class
1415 protected final function setIndexInstance (Indexable $indexInstance) {
1416 $this->indexInstance = $indexInstance;
1420 * Getter for Indexable instance
1422 * @return $indexInstance An instance of an Indexable class
1424 public final function getIndexInstance () {
1425 return $this->indexInstance;
1429 * Setter for Block instance
1431 * @param $blockInstance An instance of an Block class
1434 protected final function setBlockInstance (Block $blockInstance) {
1435 $this->blockInstance = $blockInstance;
1439 * Getter for Block instance
1441 * @return $blockInstance An instance of an Block class
1443 public final function getBlockInstance () {
1444 return $this->blockInstance;
1448 * Setter for Minable instance
1450 * @param $minableInstance A Minable instance
1453 protected final function setMinableInstance (Minable $minableInstance) {
1454 $this->minableInstance = $minableInstance;
1458 * Getter for minable instance
1460 * @return $minableInstance A Minable instance
1462 protected final function getMinableInstance () {
1463 return $this->minableInstance;
1467 * Setter for FrameworkDirectory instance
1469 * @param $directoryInstance A FrameworkDirectoryPointer instance
1472 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1473 $this->directoryInstance = $directoryInstance;
1477 * Getter for FrameworkDirectory instance
1479 * @return $directoryInstance A FrameworkDirectory instance
1481 protected final function getDirectoryInstance () {
1482 return $this->directoryInstance;
1486 * Setter for listener instance
1488 * @param $listenerInstance A Listenable instance
1491 protected final function setListenerInstance (Listenable $listenerInstance) {
1492 $this->listenerInstance = $listenerInstance;
1496 * Getter for listener instance
1498 * @return $listenerInstance A Listenable instance
1500 protected final function getListenerInstance () {
1501 return $this->listenerInstance;
1505 * Setter for command name
1507 * @param $commandName Last validated command name
1510 protected final function setCommandName ($commandName) {
1511 $this->commandName = $commandName;
1515 * Getter for command name
1517 * @return $commandName Last validated command name
1519 protected final function getCommandName () {
1520 return $this->commandName;
1524 * Setter for controller name
1526 * @param $controllerName Last validated controller name
1529 protected final function setControllerName ($controllerName) {
1530 $this->controllerName = $controllerName;
1534 * Getter for controller name
1536 * @return $controllerName Last validated controller name
1538 protected final function getControllerName () {
1539 return $this->controllerName;
1543 * Checks whether an object equals this object. You should overwrite this
1544 * method to implement own equality checks
1546 * @param $objectInstance An instance of a FrameworkInterface object
1547 * @return $equals Whether both objects equals
1549 public function equals (FrameworkInterface $objectInstance) {
1552 $this->__toString() == $objectInstance->__toString()
1554 $this->hashCode() == $objectInstance->hashCode()
1557 // Return the result
1562 * Generates a generic hash code of this class. You should really overwrite
1563 * this method with your own hash code generator code. But keep KISS in mind.
1565 * @return $hashCode A generic hash code respresenting this whole class
1567 public function hashCode () {
1569 return crc32($this->__toString());
1573 * Formats computer generated price values into human-understandable formats
1574 * with thousand and decimal separators.
1576 * @param $value The in computer format value for a price
1577 * @param $currency The currency symbol (use HTML-valid characters!)
1578 * @param $decNum Number of decimals after commata
1579 * @return $price The for the current language formated price string
1580 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1581 * thousands separator
1584 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1585 // Are all required attriutes set?
1586 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1587 // Throw an exception
1588 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1592 $value = (float) $value;
1594 // Reformat the US number
1595 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1597 // Return as string...
1602 * Appends a trailing slash to a string
1604 * @param $str A string (maybe) without trailing slash
1605 * @return $str A string with an auto-appended trailing slash
1607 public final function addMissingTrailingSlash ($str) {
1608 // Is there a trailing slash?
1609 if (substr($str, -1, 1) != '/') {
1613 // Return string with trailing slash
1618 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1619 * application helper instance (ApplicationHelper by default).
1621 * @param $applicationInstance An application helper instance or
1622 * null if we shall use the default
1623 * @return $templateInstance The template engine instance
1624 * @throws NullPointerException If the discovered application
1625 * instance is still null
1627 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1628 // Is the application instance set?
1629 if (is_null($applicationInstance)) {
1630 // Get the current instance
1631 $applicationInstance = $this->getApplicationInstance();
1634 if (is_null($applicationInstance)) {
1635 // Thrown an exception
1636 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1640 // Initialize the template engine
1641 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1643 // Return the prepared instance
1644 return $templateInstance;
1648 * Debugs this instance by putting out it's full content
1650 * @param $message Optional message to show in debug output
1653 public final function debugInstance ($message = '') {
1654 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1655 restore_error_handler();
1660 // Is a message set?
1661 if (!empty($message)) {
1662 // Construct message
1663 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1666 // Generate the output
1667 $content .= sprintf('<pre>%s</pre>',
1670 print_r($this, TRUE)
1676 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>',
1677 $this->__toString(),
1679 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1684 * Replaces control characters with printable output
1686 * @param $str String with control characters
1687 * @return $str Replaced string
1689 protected function replaceControlCharacters ($str) {
1692 chr(13), '[r]', str_replace(
1693 chr(10), '[n]', str_replace(
1703 * Output a partial stub message for the caller method
1705 * @param $message An optional message to display
1708 protected function partialStub ($message = '') {
1709 // Get the backtrace
1710 $backtrace = debug_backtrace();
1712 // Generate the class::method string
1713 $methodName = 'UnknownClass->unknownMethod';
1714 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1715 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1718 // Construct the full message
1719 $stubMessage = sprintf('[%s:] Partial stub!',
1723 // Is the extra message given?
1724 if (!empty($message)) {
1725 // Then add it as well
1726 $stubMessage .= ' Message: ' . $message;
1729 // Debug instance is there?
1730 if (!is_null($this->getDebugInstance())) {
1731 // Output stub message
1732 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1735 trigger_error($stubMessage);
1741 * Outputs a debug backtrace and stops further script execution
1743 * @param $message An optional message to output
1744 * @param $doExit Whether exit the program (TRUE is default)
1747 public function debugBackTrace ($message = '', $doExit = TRUE) {
1748 // Sorry, there is no other way getting this nice backtrace
1749 if (!empty($message)) {
1751 printf('Message: %s<br />' . chr(10), $message);
1755 debug_print_backtrace();
1759 if ($doExit === TRUE) {
1765 * Creates an instance of a debugger instance
1767 * @param $className Name of the class (currently unsupported)
1768 * @return $debugInstance An instance of a debugger class
1770 public final static function createDebugInstance ($className) {
1771 // Is the instance set?
1772 if (!Registry::getRegistry()->instanceExists('debug')) {
1773 // Init debug instance
1774 $debugInstance = NULL;
1778 // Get a debugger instance
1779 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'));
1780 } catch (NullPointerException $e) {
1781 // Didn't work, no instance there
1782 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1785 // Empty string should be ignored and used for testing the middleware
1786 DebugMiddleware::getSelfInstance()->output('');
1788 // Set it in its own class. This will set it in the registry
1789 $debugInstance->setDebugInstance($debugInstance);
1791 // Get instance from registry
1792 $debugInstance = Registry::getRegistry()->getDebugInstance();
1796 return $debugInstance;
1800 * Simple output of a message with line-break
1802 * @param $message Message to output
1805 public function outputLine ($message) {
1807 print($message . PHP_EOL);
1811 * Outputs a debug message whether to debug instance (should be set!) or
1812 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1813 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1815 * @param $message Message we shall send out...
1816 * @param $doPrint Whether print or die here (default: print)
1817 * @paran $stripTags Whether to strip tags (default: FALSE)
1820 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1821 // Set debug instance to NULL
1822 $debugInstance = NULL;
1826 // Get debug instance
1827 $debugInstance = $this->getDebugInstance();
1828 } catch (NullPointerException $e) {
1829 // The debug instance is not set (yet)
1832 // Is the debug instance there?
1833 if (is_object($debugInstance)) {
1834 // Use debug output handler
1835 $debugInstance->output($message, $stripTags);
1837 if ($doPrint === FALSE) {
1838 // Die here if not printed
1842 // Are debug times enabled?
1843 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1845 $message = $this->getPrintableExecutionTime() . $message;
1849 if ($doPrint === TRUE) {
1851 $this->outputLine($message);
1860 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1862 * @param $str The string, what ever it is needs to be converted
1863 * @return $className Generated class name
1865 public function convertToClassName ($str) {
1869 // Convert all dashes in underscores
1870 $str = $this->convertDashesToUnderscores($str);
1872 // Now use that underscores to get classname parts for hungarian style
1873 foreach (explode('_', $str) as $strPart) {
1874 // Make the class name part lower case and first upper case
1875 $className .= ucfirst(strtolower($strPart));
1878 // Return class name
1883 * Converts dashes to underscores, e.g. useable for configuration entries
1885 * @param $str The string with maybe dashes inside
1886 * @return $str The converted string with no dashed, but underscores
1888 public final function convertDashesToUnderscores ($str) {
1890 $str = str_replace('-', '_', $str);
1892 // Return converted string
1897 * Marks up the code by adding e.g. line numbers
1899 * @param $phpCode Unmarked PHP code
1900 * @return $markedCode Marked PHP code
1902 public function markupCode ($phpCode) {
1907 $errorArray = error_get_last();
1909 // Init the code with error message
1910 if (is_array($errorArray)) {
1912 $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>',
1913 basename($errorArray['file']),
1914 $errorArray['line'],
1915 $errorArray['message'],
1920 // Add line number to the code
1921 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1923 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1925 htmlentities($code, ENT_QUOTES)
1934 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1935 * beatiful for web-based front-ends. If null is given a message id
1936 * null_timestamp will be resolved and returned.
1938 * @param $timestamp Timestamp to prepare (filter) for display
1939 * @return $readable A readable timestamp
1941 public function doFilterFormatTimestamp ($timestamp) {
1942 // Default value to return
1945 // Is the timestamp null?
1946 if (is_null($timestamp)) {
1947 // Get a message string
1948 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1950 switch ($this->getLanguageInstance()->getLanguageCode()) {
1951 case 'de': // German format is a bit different to default
1952 // Split the GMT stamp up
1953 $dateTime = explode(' ', $timestamp );
1954 $dateArray = explode('-', $dateTime[0]);
1955 $timeArray = explode(':', $dateTime[1]);
1957 // Construct the timestamp
1958 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1968 default: // Default is pass-through
1969 $readable = $timestamp;
1979 * Filter a given number into a localized number
1981 * @param $value The raw value from e.g. database
1982 * @return $localized Localized value
1984 public function doFilterFormatNumber ($value) {
1985 // Generate it from config and localize dependencies
1986 switch ($this->getLanguageInstance()->getLanguageCode()) {
1987 case 'de': // German format is a bit different to default
1988 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1991 default: // US, etc.
1992 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2001 * "Getter" for databse entry
2003 * @return $entry An array with database entries
2004 * @throws NullPointerException If the database result is not found
2005 * @throws InvalidDatabaseResultException If the database result is invalid
2007 protected final function getDatabaseEntry () {
2008 // Is there an instance?
2009 if (!$this->getResultInstance() instanceof SearchableResult) {
2010 // Throw an exception here
2011 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2015 $this->getResultInstance()->rewind();
2017 // Do we have an entry?
2018 if ($this->getResultInstance()->valid() === FALSE) {
2019 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2020 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2024 $this->getResultInstance()->next();
2027 $entry = $this->getResultInstance()->current();
2034 * Getter for field name
2036 * @param $fieldName Field name which we shall get
2037 * @return $fieldValue Field value from the user
2038 * @throws NullPointerException If the result instance is null
2040 public final function getField ($fieldName) {
2041 // Default field value
2044 // Get result instance
2045 $resultInstance = $this->getResultInstance();
2047 // Is this instance null?
2048 if (is_null($resultInstance)) {
2049 // Then the user instance is no longer valid (expired cookies?)
2050 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2053 // Get current array
2054 $fieldArray = $resultInstance->current();
2055 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2057 // Convert dashes to underscore
2058 $fieldName2 = $this->convertDashesToUnderscores($fieldName);
2060 // Does the field exist?
2061 if ($this->isFieldSet($fieldName)) {
2063 $fieldValue = $fieldArray[$fieldName2];
2064 } elseif (defined('DEVELOPER')) {
2065 // Missing field entry, may require debugging
2066 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2068 // Missing field entry, may require debugging
2069 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2077 * Checks if given field is set
2079 * @param $fieldName Field name to check
2080 * @return $isSet Whether the given field name is set
2081 * @throws NullPointerException If the result instance is null
2083 public function isFieldSet ($fieldName) {
2084 // Get result instance
2085 $resultInstance = $this->getResultInstance();
2087 // Is this instance null?
2088 if (is_null($resultInstance)) {
2089 // Then the user instance is no longer valid (expired cookies?)
2090 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2093 // Get current array
2094 $fieldArray = $resultInstance->current();
2095 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2097 // Convert dashes to underscore
2098 $fieldName = $this->convertDashesToUnderscores($fieldName);
2101 $isSet = isset($fieldArray[$fieldName]);
2108 * Flushs all pending updates to the database layer
2112 public function flushPendingUpdates () {
2113 // Get result instance
2114 $resultInstance = $this->getResultInstance();
2116 // Do we have data to update?
2117 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2118 // Get wrapper class name config entry
2119 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2121 // Create object instance
2122 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
2124 // Yes, then send the whole result to the database layer
2125 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2130 * Outputs a deprecation warning to the developer.
2132 * @param $message The message we shall output to the developer
2134 * @todo Write a logging mechanism for productive mode
2136 public function deprecationWarning ($message) {
2137 // Is developer mode active?
2138 if (defined('DEVELOPER')) {
2139 // Debug instance is there?
2140 if (!is_null($this->getDebugInstance())) {
2141 // Output stub message
2142 self::createDebugInstance(__CLASS__)->debugOutput($message);
2145 trigger_error($message . "<br />\n");
2149 // @TODO Finish this part!
2150 $this->partialStub('Developer mode inactive. Message:' . $message);
2155 * Checks whether the given PHP extension is loaded
2157 * @param $phpExtension The PHP extension we shall check
2158 * @return $isLoaded Whether the PHP extension is loaded
2160 public final function isPhpExtensionLoaded ($phpExtension) {
2162 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2169 * "Getter" as a time() replacement but with milliseconds. You should use this
2170 * method instead of the encapsulated getimeofday() function.
2172 * @return $milliTime Timestamp with milliseconds
2174 public function getMilliTime () {
2175 // Get the time of day as float
2176 $milliTime = gettimeofday(TRUE);
2183 * Idles (sleeps) for given milliseconds
2185 * @return $hasSlept Whether it goes fine
2187 public function idle ($milliSeconds) {
2188 // Sleep is fine by default
2191 // Idle so long with found function
2192 if (function_exists('time_sleep_until')) {
2193 // Get current time and add idle time
2194 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2196 // New PHP 5.1.0 function found, ignore errors
2197 $hasSlept = @time_sleep_until($sleepUntil);
2200 * My Sun station doesn't have that function even with latest PHP
2203 usleep($milliSeconds * 1000);
2210 * Converts a hexadecimal string, even with negative sign as first string to
2211 * a decimal number using BC functions.
2213 * This work is based on comment #86673 on php.net documentation page at:
2214 * <http://de.php.net/manual/en/function.dechex.php#86673>
2216 * @param $hex Hexadecimal string
2217 * @return $dec Decimal number
2219 protected function hex2dec ($hex) {
2220 // Convert to all lower-case
2221 $hex = strtolower($hex);
2223 // Detect sign (negative/positive numbers)
2225 if (substr($hex, 0, 1) == '-') {
2227 $hex = substr($hex, 1);
2230 // Decode the hexadecimal string into a decimal number
2232 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2233 $factor = self::$hexdec[substr($hex, $i, 1)];
2234 $dec = bcadd($dec, bcmul($factor, $e));
2237 // Return the decimal number
2238 return $sign . $dec;
2242 * Converts even very large decimal numbers, also signed, to a hexadecimal
2245 * This work is based on comment #97756 on php.net documentation page at:
2246 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2248 * @param $dec Decimal number, even with negative sign
2249 * @param $maxLength Optional maximum length of the string
2250 * @return $hex Hexadecimal string
2252 protected function dec2hex ($dec, $maxLength = 0) {
2253 // maxLength can be zero or devideable by 2
2254 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2256 // Detect sign (negative/positive numbers)
2263 // Encode the decimal number into a hexadecimal string
2266 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2268 } while ($dec >= 1);
2271 * Leading zeros are required for hex-decimal "numbers". In some
2272 * situations more leading zeros are wanted, so check for both
2275 if ($maxLength > 0) {
2276 // Prepend more zeros
2277 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2278 } elseif ((strlen($hex) % 2) != 0) {
2279 // Only make string's length dividable by 2
2283 // Return the hexadecimal string
2284 return $sign . $hex;
2288 * Converts a ASCII string (0 to 255) into a decimal number.
2290 * @param $asc The ASCII string to be converted
2291 * @return $dec Decimal number
2293 protected function asc2dec ($asc) {
2294 // Convert it into a hexadecimal number
2295 $hex = bin2hex($asc);
2297 // And back into a decimal number
2298 $dec = $this->hex2dec($hex);
2305 * Converts a decimal number into an ASCII string.
2307 * @param $dec Decimal number
2308 * @return $asc An ASCII string
2310 protected function dec2asc ($dec) {
2311 // First convert the number into a hexadecimal string
2312 $hex = $this->dec2hex($dec);
2314 // Then convert it into the ASCII string
2315 $asc = $this->hex2asc($hex);
2322 * Converts a hexadecimal number into an ASCII string. Negative numbers
2325 * @param $hex Hexadecimal string
2326 * @return $asc An ASCII string
2328 protected function hex2asc ($hex) {
2329 // Check for length, it must be devideable by 2
2330 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2331 assert((strlen($hex) % 2) == 0);
2335 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2336 // Get the decimal number of the chunk
2337 $part = hexdec(substr($hex, $idx, 2));
2339 // Add it to the final string
2343 // Return the final string
2348 * Checks whether the given encoded data was encoded with Base64
2350 * @param $encodedData Encoded data we shall check
2351 * @return $isBase64 Whether the encoded data is Base64
2353 protected function isBase64Encoded ($encodedData) {
2355 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2362 * "Getter" to get response/request type from analysis of the system.
2364 * @return $responseType Analyzed response type
2366 protected static function getResponseTypeFromSystem () {
2367 // Default is console
2368 $responseType = 'console';
2370 // Is 'HTTP_HOST' set?
2371 if (isset($_SERVER['HTTP_HOST'])) {
2373 * Then it is a HTML response/request as RSS and so on may be
2374 * transfered over HTTP as well.
2376 $responseType = 'html';
2380 return $responseType;
2384 * Gets a cache key from Criteria instance
2386 * @param $criteriaInstance An instance of a Criteria class
2387 * @param $onlyKeys Only use these keys for a cache key
2388 * @return $cacheKey A cache key suitable for lookup/storage purposes
2390 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2392 $cacheKey = sprintf('%s@%s',
2393 $this->__toString(),
2394 $criteriaInstance->getCacheKey($onlyKeys)
2398 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2403 * Getter for startup time in miliseconds
2405 * @return $startupTime Startup time in miliseconds
2407 protected function getStartupTime () {
2408 return self::$startupTime;
2412 * "Getter" for a printable currently execution time in nice braces
2414 * @return $executionTime Current execution time in nice braces
2416 protected function getPrintableExecutionTime () {
2417 // Caculate the execution time
2418 $executionTime = microtime(TRUE) - $this->getStartupTime();
2420 // Pack it in nice braces
2421 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2424 return $executionTime;
2428 * Hashes a given string with a simple but stronger hash function (no salt)
2429 * and hex-encode it.
2431 * @param $str The string to be hashed
2432 * @return $hash The hash from string $str
2434 public static final function hash ($str) {
2435 // Hash given string with (better secure) hasher
2436 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2443 * "Getter" for length of hash() output. This will be "cached" to speed up
2446 * @return $length Length of hash() output
2448 public static final function getHashLength () {
2450 if (is_null(self::$hashLength)) {
2451 // No, then hash a string and save its length.
2452 self::$hashLength = strlen(self::hash('abc123'));
2456 return self::$hashLength;
2460 * Checks whether the given number is really a number (only chars 0-9).
2462 * @param $num A string consisting only chars between 0 and 9
2463 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2464 * @param $assertMismatch Whether to assert mismatches
2465 * @return $ret The (hopefully) secured numbered value
2467 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2468 // Filter all numbers out
2469 $ret = preg_replace('/[^0123456789]/', '', $num);
2472 if ($castValue === TRUE) {
2473 // Cast to biggest numeric type
2474 $ret = (double) $ret;
2477 // Assert only if requested
2478 if ($assertMismatch === TRUE) {
2479 // Has the whole value changed?
2480 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2488 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2490 * @param $num A string consisting only chars between 0 and 9
2491 * @param $assertMismatch Whether to assert mismatches
2492 * @return $ret The (hopefully) secured hext-numbered value
2494 public function hexval ($num, $assertMismatch = FALSE) {
2495 // Filter all numbers out
2496 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2498 // Assert only if requested
2499 if ($assertMismatch === TRUE) {
2500 // Has the whole value changed?
2501 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2509 * Checks whether start/end marker are set
2511 * @param $data Data to be checked
2512 * @return $isset Whether start/end marker are set
2514 public final function ifStartEndMarkersSet ($data) {
2516 $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));
2518 // ... and return it
2523 * Determines if an element is set in the generic array
2525 * @param $keyGroup Main group for the key
2526 * @param $subGroup Sub group for the key
2527 * @param $key Key to check
2528 * @param $element Element to check
2529 * @return $isset Whether the given key is set
2531 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2533 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2536 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2542 * Determines if a key is set in the generic array
2544 * @param $keyGroup Main group for the key
2545 * @param $subGroup Sub group for the key
2546 * @param $key Key to check
2547 * @return $isset Whether the given key is set
2549 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2551 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2554 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2562 * Determines if a group is set in the generic array
2564 * @param $keyGroup Main group
2565 * @param $subGroup Sub group
2566 * @return $isset Whether the given group is set
2568 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2570 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2573 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2580 * Getter for sub key group
2582 * @param $keyGroup Main key group
2583 * @param $subGroup Sub key group
2584 * @return $array An array with all array elements
2586 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2588 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2589 // No, then abort here
2590 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2595 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2598 return $this->genericArray[$keyGroup][$subGroup];
2602 * Unsets a given key in generic array
2604 * @param $keyGroup Main group for the key
2605 * @param $subGroup Sub group for the key
2606 * @param $key Key to unset
2609 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2611 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2614 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2618 * Unsets a given element in generic array
2620 * @param $keyGroup Main group for the key
2621 * @param $subGroup Sub group for the key
2622 * @param $key Key to unset
2623 * @param $element Element to unset
2626 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2628 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2631 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2635 * Append a string to a given generic array key
2637 * @param $keyGroup Main group for the key
2638 * @param $subGroup Sub group for the key
2639 * @param $key Key to unset
2640 * @param $value Value to add/append
2643 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2645 //* 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);
2647 // Is it already there?
2648 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2650 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2653 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2658 * Append a string to a given generic array element
2660 * @param $keyGroup Main group for the key
2661 * @param $subGroup Sub group for the key
2662 * @param $key Key to unset
2663 * @param $element Element to check
2664 * @param $value Value to add/append
2667 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2669 //* 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);
2671 // Is it already there?
2672 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2674 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2677 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2682 * Initializes given generic array group
2684 * @param $keyGroup Main group for the key
2685 * @param $subGroup Sub group for the key
2686 * @param $key Key to use
2687 * @param $forceInit Optionally force initialization
2690 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2692 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2694 // Is it already set?
2695 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2696 // Already initialized
2697 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2702 $this->genericArray[$keyGroup][$subGroup] = array();
2706 * Initializes given generic array key
2708 * @param $keyGroup Main group for the key
2709 * @param $subGroup Sub group for the key
2710 * @param $key Key to use
2711 * @param $forceInit Optionally force initialization
2714 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2716 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2718 // Is it already set?
2719 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2720 // Already initialized
2721 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2726 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2730 * Initializes given generic array element
2732 * @param $keyGroup Main group for the key
2733 * @param $subGroup Sub group for the key
2734 * @param $key Key to use
2735 * @param $element Element to use
2736 * @param $forceInit Optionally force initialization
2739 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2741 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2743 // Is it already set?
2744 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2745 // Already initialized
2746 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2751 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2755 * Pushes an element to a generic key
2757 * @param $keyGroup Main group for the key
2758 * @param $subGroup Sub group for the key
2759 * @param $key Key to use
2760 * @param $value Value to add/append
2761 * @return $count Number of array elements
2763 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2765 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2768 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2770 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2774 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2777 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2778 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2783 * Pushes an element to a generic array element
2785 * @param $keyGroup Main group for the key
2786 * @param $subGroup Sub group for the key
2787 * @param $key Key to use
2788 * @param $element Element to check
2789 * @param $value Value to add/append
2790 * @return $count Number of array elements
2792 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2794 //* 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));
2797 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2799 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2803 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2806 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2807 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2812 * Pops an element from a generic group
2814 * @param $keyGroup Main group for the key
2815 * @param $subGroup Sub group for the key
2816 * @param $key Key to unset
2817 * @return $value Last "popped" value
2819 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2821 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2824 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2826 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2831 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2834 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2835 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2840 * Shifts an element from a generic group
2842 * @param $keyGroup Main group for the key
2843 * @param $subGroup Sub group for the key
2844 * @param $key Key to unset
2845 * @return $value Last "popped" value
2847 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2849 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2852 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2854 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2859 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2862 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2863 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2868 * Count generic array group
2870 * @param $keyGroup Main group for the key
2871 * @return $count Count of given group
2873 protected final function countGenericArray ($keyGroup) {
2875 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2878 if (!isset($this->genericArray[$keyGroup])) {
2880 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2885 $count = count($this->genericArray[$keyGroup]);
2888 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2895 * Count generic array sub group
2897 * @param $keyGroup Main group for the key
2898 * @param $subGroup Sub group for the key
2899 * @return $count Count of given group
2901 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2903 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2906 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2908 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2913 $count = count($this->genericArray[$keyGroup][$subGroup]);
2916 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2923 * Count generic array elements
2925 * @param $keyGroup Main group for the key
2926 * @param $subGroup Sub group for the key
2927 * @para $key Key to count
2928 * @return $count Count of given key
2930 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2932 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2935 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2937 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2939 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2941 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2946 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2949 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2956 * Getter for whole generic group array
2958 * @param $keyGroup Key group to get
2959 * @return $array Whole generic array group
2961 protected final function getGenericArray ($keyGroup) {
2963 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2966 if (!isset($this->genericArray[$keyGroup])) {
2968 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2973 return $this->genericArray[$keyGroup];
2977 * Setter for generic array key
2979 * @param $keyGroup Key group to get
2980 * @param $subGroup Sub group for the key
2981 * @param $key Key to unset
2982 * @param $value Mixed value from generic array element
2985 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2987 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2990 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2994 * Getter for generic array key
2996 * @param $keyGroup Key group to get
2997 * @param $subGroup Sub group for the key
2998 * @param $key Key to unset
2999 * @return $value Mixed value from generic array element
3001 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3003 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3006 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3008 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3013 return $this->genericArray[$keyGroup][$subGroup][$key];
3017 * Sets a value in given generic array key/element
3019 * @param $keyGroup Main group for the key
3020 * @param $subGroup Sub group for the key
3021 * @param $key Key to set
3022 * @param $element Element to set
3023 * @param $value Value to set
3026 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3028 //* 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));
3031 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3035 * Getter for generic array element
3037 * @param $keyGroup Key group to get
3038 * @param $subGroup Sub group for the key
3039 * @param $key Key to look for
3040 * @param $element Element to look for
3041 * @return $value Mixed value from generic array element
3043 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3045 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3048 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3050 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3055 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3059 * Checks if a given sub group is valid (array)
3061 * @param $keyGroup Key group to get
3062 * @param $subGroup Sub group for the key
3063 * @return $isValid Whether given sub group is valid
3065 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3067 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3070 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3077 * Checks if a given key is valid (array)
3079 * @param $keyGroup Key group to get
3080 * @param $subGroup Sub group for the key
3081 * @param $key Key to check
3082 * @return $isValid Whether given sub group is valid
3084 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3086 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3089 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3096 * Initializes the web output instance
3100 protected function initWebOutputInstance () {
3101 // Get application instance
3102 $applicationInstance = Registry::getRegistry()->getInstance('app');
3104 // Is this a response instance?
3105 if ($this instanceof Responseable) {
3106 // Then set it in application instance
3107 $applicationInstance->setResponseInstance($this);
3110 // Init web output instance
3111 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3114 $this->setWebOutputInstance($outputInstance);
3118 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3120 * @param $boolean Boolean value
3121 * @return $translated Translated boolean value
3123 public static final function translateBooleanToYesNo ($boolean) {
3124 // Make sure it is really boolean
3125 assert(is_bool($boolean));
3128 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3130 // ... and return it
3135 * Encodes raw data (almost any type) by "serializing" it and then pack it
3136 * into a "binary format".
3138 * @param $rawData Raw data (almost any type)
3139 * @return $encoded Encoded data
3141 protected function encodeData ($rawData) {
3142 // Make sure no objects or resources pass through
3143 assert(!is_object($rawData));
3144 assert(!is_resource($rawData));
3146 // First "serialize" it (json_encode() is faster than serialize())
3147 $encoded = $this->packString(json_encode($rawData));
3154 * Pack a string into a "binary format". Please execuse me that this is
3155 * widely undocumented. :-(
3157 * @param $str Unpacked string
3158 * @return $packed Packed string
3159 * @todo Improve documentation
3161 protected function packString ($str) {
3163 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3165 // First compress the string (gzcompress is okay)
3166 $str = gzcompress($str);
3171 // And start the "encoding" loop
3172 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3174 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3175 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3177 if (($idx + $i) <= strlen($str)) {
3178 $ord = ord(substr($str, ($idx + $i), 1));
3180 $add = $ord * pow(256, $factor);
3184 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3188 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3189 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3191 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3192 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3198 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');