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 = FALSE;
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);
420 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
424 * Destructor for all classes
428 public function __destruct () {
429 // Flush any updated entries to the database
430 $this->flushPendingUpdates();
432 // Is this object already destroyed?
433 if ($this->__toString() != 'DestructedObject') {
434 // Destroy all informations about this class but keep some text about it alive
435 $this->setRealClass('DestructedObject');
436 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
437 // Already destructed object
438 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
443 // Do not call this twice
444 trigger_error(__METHOD__ . ': Called twice.');
450 * The __call() method where all non-implemented methods end up
452 * @param $methodName Name of the missing method
453 * @args $args Arguments passed to the method
456 public final function __call ($methodName, $args) {
457 return self::__callStatic($methodName, $args);
461 * The __callStatic() method where all non-implemented static methods end up
463 * @param $methodName Name of the missing method
464 * @args $args Arguments passed to the method
467 public static final function __callStatic ($methodName, $args) {
468 // Init argument string
471 // Is it empty or an array?
474 $argsString = 'NULL';
475 } elseif (is_array($args)) {
476 // Some arguments are there
477 foreach ($args as $arg) {
478 // Add the value itself if not array. This prevents 'array to string conversion' message
479 if (is_array($arg)) {
480 $argsString .= 'Array';
485 // Add data about the argument
486 $argsString .= ' (' . gettype($arg);
488 if (is_string($arg)) {
489 // Add length for strings
490 $argsString .= ', ' . strlen($arg);
491 } elseif (is_array($arg)) {
492 // .. or size if array
493 $argsString .= ', ' . count($arg);
494 } elseif ($arg === TRUE) {
495 // ... is boolean 'TRUE'
496 $argsString .= ', TRUE';
497 } elseif ($arg === FALSE) {
498 // ... is boolean 'FALSE'
499 $argsString .= ', FALSE';
503 $argsString .= '), ';
507 if (substr($argsString, -2, 1) == ',') {
508 $argsString = substr($argsString, 0, -2);
511 // Invalid arguments!
512 $argsString = '!INVALID:' . gettype($args) . '!';
515 // Output stub message
516 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
517 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
527 * Getter for $realClass
529 * @return $realClass The name of the real class (not BaseFrameworkSystem)
531 public function __toString () {
532 return $this->realClass;
536 * Magic method to catch setting of missing but set class fields/attributes
538 * @param $name Name of the field/attribute
539 * @param $value Value to store
542 public final function __set ($name, $value) {
543 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
546 print_r($value, TRUE)
551 * Magic method to catch getting of missing fields/attributes
553 * @param $name Name of the field/attribute
556 public final function __get ($name) {
557 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
563 * Magic method to catch unsetting of missing fields/attributes
565 * @param $name Name of the field/attribute
568 public final function __unset ($name) {
569 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
575 * Magic method to catch object serialization
577 * @return $unsupported Unsupported method
578 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
580 public final function __sleep () {
581 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
585 * Magic method to catch object deserialization
587 * @return $unsupported Unsupported method
588 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
590 public final function __wakeup () {
591 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
595 * Magic method to catch calls when an object instance is called
597 * @return $unsupported Unsupported method
598 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
600 public final function __invoke () {
601 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
605 * Setter for the real class name
607 * @param $realClass Class name (string)
610 public final function setRealClass ($realClass) {
612 $this->realClass = (string) $realClass;
616 * Setter for database result instance
618 * @param $resultInstance An instance of a database result class
620 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
622 protected final function setResultInstance (SearchableResult $resultInstance) {
623 $this->resultInstance = $resultInstance;
627 * Getter for database result instance
629 * @return $resultInstance An instance of a database result class
631 public final function getResultInstance () {
632 return $this->resultInstance;
636 * Setter for template engine instances
638 * @param $templateInstance An instance of a template engine class
641 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
642 $this->templateInstance = $templateInstance;
646 * Getter for template engine instances
648 * @return $templateInstance An instance of a template engine class
650 protected final function getTemplateInstance () {
651 return $this->templateInstance;
655 * Setter for search instance
657 * @param $searchInstance Searchable criteria instance
660 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
661 $this->searchInstance = $searchInstance;
665 * Getter for search instance
667 * @return $searchInstance Searchable criteria instance
669 public final function getSearchInstance () {
670 return $this->searchInstance;
674 * Setter for update instance
676 * @param $updateInstance Searchable criteria instance
679 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
680 $this->updateInstance = $updateInstance;
684 * Getter for update instance
686 * @return $updateInstance Updateable criteria instance
688 public final function getUpdateInstance () {
689 return $this->updateInstance;
693 * Setter for resolver instance
695 * @param $resolverInstance Instance of a command resolver class
698 public final function setResolverInstance (Resolver $resolverInstance) {
699 $this->resolverInstance = $resolverInstance;
703 * Getter for resolver instance
705 * @return $resolverInstance Instance of a command resolver class
707 public final function getResolverInstance () {
708 return $this->resolverInstance;
712 * Setter for language instance
714 * @param $configInstance The configuration instance which shall
715 * be FrameworkConfiguration
718 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
719 Registry::getRegistry()->addInstance('config', $configInstance);
723 * Getter for configuration instance
725 * @return $configInstance Configuration instance
727 public final function getConfigInstance () {
728 $configInstance = Registry::getRegistry()->getInstance('config');
729 return $configInstance;
733 * Setter for debug instance
735 * @param $debugInstance The instance for debug output class
738 public final function setDebugInstance (DebugMiddleware $debugInstance) {
739 Registry::getRegistry()->addInstance('debug', $debugInstance);
743 * Getter for debug instance
745 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
747 public final function getDebugInstance () {
748 // Get debug instance
749 $debugInstance = Registry::getRegistry()->getInstance('debug');
752 return $debugInstance;
756 * Setter for web output instance
758 * @param $webInstance The instance for web output class
761 public final function setWebOutputInstance (OutputStreamer $webInstance) {
762 Registry::getRegistry()->addInstance('web_output', $webInstance);
766 * Getter for web output instance
768 * @return $webOutputInstance - Instance to class WebOutput
770 public final function getWebOutputInstance () {
771 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
772 return $webOutputInstance;
776 * Setter for database instance
778 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
781 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
782 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
786 * Getter for database layer
788 * @return $databaseInstance The database layer instance
790 public final function getDatabaseInstance () {
792 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
795 return $databaseInstance;
799 * Setter for compressor channel
801 * @param $compressorInstance An instance of CompressorChannel
804 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
805 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
809 * Getter for compressor channel
811 * @return $compressorInstance The compressor channel
813 public final function getCompressorChannel () {
814 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
815 return $compressorInstance;
819 * Protected getter for a manageable application helper class
821 * @return $applicationInstance An instance of a manageable application helper class
823 protected final function getApplicationInstance () {
824 $applicationInstance = Registry::getRegistry()->getInstance('application');
825 return $applicationInstance;
829 * Setter for a manageable application helper class
831 * @param $applicationInstance An instance of a manageable application helper class
834 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
835 Registry::getRegistry()->addInstance('application', $applicationInstance);
839 * Setter for request instance
841 * @param $requestInstance An instance of a Requestable class
844 public final function setRequestInstance (Requestable $requestInstance) {
845 $this->requestInstance = $requestInstance;
849 * Getter for request instance
851 * @return $requestInstance An instance of a Requestable class
853 public final function getRequestInstance () {
854 return $this->requestInstance;
858 * Setter for response instance
860 * @param $responseInstance An instance of a Responseable class
863 public final function setResponseInstance (Responseable $responseInstance) {
864 $this->responseInstance = $responseInstance;
868 * Getter for response instance
870 * @return $responseInstance An instance of a Responseable class
872 public final function getResponseInstance () {
873 return $this->responseInstance;
877 * Private getter for language instance
879 * @return $langInstance An instance to the language sub-system
881 protected final function getLanguageInstance () {
882 $langInstance = Registry::getRegistry()->getInstance('language');
883 return $langInstance;
887 * Setter for language instance
889 * @param $langInstance An instance to the language sub-system
891 * @see LanguageSystem
893 public final function setLanguageInstance (ManageableLanguage $langInstance) {
894 Registry::getRegistry()->addInstance('language', $langInstance);
898 * Private getter for file IO instance
900 * @return $fileIoInstance An instance to the file I/O sub-system
902 protected final function getFileIoInstance () {
903 return $this->fileIoInstance;
907 * Setter for file I/O instance
909 * @param $fileIoInstance An instance to the file I/O sub-system
912 public final function setFileIoInstance (IoHandler $fileIoInstance) {
913 $this->fileIoInstance = $fileIoInstance;
917 * Protected setter for user instance
919 * @param $userInstance An instance of a user class
922 protected final function setUserInstance (ManageableAccount $userInstance) {
923 $this->userInstance = $userInstance;
927 * Getter for user instance
929 * @return $userInstance An instance of a user class
931 public final function getUserInstance () {
932 return $this->userInstance;
936 * Setter for controller instance (this surely breaks a bit the MVC patterm)
938 * @param $controllerInstance An instance of the controller
941 public final function setControllerInstance (Controller $controllerInstance) {
942 $this->controllerInstance = $controllerInstance;
946 * Getter for controller instance (this surely breaks a bit the MVC patterm)
948 * @return $controllerInstance An instance of the controller
950 public final function getControllerInstance () {
951 return $this->controllerInstance;
955 * Setter for RNG instance
957 * @param $rngInstance An instance of a random number generator (RNG)
960 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
961 $this->rngInstance = $rngInstance;
965 * Getter for RNG instance
967 * @return $rngInstance An instance of a random number generator (RNG)
969 public final function getRngInstance () {
970 return $this->rngInstance;
974 * Setter for Cryptable instance
976 * @param $cryptoInstance An instance of a Cryptable class
979 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
980 $this->cryptoInstance = $cryptoInstance;
984 * Getter for Cryptable instance
986 * @return $cryptoInstance An instance of a Cryptable class
988 public final function getCryptoInstance () {
989 return $this->cryptoInstance;
993 * Setter for the list instance
995 * @param $listInstance A list of Listable
998 protected final function setListInstance (Listable $listInstance) {
999 $this->listInstance = $listInstance;
1003 * Getter for the list instance
1005 * @return $listInstance A list of Listable
1007 protected final function getListInstance () {
1008 return $this->listInstance;
1012 * Setter for the menu instance
1014 * @param $menuInstance A RenderableMenu instance
1017 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1018 $this->menuInstance = $menuInstance;
1022 * Getter for the menu instance
1024 * @return $menuInstance A RenderableMenu instance
1026 protected final function getMenuInstance () {
1027 return $this->menuInstance;
1031 * Setter for image instance
1033 * @param $imageInstance An instance of an image
1036 public final function setImageInstance (BaseImage $imageInstance) {
1037 $this->imageInstance = $imageInstance;
1041 * Getter for image instance
1043 * @return $imageInstance An instance of an image
1045 public final function getImageInstance () {
1046 return $this->imageInstance;
1050 * Setter for stacker instance
1052 * @param $stackInstance An instance of an stacker
1055 public final function setStackInstance (Stackable $stackInstance) {
1056 $this->stackInstance = $stackInstance;
1060 * Getter for stacker instance
1062 * @return $stackInstance An instance of an stacker
1064 public final function getStackInstance () {
1065 return $this->stackInstance;
1069 * Setter for compressor instance
1071 * @param $compressorInstance An instance of an compressor
1074 public final function setCompressorInstance (Compressor $compressorInstance) {
1075 $this->compressorInstance = $compressorInstance;
1079 * Getter for compressor instance
1081 * @return $compressorInstance An instance of an compressor
1083 public final function getCompressorInstance () {
1084 return $this->compressorInstance;
1088 * Setter for Parseable instance
1090 * @param $parserInstance An instance of an Parseable
1093 public final function setParserInstance (Parseable $parserInstance) {
1094 $this->parserInstance = $parserInstance;
1098 * Getter for Parseable instance
1100 * @return $parserInstance An instance of an Parseable
1102 public final function getParserInstance () {
1103 return $this->parserInstance;
1107 * Setter for HandleableProtocol instance
1109 * @param $protocolInstance An instance of an HandleableProtocol
1112 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1113 $this->protocolInstance = $protocolInstance;
1117 * Getter for HandleableProtocol instance
1119 * @return $protocolInstance An instance of an HandleableProtocol
1121 public final function getProtocolInstance () {
1122 return $this->protocolInstance;
1126 * Setter for DatabaseWrapper instance
1128 * @param $wrapperInstance An instance of an DatabaseWrapper
1131 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1132 $this->wrapperInstance = $wrapperInstance;
1136 * Getter for DatabaseWrapper instance
1138 * @return $wrapperInstance An instance of an DatabaseWrapper
1140 public final function getWrapperInstance () {
1141 return $this->wrapperInstance;
1145 * Setter for socket resource
1147 * @param $socketResource A valid socket resource
1150 public final function setSocketResource ($socketResource) {
1151 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1152 $this->socketResource = $socketResource;
1156 * Getter for socket resource
1158 * @return $socketResource A valid socket resource
1160 public final function getSocketResource () {
1161 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1162 return $this->socketResource;
1166 * Setter for regular expression
1168 * @param $regularExpression A valid regular expression
1171 public final function setRegularExpression ($regularExpression) {
1172 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1173 $this->regularExpression = $regularExpression;
1177 * Getter for regular expression
1179 * @return $regularExpression A valid regular expression
1181 public final function getRegularExpression () {
1182 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1183 return $this->regularExpression;
1187 * Setter for helper instance
1189 * @param $helperInstance An instance of a helper class
1192 protected final function setHelperInstance (Helper $helperInstance) {
1193 $this->helperInstance = $helperInstance;
1197 * Getter for helper instance
1199 * @return $helperInstance An instance of a helper class
1201 public final function getHelperInstance () {
1202 return $this->helperInstance;
1206 * Setter for a Source instance
1208 * @param $sourceInstance An instance of a Source class
1211 protected final function setSourceInstance (Source $sourceInstance) {
1212 $this->sourceInstance = $sourceInstance;
1216 * Getter for a Source instance
1218 * @return $sourceInstance An instance of a Source class
1220 protected final function getSourceInstance () {
1221 return $this->sourceInstance;
1225 * Setter for a UrlSource instance
1227 * @param $sourceInstance An instance of a UrlSource class
1230 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1231 $this->urlSourceInstance = $urlSourceInstance;
1235 * Getter for a UrlSource instance
1237 * @return $urlSourceInstance An instance of a UrlSource class
1239 protected final function getUrlSourceInstance () {
1240 return $this->urlSourceInstance;
1244 * Getter for a InputStream instance
1246 * @param $inputStreamInstance The InputStream instance
1248 protected final function getInputStreamInstance () {
1249 return $this->inputStreamInstance;
1253 * Setter for a InputStream instance
1255 * @param $inputStreamInstance The InputStream instance
1258 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1259 $this->inputStreamInstance = $inputStreamInstance;
1263 * Getter for a OutputStream instance
1265 * @param $outputStreamInstance The OutputStream instance
1267 protected final function getOutputStreamInstance () {
1268 return $this->outputStreamInstance;
1272 * Setter for a OutputStream instance
1274 * @param $outputStreamInstance The OutputStream instance
1277 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1278 $this->outputStreamInstance = $outputStreamInstance;
1282 * Setter for handler instance
1284 * @param $handlerInstance An instance of a Handleable class
1287 protected final function setHandlerInstance (Handleable $handlerInstance) {
1288 $this->handlerInstance = $handlerInstance;
1292 * Getter for handler instance
1294 * @return $handlerInstance A Networkable instance
1296 protected final function getHandlerInstance () {
1297 return $this->handlerInstance;
1301 * Setter for visitor instance
1303 * @param $visitorInstance A Visitor instance
1306 protected final function setVisitorInstance (Visitor $visitorInstance) {
1307 $this->visitorInstance = $visitorInstance;
1311 * Getter for visitor instance
1313 * @return $visitorInstance A Visitor instance
1315 protected final function getVisitorInstance () {
1316 return $this->visitorInstance;
1320 * Setter for DHT instance
1322 * @param $dhtInstance A Distributable instance
1325 protected final function setDhtInstance (Distributable $dhtInstance) {
1326 $this->dhtInstance = $dhtInstance;
1330 * Getter for DHT instance
1332 * @return $dhtInstance A Distributable instance
1334 protected final function getDhtInstance () {
1335 return $this->dhtInstance;
1339 * Setter for raw package Data
1341 * @param $packageData Raw package Data
1344 public final function setPackageData (array $packageData) {
1345 $this->packageData = $packageData;
1349 * Getter for raw package Data
1351 * @return $packageData Raw package Data
1353 public function getPackageData () {
1354 return $this->packageData;
1359 * Setter for Iterator instance
1361 * @param $iteratorInstance An instance of an Iterator
1364 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1365 $this->iteratorInstance = $iteratorInstance;
1369 * Getter for Iterator instance
1371 * @return $iteratorInstance An instance of an Iterator
1373 public final function getIteratorInstance () {
1374 return $this->iteratorInstance;
1378 * Setter for FilePointer instance
1380 * @param $pointerInstance An instance of an FilePointer class
1383 protected final function setPointerInstance (FilePointer $pointerInstance) {
1384 $this->pointerInstance = $pointerInstance;
1388 * Getter for FilePointer instance
1390 * @return $pointerInstance An instance of an FilePointer class
1392 public final function getPointerInstance () {
1393 return $this->pointerInstance;
1397 * Unsets pointer instance which triggers a call of __destruct() if the
1398 * instance is still there. This is surely not fatal on already "closed"
1399 * file pointer instances.
1401 * I don't want to mess around with above setter by giving it a default
1402 * value NULL as setter should always explicitly only set (existing) object
1403 * instances and NULL is NULL.
1407 protected final function unsetPointerInstance () {
1408 // Simply it to NULL
1409 $this->pointerInstance = NULL;
1413 * Setter for Indexable instance
1415 * @param $indexInstance An instance of an Indexable class
1418 protected final function setIndexInstance (Indexable $indexInstance) {
1419 $this->indexInstance = $indexInstance;
1423 * Getter for Indexable instance
1425 * @return $indexInstance An instance of an Indexable class
1427 public final function getIndexInstance () {
1428 return $this->indexInstance;
1432 * Setter for Block instance
1434 * @param $blockInstance An instance of an Block class
1437 protected final function setBlockInstance (Block $blockInstance) {
1438 $this->blockInstance = $blockInstance;
1442 * Getter for Block instance
1444 * @return $blockInstance An instance of an Block class
1446 public final function getBlockInstance () {
1447 return $this->blockInstance;
1451 * Setter for Minable instance
1453 * @param $minableInstance A Minable instance
1456 protected final function setMinableInstance (Minable $minableInstance) {
1457 $this->minableInstance = $minableInstance;
1461 * Getter for minable instance
1463 * @return $minableInstance A Minable instance
1465 protected final function getMinableInstance () {
1466 return $this->minableInstance;
1470 * Setter for FrameworkDirectory instance
1472 * @param $directoryInstance A FrameworkDirectoryPointer instance
1475 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1476 $this->directoryInstance = $directoryInstance;
1480 * Getter for FrameworkDirectory instance
1482 * @return $directoryInstance A FrameworkDirectory instance
1484 protected final function getDirectoryInstance () {
1485 return $this->directoryInstance;
1489 * Setter for listener instance
1491 * @param $listenerInstance A Listenable instance
1494 protected final function setListenerInstance (Listenable $listenerInstance) {
1495 $this->listenerInstance = $listenerInstance;
1499 * Getter for listener instance
1501 * @return $listenerInstance A Listenable instance
1503 protected final function getListenerInstance () {
1504 return $this->listenerInstance;
1508 * Setter for command name
1510 * @param $commandName Last validated command name
1513 protected final function setCommandName ($commandName) {
1514 $this->commandName = $commandName;
1518 * Getter for command name
1520 * @return $commandName Last validated command name
1522 protected final function getCommandName () {
1523 return $this->commandName;
1527 * Setter for controller name
1529 * @param $controllerName Last validated controller name
1532 protected final function setControllerName ($controllerName) {
1533 $this->controllerName = $controllerName;
1537 * Getter for controller name
1539 * @return $controllerName Last validated controller name
1541 protected final function getControllerName () {
1542 return $this->controllerName;
1546 * Checks whether an object equals this object. You should overwrite this
1547 * method to implement own equality checks
1549 * @param $objectInstance An instance of a FrameworkInterface object
1550 * @return $equals Whether both objects equals
1552 public function equals (FrameworkInterface $objectInstance) {
1555 $this->__toString() == $objectInstance->__toString()
1557 $this->hashCode() == $objectInstance->hashCode()
1560 // Return the result
1565 * Generates a generic hash code of this class. You should really overwrite
1566 * this method with your own hash code generator code. But keep KISS in mind.
1568 * @return $hashCode A generic hash code respresenting this whole class
1570 public function hashCode () {
1572 return crc32($this->__toString());
1576 * Formats computer generated price values into human-understandable formats
1577 * with thousand and decimal separators.
1579 * @param $value The in computer format value for a price
1580 * @param $currency The currency symbol (use HTML-valid characters!)
1581 * @param $decNum Number of decimals after commata
1582 * @return $price The for the current language formated price string
1583 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1584 * thousands separator
1587 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1588 // Are all required attriutes set?
1589 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1590 // Throw an exception
1591 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1595 $value = (float) $value;
1597 // Reformat the US number
1598 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1600 // Return as string...
1605 * Appends a trailing slash to a string
1607 * @param $str A string (maybe) without trailing slash
1608 * @return $str A string with an auto-appended trailing slash
1610 public final function addMissingTrailingSlash ($str) {
1611 // Is there a trailing slash?
1612 if (substr($str, -1, 1) != '/') {
1616 // Return string with trailing slash
1621 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1622 * application helper instance (ApplicationHelper by default).
1624 * @param $applicationInstance An application helper instance or
1625 * null if we shall use the default
1626 * @return $templateInstance The template engine instance
1627 * @throws NullPointerException If the discovered application
1628 * instance is still null
1630 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1631 // Is the application instance set?
1632 if (is_null($applicationInstance)) {
1633 // Get the current instance
1634 $applicationInstance = $this->getApplicationInstance();
1637 if (is_null($applicationInstance)) {
1638 // Thrown an exception
1639 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1643 // Initialize the template engine
1644 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1646 // Return the prepared instance
1647 return $templateInstance;
1651 * Debugs this instance by putting out it's full content
1653 * @param $message Optional message to show in debug output
1656 public final function debugInstance ($message = '') {
1657 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1658 restore_error_handler();
1663 // Is a message set?
1664 if (!empty($message)) {
1665 // Construct message
1666 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1669 // Generate the output
1670 $content .= sprintf('<pre>%s</pre>',
1673 print_r($this, TRUE)
1679 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>',
1680 $this->__toString(),
1682 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1687 * Replaces control characters with printable output
1689 * @param $str String with control characters
1690 * @return $str Replaced string
1692 protected function replaceControlCharacters ($str) {
1695 chr(13), '[r]', str_replace(
1696 chr(10), '[n]', str_replace(
1706 * Output a partial stub message for the caller method
1708 * @param $message An optional message to display
1711 protected function partialStub ($message = '') {
1712 // Get the backtrace
1713 $backtrace = debug_backtrace();
1715 // Generate the class::method string
1716 $methodName = 'UnknownClass->unknownMethod';
1717 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1718 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1721 // Construct the full message
1722 $stubMessage = sprintf('[%s:] Partial stub!',
1726 // Is the extra message given?
1727 if (!empty($message)) {
1728 // Then add it as well
1729 $stubMessage .= ' Message: ' . $message;
1732 // Debug instance is there?
1733 if (!is_null($this->getDebugInstance())) {
1734 // Output stub message
1735 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1738 trigger_error($stubMessage);
1744 * Outputs a debug backtrace and stops further script execution
1746 * @param $message An optional message to output
1747 * @param $doExit Whether exit the program (TRUE is default)
1750 public function debugBackTrace ($message = '', $doExit = TRUE) {
1751 // Sorry, there is no other way getting this nice backtrace
1752 if (!empty($message)) {
1754 printf('Message: %s<br />' . chr(10), $message);
1758 debug_print_backtrace();
1762 if ($doExit === TRUE) {
1768 * Creates an instance of a debugger instance
1770 * @param $className Name of the class (currently unsupported)
1771 * @return $debugInstance An instance of a debugger class
1773 public final static function createDebugInstance ($className) {
1774 // Is the instance set?
1775 if (!Registry::getRegistry()->instanceExists('debug')) {
1776 // Init debug instance
1777 $debugInstance = NULL;
1781 // Get a debugger instance
1782 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'));
1783 } catch (NullPointerException $e) {
1784 // Didn't work, no instance there
1785 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1788 // Empty string should be ignored and used for testing the middleware
1789 DebugMiddleware::getSelfInstance()->output('');
1791 // Set it in its own class. This will set it in the registry
1792 $debugInstance->setDebugInstance($debugInstance);
1794 // Get instance from registry
1795 $debugInstance = Registry::getRegistry()->getDebugInstance();
1799 return $debugInstance;
1803 * Simple output of a message with line-break
1805 * @param $message Message to output
1808 public function outputLine ($message) {
1810 print($message . PHP_EOL);
1814 * Outputs a debug message whether to debug instance (should be set!) or
1815 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1816 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1818 * @param $message Message we shall send out...
1819 * @param $doPrint Whether print or die here (default: print)
1820 * @paran $stripTags Whether to strip tags (default: FALSE)
1823 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1824 // Set debug instance to NULL
1825 $debugInstance = NULL;
1829 // Get debug instance
1830 $debugInstance = $this->getDebugInstance();
1831 } catch (NullPointerException $e) {
1832 // The debug instance is not set (yet)
1835 // Is the debug instance there?
1836 if (is_object($debugInstance)) {
1837 // Use debug output handler
1838 $debugInstance->output($message, $stripTags);
1840 if ($doPrint === FALSE) {
1841 // Die here if not printed
1845 // Are debug times enabled?
1846 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1848 $message = $this->getPrintableExecutionTime() . $message;
1852 if ($doPrint === TRUE) {
1854 $this->outputLine($message);
1863 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1865 * @param $str The string, what ever it is needs to be converted
1866 * @return $className Generated class name
1868 public function convertToClassName ($str) {
1872 // Convert all dashes in underscores
1873 $str = $this->convertDashesToUnderscores($str);
1875 // Now use that underscores to get classname parts for hungarian style
1876 foreach (explode('_', $str) as $strPart) {
1877 // Make the class name part lower case and first upper case
1878 $className .= ucfirst(strtolower($strPart));
1881 // Return class name
1886 * Converts dashes to underscores, e.g. useable for configuration entries
1888 * @param $str The string with maybe dashes inside
1889 * @return $str The converted string with no dashed, but underscores
1891 public final function convertDashesToUnderscores ($str) {
1893 $str = str_replace('-', '_', $str);
1895 // Return converted string
1900 * Marks up the code by adding e.g. line numbers
1902 * @param $phpCode Unmarked PHP code
1903 * @return $markedCode Marked PHP code
1905 public function markupCode ($phpCode) {
1910 $errorArray = error_get_last();
1912 // Init the code with error message
1913 if (is_array($errorArray)) {
1915 $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>',
1916 basename($errorArray['file']),
1917 $errorArray['line'],
1918 $errorArray['message'],
1923 // Add line number to the code
1924 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1926 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1928 htmlentities($code, ENT_QUOTES)
1937 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1938 * beatiful for web-based front-ends. If null is given a message id
1939 * null_timestamp will be resolved and returned.
1941 * @param $timestamp Timestamp to prepare (filter) for display
1942 * @return $readable A readable timestamp
1944 public function doFilterFormatTimestamp ($timestamp) {
1945 // Default value to return
1948 // Is the timestamp null?
1949 if (is_null($timestamp)) {
1950 // Get a message string
1951 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1953 switch ($this->getLanguageInstance()->getLanguageCode()) {
1954 case 'de': // German format is a bit different to default
1955 // Split the GMT stamp up
1956 $dateTime = explode(' ', $timestamp );
1957 $dateArray = explode('-', $dateTime[0]);
1958 $timeArray = explode(':', $dateTime[1]);
1960 // Construct the timestamp
1961 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1971 default: // Default is pass-through
1972 $readable = $timestamp;
1982 * Filter a given number into a localized number
1984 * @param $value The raw value from e.g. database
1985 * @return $localized Localized value
1987 public function doFilterFormatNumber ($value) {
1988 // Generate it from config and localize dependencies
1989 switch ($this->getLanguageInstance()->getLanguageCode()) {
1990 case 'de': // German format is a bit different to default
1991 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1994 default: // US, etc.
1995 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2004 * "Getter" for databse entry
2006 * @return $entry An array with database entries
2007 * @throws NullPointerException If the database result is not found
2008 * @throws InvalidDatabaseResultException If the database result is invalid
2010 protected final function getDatabaseEntry () {
2011 // Is there an instance?
2012 if (!$this->getResultInstance() instanceof SearchableResult) {
2013 // Throw an exception here
2014 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2018 $this->getResultInstance()->rewind();
2020 // Do we have an entry?
2021 if ($this->getResultInstance()->valid() === FALSE) {
2022 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2023 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2027 $this->getResultInstance()->next();
2030 $entry = $this->getResultInstance()->current();
2037 * Getter for field name
2039 * @param $fieldName Field name which we shall get
2040 * @return $fieldValue Field value from the user
2041 * @throws NullPointerException If the result instance is null
2043 public final function getField ($fieldName) {
2044 // Default field value
2047 // Get result instance
2048 $resultInstance = $this->getResultInstance();
2050 // Is this instance null?
2051 if (is_null($resultInstance)) {
2052 // Then the user instance is no longer valid (expired cookies?)
2053 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2056 // Get current array
2057 $fieldArray = $resultInstance->current();
2058 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2060 // Convert dashes to underscore
2061 $fieldName2 = $this->convertDashesToUnderscores($fieldName);
2063 // Does the field exist?
2064 if ($this->isFieldSet($fieldName)) {
2066 $fieldValue = $fieldArray[$fieldName2];
2067 } elseif (defined('DEVELOPER')) {
2068 // Missing field entry, may require debugging
2069 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2071 // Missing field entry, may require debugging
2072 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2080 * Checks if given field is set
2082 * @param $fieldName Field name to check
2083 * @return $isSet Whether the given field name is set
2084 * @throws NullPointerException If the result instance is null
2086 public function isFieldSet ($fieldName) {
2087 // Get result instance
2088 $resultInstance = $this->getResultInstance();
2090 // Is this instance null?
2091 if (is_null($resultInstance)) {
2092 // Then the user instance is no longer valid (expired cookies?)
2093 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2096 // Get current array
2097 $fieldArray = $resultInstance->current();
2098 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2100 // Convert dashes to underscore
2101 $fieldName = $this->convertDashesToUnderscores($fieldName);
2104 $isSet = isset($fieldArray[$fieldName]);
2111 * Flushs all pending updates to the database layer
2115 public function flushPendingUpdates () {
2116 // Get result instance
2117 $resultInstance = $this->getResultInstance();
2119 // Do we have data to update?
2120 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2121 // Get wrapper class name config entry
2122 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2124 // Create object instance
2125 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
2127 // Yes, then send the whole result to the database layer
2128 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2133 * Outputs a deprecation warning to the developer.
2135 * @param $message The message we shall output to the developer
2137 * @todo Write a logging mechanism for productive mode
2139 public function deprecationWarning ($message) {
2140 // Is developer mode active?
2141 if (defined('DEVELOPER')) {
2142 // Debug instance is there?
2143 if (!is_null($this->getDebugInstance())) {
2144 // Output stub message
2145 self::createDebugInstance(__CLASS__)->debugOutput($message);
2148 trigger_error($message . "<br />\n");
2152 // @TODO Finish this part!
2153 $this->partialStub('Developer mode inactive. Message:' . $message);
2158 * Checks whether the given PHP extension is loaded
2160 * @param $phpExtension The PHP extension we shall check
2161 * @return $isLoaded Whether the PHP extension is loaded
2163 public final function isPhpExtensionLoaded ($phpExtension) {
2165 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2172 * "Getter" as a time() replacement but with milliseconds. You should use this
2173 * method instead of the encapsulated getimeofday() function.
2175 * @return $milliTime Timestamp with milliseconds
2177 public function getMilliTime () {
2178 // Get the time of day as float
2179 $milliTime = gettimeofday(TRUE);
2186 * Idles (sleeps) for given milliseconds
2188 * @return $hasSlept Whether it goes fine
2190 public function idle ($milliSeconds) {
2191 // Sleep is fine by default
2194 // Idle so long with found function
2195 if (function_exists('time_sleep_until')) {
2196 // Get current time and add idle time
2197 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2199 // New PHP 5.1.0 function found, ignore errors
2200 $hasSlept = @time_sleep_until($sleepUntil);
2203 * My Sun station doesn't have that function even with latest PHP
2206 usleep($milliSeconds * 1000);
2213 * Converts a hexadecimal string, even with negative sign as first string to
2214 * a decimal number using BC functions.
2216 * This work is based on comment #86673 on php.net documentation page at:
2217 * <http://de.php.net/manual/en/function.dechex.php#86673>
2219 * @param $hex Hexadecimal string
2220 * @return $dec Decimal number
2222 protected function hex2dec ($hex) {
2223 // Convert to all lower-case
2224 $hex = strtolower($hex);
2226 // Detect sign (negative/positive numbers)
2228 if (substr($hex, 0, 1) == '-') {
2230 $hex = substr($hex, 1);
2233 // Decode the hexadecimal string into a decimal number
2235 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2236 $factor = self::$hexdec[substr($hex, $i, 1)];
2237 $dec = bcadd($dec, bcmul($factor, $e));
2240 // Return the decimal number
2241 return $sign . $dec;
2245 * Converts even very large decimal numbers, also signed, to a hexadecimal
2248 * This work is based on comment #97756 on php.net documentation page at:
2249 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2251 * @param $dec Decimal number, even with negative sign
2252 * @param $maxLength Optional maximum length of the string
2253 * @return $hex Hexadecimal string
2255 protected function dec2hex ($dec, $maxLength = 0) {
2256 // maxLength can be zero or devideable by 2
2257 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2259 // Detect sign (negative/positive numbers)
2266 // Encode the decimal number into a hexadecimal string
2269 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2271 } while ($dec >= 1);
2274 * Leading zeros are required for hex-decimal "numbers". In some
2275 * situations more leading zeros are wanted, so check for both
2278 if ($maxLength > 0) {
2279 // Prepend more zeros
2280 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2281 } elseif ((strlen($hex) % 2) != 0) {
2282 // Only make string's length dividable by 2
2286 // Return the hexadecimal string
2287 return $sign . $hex;
2291 * Converts a ASCII string (0 to 255) into a decimal number.
2293 * @param $asc The ASCII string to be converted
2294 * @return $dec Decimal number
2296 protected function asc2dec ($asc) {
2297 // Convert it into a hexadecimal number
2298 $hex = bin2hex($asc);
2300 // And back into a decimal number
2301 $dec = $this->hex2dec($hex);
2308 * Converts a decimal number into an ASCII string.
2310 * @param $dec Decimal number
2311 * @return $asc An ASCII string
2313 protected function dec2asc ($dec) {
2314 // First convert the number into a hexadecimal string
2315 $hex = $this->dec2hex($dec);
2317 // Then convert it into the ASCII string
2318 $asc = $this->hex2asc($hex);
2325 * Converts a hexadecimal number into an ASCII string. Negative numbers
2328 * @param $hex Hexadecimal string
2329 * @return $asc An ASCII string
2331 protected function hex2asc ($hex) {
2332 // Check for length, it must be devideable by 2
2333 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2334 assert((strlen($hex) % 2) == 0);
2338 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2339 // Get the decimal number of the chunk
2340 $part = hexdec(substr($hex, $idx, 2));
2342 // Add it to the final string
2346 // Return the final string
2351 * Checks whether the given encoded data was encoded with Base64
2353 * @param $encodedData Encoded data we shall check
2354 * @return $isBase64 Whether the encoded data is Base64
2356 protected function isBase64Encoded ($encodedData) {
2358 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2365 * "Getter" to get response/request type from analysis of the system.
2367 * @return $responseType Analyzed response type
2369 protected static function getResponseTypeFromSystem () {
2370 // Default is console
2371 $responseType = 'console';
2373 // Is 'HTTP_HOST' set?
2374 if (isset($_SERVER['HTTP_HOST'])) {
2376 * Then it is a HTML response/request as RSS and so on may be
2377 * transfered over HTTP as well.
2379 $responseType = 'html';
2383 return $responseType;
2387 * Gets a cache key from Criteria instance
2389 * @param $criteriaInstance An instance of a Criteria class
2390 * @param $onlyKeys Only use these keys for a cache key
2391 * @return $cacheKey A cache key suitable for lookup/storage purposes
2393 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2395 $cacheKey = sprintf('%s@%s',
2396 $this->__toString(),
2397 $criteriaInstance->getCacheKey($onlyKeys)
2401 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2406 * Getter for startup time in miliseconds
2408 * @return $startupTime Startup time in miliseconds
2410 protected function getStartupTime () {
2411 return self::$startupTime;
2415 * "Getter" for a printable currently execution time in nice braces
2417 * @return $executionTime Current execution time in nice braces
2419 protected function getPrintableExecutionTime () {
2420 // Caculate the execution time
2421 $executionTime = microtime(TRUE) - $this->getStartupTime();
2423 // Pack it in nice braces
2424 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2427 return $executionTime;
2431 * Hashes a given string with a simple but stronger hash function (no salt)
2432 * and hex-encode it.
2434 * @param $str The string to be hashed
2435 * @return $hash The hash from string $str
2437 public static final function hash ($str) {
2438 // Hash given string with (better secure) hasher
2439 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2446 * "Getter" for length of hash() output. This will be "cached" to speed up
2449 * @return $length Length of hash() output
2451 public static final function getHashLength () {
2453 if (is_null(self::$hashLength)) {
2454 // No, then hash a string and save its length.
2455 self::$hashLength = strlen(self::hash('abc123'));
2459 return self::$hashLength;
2463 * Checks whether the given number is really a number (only chars 0-9).
2465 * @param $num A string consisting only chars between 0 and 9
2466 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2467 * @param $assertMismatch Whether to assert mismatches
2468 * @return $ret The (hopefully) secured numbered value
2470 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2471 // Filter all numbers out
2472 $ret = preg_replace('/[^0123456789]/', '', $num);
2475 if ($castValue === TRUE) {
2476 // Cast to biggest numeric type
2477 $ret = (double) $ret;
2480 // Assert only if requested
2481 if ($assertMismatch === TRUE) {
2482 // Has the whole value changed?
2483 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2491 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2493 * @param $num A string consisting only chars between 0 and 9
2494 * @param $assertMismatch Whether to assert mismatches
2495 * @return $ret The (hopefully) secured hext-numbered value
2497 public function hexval ($num, $assertMismatch = FALSE) {
2498 // Filter all numbers out
2499 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2501 // Assert only if requested
2502 if ($assertMismatch === TRUE) {
2503 // Has the whole value changed?
2504 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2512 * Checks whether start/end marker are set
2514 * @param $data Data to be checked
2515 * @return $isset Whether start/end marker are set
2517 public final function ifStartEndMarkersSet ($data) {
2519 $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));
2521 // ... and return it
2526 * Determines if an element is set in the generic array
2528 * @param $keyGroup Main group for the key
2529 * @param $subGroup Sub group for the key
2530 * @param $key Key to check
2531 * @param $element Element to check
2532 * @return $isset Whether the given key is set
2534 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2536 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2539 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2545 * Determines if a key is set in the generic array
2547 * @param $keyGroup Main group for the key
2548 * @param $subGroup Sub group for the key
2549 * @param $key Key to check
2550 * @return $isset Whether the given key is set
2552 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2554 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2557 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2565 * Determines if a group is set in the generic array
2567 * @param $keyGroup Main group
2568 * @param $subGroup Sub group
2569 * @return $isset Whether the given group is set
2571 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2573 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2576 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2583 * Getter for sub key group
2585 * @param $keyGroup Main key group
2586 * @param $subGroup Sub key group
2587 * @return $array An array with all array elements
2589 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2591 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2592 // No, then abort here
2593 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2598 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2601 return $this->genericArray[$keyGroup][$subGroup];
2605 * Unsets a given key in generic array
2607 * @param $keyGroup Main group for the key
2608 * @param $subGroup Sub group for the key
2609 * @param $key Key to unset
2612 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2614 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2617 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2621 * Unsets a given element in generic array
2623 * @param $keyGroup Main group for the key
2624 * @param $subGroup Sub group for the key
2625 * @param $key Key to unset
2626 * @param $element Element to unset
2629 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2631 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2634 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2638 * Append a string to a given generic array key
2640 * @param $keyGroup Main group for the key
2641 * @param $subGroup Sub group for the key
2642 * @param $key Key to unset
2643 * @param $value Value to add/append
2646 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2648 //* 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);
2650 // Is it already there?
2651 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2653 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2656 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2661 * Append a string to a given generic array element
2663 * @param $keyGroup Main group for the key
2664 * @param $subGroup Sub group for the key
2665 * @param $key Key to unset
2666 * @param $element Element to check
2667 * @param $value Value to add/append
2670 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2672 //* 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);
2674 // Is it already there?
2675 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2677 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2680 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2685 * Initializes given generic array group
2687 * @param $keyGroup Main group for the key
2688 * @param $subGroup Sub group for the key
2689 * @param $key Key to use
2690 * @param $forceInit Optionally force initialization
2693 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2695 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2697 // Is it already set?
2698 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2699 // Already initialized
2700 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2705 $this->genericArray[$keyGroup][$subGroup] = array();
2709 * Initializes given generic array key
2711 * @param $keyGroup Main group for the key
2712 * @param $subGroup Sub group for the key
2713 * @param $key Key to use
2714 * @param $forceInit Optionally force initialization
2717 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2719 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2721 // Is it already set?
2722 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2723 // Already initialized
2724 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2729 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2733 * Initializes given generic array element
2735 * @param $keyGroup Main group for the key
2736 * @param $subGroup Sub group for the key
2737 * @param $key Key to use
2738 * @param $element Element to use
2739 * @param $forceInit Optionally force initialization
2742 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2744 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2746 // Is it already set?
2747 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2748 // Already initialized
2749 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2754 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2758 * Pushes an element to a generic key
2760 * @param $keyGroup Main group for the key
2761 * @param $subGroup Sub group for the key
2762 * @param $key Key to use
2763 * @param $value Value to add/append
2764 * @return $count Number of array elements
2766 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2768 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2771 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2773 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2777 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2780 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2781 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2786 * Pushes an element to a generic array element
2788 * @param $keyGroup Main group for the key
2789 * @param $subGroup Sub group for the key
2790 * @param $key Key to use
2791 * @param $element Element to check
2792 * @param $value Value to add/append
2793 * @return $count Number of array elements
2795 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2797 //* 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));
2800 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2802 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2806 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2809 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2810 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2815 * Pops an element from a generic group
2817 * @param $keyGroup Main group for the key
2818 * @param $subGroup Sub group for the key
2819 * @param $key Key to unset
2820 * @return $value Last "popped" value
2822 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2824 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2827 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2829 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2834 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2837 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2838 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2843 * Shifts an element from a generic group
2845 * @param $keyGroup Main group for the key
2846 * @param $subGroup Sub group for the key
2847 * @param $key Key to unset
2848 * @return $value Last "popped" value
2850 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2852 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2855 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2857 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2862 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2865 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2866 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2871 * Count generic array group
2873 * @param $keyGroup Main group for the key
2874 * @return $count Count of given group
2876 protected final function countGenericArray ($keyGroup) {
2878 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2881 if (!isset($this->genericArray[$keyGroup])) {
2883 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2888 $count = count($this->genericArray[$keyGroup]);
2891 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2898 * Count generic array sub group
2900 * @param $keyGroup Main group for the key
2901 * @param $subGroup Sub group for the key
2902 * @return $count Count of given group
2904 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2906 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2909 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2911 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2916 $count = count($this->genericArray[$keyGroup][$subGroup]);
2919 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2926 * Count generic array elements
2928 * @param $keyGroup Main group for the key
2929 * @param $subGroup Sub group for the key
2930 * @para $key Key to count
2931 * @return $count Count of given key
2933 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2935 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2938 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2940 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2942 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2944 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2949 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2952 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2959 * Getter for whole generic group array
2961 * @param $keyGroup Key group to get
2962 * @return $array Whole generic array group
2964 protected final function getGenericArray ($keyGroup) {
2966 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2969 if (!isset($this->genericArray[$keyGroup])) {
2971 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2976 return $this->genericArray[$keyGroup];
2980 * Setter for generic array key
2982 * @param $keyGroup Key group to get
2983 * @param $subGroup Sub group for the key
2984 * @param $key Key to unset
2985 * @param $value Mixed value from generic array element
2988 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2990 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2993 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2997 * Getter for generic array key
2999 * @param $keyGroup Key group to get
3000 * @param $subGroup Sub group for the key
3001 * @param $key Key to unset
3002 * @return $value Mixed value from generic array element
3004 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3006 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3009 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3011 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3016 return $this->genericArray[$keyGroup][$subGroup][$key];
3020 * Sets a value in given generic array key/element
3022 * @param $keyGroup Main group for the key
3023 * @param $subGroup Sub group for the key
3024 * @param $key Key to set
3025 * @param $element Element to set
3026 * @param $value Value to set
3029 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3031 //* 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));
3034 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3038 * Getter for generic array element
3040 * @param $keyGroup Key group to get
3041 * @param $subGroup Sub group for the key
3042 * @param $key Key to look for
3043 * @param $element Element to look for
3044 * @return $value Mixed value from generic array element
3046 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3048 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3051 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3053 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3058 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3062 * Checks if a given sub group is valid (array)
3064 * @param $keyGroup Key group to get
3065 * @param $subGroup Sub group for the key
3066 * @return $isValid Whether given sub group is valid
3068 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3070 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3073 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3080 * Checks if a given key is valid (array)
3082 * @param $keyGroup Key group to get
3083 * @param $subGroup Sub group for the key
3084 * @param $key Key to check
3085 * @return $isValid Whether given sub group is valid
3087 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3089 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3092 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3099 * Initializes the web output instance
3103 protected function initWebOutputInstance () {
3104 // Get application instance
3105 $applicationInstance = Registry::getRegistry()->getInstance('app');
3107 // Is this a response instance?
3108 if ($this instanceof Responseable) {
3109 // Then set it in application instance
3110 $applicationInstance->setResponseInstance($this);
3113 // Init web output instance
3114 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3117 $this->setWebOutputInstance($outputInstance);
3121 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3123 * @param $boolean Boolean value
3124 * @return $translated Translated boolean value
3126 public static final function translateBooleanToYesNo ($boolean) {
3127 // Make sure it is really boolean
3128 assert(is_bool($boolean));
3131 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3133 // ... and return it
3138 * Encodes raw data (almost any type) by "serializing" it and then pack it
3139 * into a "binary format".
3141 * @param $rawData Raw data (almost any type)
3142 * @return $encoded Encoded data
3144 protected function encodeData ($rawData) {
3145 // Make sure no objects or resources pass through
3146 assert(!is_object($rawData));
3147 assert(!is_resource($rawData));
3149 // First "serialize" it (json_encode() is faster than serialize())
3150 $encoded = $this->packString(json_encode($rawData));
3157 * Pack a string into a "binary format". Please execuse me that this is
3158 * widely undocumented. :-(
3160 * @param $str Unpacked string
3161 * @return $packed Packed string
3162 * @todo Improve documentation
3164 protected function packString ($str) {
3166 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3168 // First compress the string (gzcompress is okay)
3169 $str = gzcompress($str);
3174 // And start the "encoding" loop
3175 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3177 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3178 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3180 if (($idx + $i) <= strlen($str)) {
3181 $ord = ord(substr($str, ($idx + $i), 1));
3183 $add = $ord * pow(256, $factor);
3187 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3191 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3192 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3194 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3195 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3201 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');