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 * An instance of a communicator
219 private $communicatorInstance = NULL;
222 * Thousands separator
224 private $thousands = '.'; // German
229 private $decimals = ','; // German
234 private $socketResource = FALSE;
237 * Regular expression to use for validation
239 private $regularExpression = '';
244 private $packageData = array();
249 private $genericArray = array();
254 private $commandName = '';
259 private $controllerName = '';
262 * Array with bitmasks and such for pack/unpack methods to support both
263 * 32-bit and 64-bit systems
265 private $packingData = array(
268 'left' => 0xffff0000,
269 'right' => 0x0000ffff,
275 'left' => 0xffffffff00000000,
276 'right' => 0x00000000ffffffff,
283 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
285 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
287 private $archArrayElement = FALSE;
289 /***********************
290 * Exception codes.... *
291 ***********************/
293 // @todo Try to clean these constants up
294 const EXCEPTION_IS_NULL_POINTER = 0x001;
295 const EXCEPTION_IS_NO_OBJECT = 0x002;
296 const EXCEPTION_IS_NO_ARRAY = 0x003;
297 const EXCEPTION_MISSING_METHOD = 0x004;
298 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
299 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
300 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
301 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
302 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
303 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
304 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
305 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
306 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
307 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
308 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
309 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
310 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
311 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
312 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
313 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
314 const EXCEPTION_PATH_NOT_FOUND = 0x015;
315 const EXCEPTION_INVALID_PATH_NAME = 0x016;
316 const EXCEPTION_READ_PROTECED_PATH = 0x017;
317 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
318 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
319 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
320 const EXCEPTION_INVALID_RESOURCE = 0x01b;
321 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
322 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
323 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
324 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
325 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
326 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
327 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
328 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
329 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
330 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
331 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
332 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
333 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
334 const EXCEPTION_INVALID_STRING = 0x029;
335 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
336 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
337 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
338 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
339 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
340 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
341 const EXCEPTION_MISSING_ELEMENT = 0x030;
342 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
343 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
344 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
345 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
346 const EXCEPTION_FATAL_ERROR = 0x035;
347 const EXCEPTION_FILE_NOT_FOUND = 0x036;
348 const EXCEPTION_ASSERTION_FAILED = 0x037;
349 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
350 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
351 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03a;
354 * Hexadecimal->Decimal translation array
356 private static $hexdec = array(
376 * Decimal->hexadecimal translation array
378 private static $dechex = array(
398 * Startup time in miliseconds
400 private static $startupTime = 0;
403 * Protected super constructor
405 * @param $className Name of the class
408 protected function __construct ($className) {
410 $this->setRealClass($className);
412 // Set configuration instance if no registry ...
413 if (!$this instanceof Register) {
414 // ... because registries doesn't need to be configured
415 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
418 // Is the startup time set? (0 cannot be TRUE anymore)
419 if (self::$startupTime == 0) {
421 self::$startupTime = microtime(TRUE);
425 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
429 * Destructor for all classes
433 public function __destruct () {
434 // Flush any updated entries to the database
435 $this->flushPendingUpdates();
437 // Is this object already destroyed?
438 if ($this->__toString() != 'DestructedObject') {
439 // Destroy all informations about this class but keep some text about it alive
440 $this->setRealClass('DestructedObject');
441 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
442 // Already destructed object
443 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
448 // Do not call this twice
449 trigger_error(__METHOD__ . ': Called twice.');
455 * The __call() method where all non-implemented methods end up
457 * @param $methodName Name of the missing method
458 * @args $args Arguments passed to the method
461 public final function __call ($methodName, $args) {
462 return self::__callStatic($methodName, $args);
466 * The __callStatic() method where all non-implemented static methods end up
468 * @param $methodName Name of the missing method
469 * @args $args Arguments passed to the method
472 public static final function __callStatic ($methodName, $args) {
473 // Init argument string
476 // Is it empty or an array?
479 $argsString = 'NULL';
480 } elseif (is_array($args)) {
481 // Some arguments are there
482 foreach ($args as $arg) {
483 // Add the value itself if not array. This prevents 'array to string conversion' message
484 if (is_array($arg)) {
485 $argsString .= 'Array';
490 // Add data about the argument
491 $argsString .= ' (' . gettype($arg);
493 if (is_string($arg)) {
494 // Add length for strings
495 $argsString .= ', ' . strlen($arg);
496 } elseif (is_array($arg)) {
497 // .. or size if array
498 $argsString .= ', ' . count($arg);
499 } elseif ($arg === TRUE) {
500 // ... is boolean 'TRUE'
501 $argsString .= ', TRUE';
502 } elseif ($arg === FALSE) {
503 // ... is boolean 'FALSE'
504 $argsString .= ', FALSE';
508 $argsString .= '), ';
512 if (substr($argsString, -2, 1) == ',') {
513 $argsString = substr($argsString, 0, -2);
516 // Invalid arguments!
517 $argsString = '!INVALID:' . gettype($args) . '!';
520 // Output stub message
521 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
522 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
532 * Getter for $realClass
534 * @return $realClass The name of the real class (not BaseFrameworkSystem)
536 public function __toString () {
537 return $this->realClass;
541 * Magic method to catch setting of missing but set class fields/attributes
543 * @param $name Name of the field/attribute
544 * @param $value Value to store
547 public final function __set ($name, $value) {
548 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
551 print_r($value, TRUE)
556 * Magic method to catch getting of missing fields/attributes
558 * @param $name Name of the field/attribute
561 public final function __get ($name) {
562 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
568 * Magic method to catch unsetting of missing fields/attributes
570 * @param $name Name of the field/attribute
573 public final function __unset ($name) {
574 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
580 * Magic method to catch object serialization
582 * @return $unsupported Unsupported method
583 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
585 public final function __sleep () {
586 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
590 * Magic method to catch object deserialization
592 * @return $unsupported Unsupported method
593 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
595 public final function __wakeup () {
596 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
600 * Magic method to catch calls when an object instance is called
602 * @return $unsupported Unsupported method
603 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
605 public final function __invoke () {
606 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
610 * Setter for the real class name
612 * @param $realClass Class name (string)
615 public final function setRealClass ($realClass) {
617 $this->realClass = (string) $realClass;
621 * Setter for database result instance
623 * @param $resultInstance An instance of a database result class
625 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
627 protected final function setResultInstance (SearchableResult $resultInstance) {
628 $this->resultInstance = $resultInstance;
632 * Getter for database result instance
634 * @return $resultInstance An instance of a database result class
636 public final function getResultInstance () {
637 return $this->resultInstance;
641 * Setter for template engine instances
643 * @param $templateInstance An instance of a template engine class
646 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
647 $this->templateInstance = $templateInstance;
651 * Getter for template engine instances
653 * @return $templateInstance An instance of a template engine class
655 protected final function getTemplateInstance () {
656 return $this->templateInstance;
660 * Setter for search instance
662 * @param $searchInstance Searchable criteria instance
665 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
666 $this->searchInstance = $searchInstance;
670 * Getter for search instance
672 * @return $searchInstance Searchable criteria instance
674 public final function getSearchInstance () {
675 return $this->searchInstance;
679 * Setter for update instance
681 * @param $updateInstance Searchable criteria instance
684 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
685 $this->updateInstance = $updateInstance;
689 * Getter for update instance
691 * @return $updateInstance Updateable criteria instance
693 public final function getUpdateInstance () {
694 return $this->updateInstance;
698 * Setter for resolver instance
700 * @param $resolverInstance Instance of a command resolver class
703 public final function setResolverInstance (Resolver $resolverInstance) {
704 $this->resolverInstance = $resolverInstance;
708 * Getter for resolver instance
710 * @return $resolverInstance Instance of a command resolver class
712 public final function getResolverInstance () {
713 return $this->resolverInstance;
717 * Setter for language instance
719 * @param $configInstance The configuration instance which shall
720 * be FrameworkConfiguration
723 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
724 Registry::getRegistry()->addInstance('config', $configInstance);
728 * Getter for configuration instance
730 * @return $configInstance Configuration instance
732 public final function getConfigInstance () {
733 $configInstance = Registry::getRegistry()->getInstance('config');
734 return $configInstance;
738 * Setter for debug instance
740 * @param $debugInstance The instance for debug output class
743 public final function setDebugInstance (DebugMiddleware $debugInstance) {
744 Registry::getRegistry()->addInstance('debug', $debugInstance);
748 * Getter for debug instance
750 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
752 public final function getDebugInstance () {
753 // Get debug instance
754 $debugInstance = Registry::getRegistry()->getInstance('debug');
757 return $debugInstance;
761 * Setter for web output instance
763 * @param $webInstance The instance for web output class
766 public final function setWebOutputInstance (OutputStreamer $webInstance) {
767 Registry::getRegistry()->addInstance('web_output', $webInstance);
771 * Getter for web output instance
773 * @return $webOutputInstance - Instance to class WebOutput
775 public final function getWebOutputInstance () {
776 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
777 return $webOutputInstance;
781 * Setter for database instance
783 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
786 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
787 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
791 * Getter for database layer
793 * @return $databaseInstance The database layer instance
795 public final function getDatabaseInstance () {
797 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
800 return $databaseInstance;
804 * Setter for compressor channel
806 * @param $compressorInstance An instance of CompressorChannel
809 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
810 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
814 * Getter for compressor channel
816 * @return $compressorInstance The compressor channel
818 public final function getCompressorChannel () {
819 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
820 return $compressorInstance;
824 * Protected getter for a manageable application helper class
826 * @return $applicationInstance An instance of a manageable application helper class
828 protected final function getApplicationInstance () {
829 $applicationInstance = Registry::getRegistry()->getInstance('application');
830 return $applicationInstance;
834 * Setter for a manageable application helper class
836 * @param $applicationInstance An instance of a manageable application helper class
839 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
840 Registry::getRegistry()->addInstance('application', $applicationInstance);
844 * Setter for request instance
846 * @param $requestInstance An instance of a Requestable class
849 public final function setRequestInstance (Requestable $requestInstance) {
850 $this->requestInstance = $requestInstance;
854 * Getter for request instance
856 * @return $requestInstance An instance of a Requestable class
858 public final function getRequestInstance () {
859 return $this->requestInstance;
863 * Setter for response instance
865 * @param $responseInstance An instance of a Responseable class
868 public final function setResponseInstance (Responseable $responseInstance) {
869 $this->responseInstance = $responseInstance;
873 * Getter for response instance
875 * @return $responseInstance An instance of a Responseable class
877 public final function getResponseInstance () {
878 return $this->responseInstance;
882 * Private getter for language instance
884 * @return $langInstance An instance to the language sub-system
886 protected final function getLanguageInstance () {
887 $langInstance = Registry::getRegistry()->getInstance('language');
888 return $langInstance;
892 * Setter for language instance
894 * @param $langInstance An instance to the language sub-system
896 * @see LanguageSystem
898 public final function setLanguageInstance (ManageableLanguage $langInstance) {
899 Registry::getRegistry()->addInstance('language', $langInstance);
903 * Private getter for file IO instance
905 * @return $fileIoInstance An instance to the file I/O sub-system
907 protected final function getFileIoInstance () {
908 return $this->fileIoInstance;
912 * Setter for file I/O instance
914 * @param $fileIoInstance An instance to the file I/O sub-system
917 public final function setFileIoInstance (IoHandler $fileIoInstance) {
918 $this->fileIoInstance = $fileIoInstance;
922 * Protected setter for user instance
924 * @param $userInstance An instance of a user class
927 protected final function setUserInstance (ManageableAccount $userInstance) {
928 $this->userInstance = $userInstance;
932 * Getter for user instance
934 * @return $userInstance An instance of a user class
936 public final function getUserInstance () {
937 return $this->userInstance;
941 * Setter for controller instance (this surely breaks a bit the MVC patterm)
943 * @param $controllerInstance An instance of the controller
946 public final function setControllerInstance (Controller $controllerInstance) {
947 $this->controllerInstance = $controllerInstance;
951 * Getter for controller instance (this surely breaks a bit the MVC patterm)
953 * @return $controllerInstance An instance of the controller
955 public final function getControllerInstance () {
956 return $this->controllerInstance;
960 * Setter for RNG instance
962 * @param $rngInstance An instance of a random number generator (RNG)
965 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
966 $this->rngInstance = $rngInstance;
970 * Getter for RNG instance
972 * @return $rngInstance An instance of a random number generator (RNG)
974 public final function getRngInstance () {
975 return $this->rngInstance;
979 * Setter for Cryptable instance
981 * @param $cryptoInstance An instance of a Cryptable class
984 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
985 $this->cryptoInstance = $cryptoInstance;
989 * Getter for Cryptable instance
991 * @return $cryptoInstance An instance of a Cryptable class
993 public final function getCryptoInstance () {
994 return $this->cryptoInstance;
998 * Setter for the list instance
1000 * @param $listInstance A list of Listable
1003 protected final function setListInstance (Listable $listInstance) {
1004 $this->listInstance = $listInstance;
1008 * Getter for the list instance
1010 * @return $listInstance A list of Listable
1012 protected final function getListInstance () {
1013 return $this->listInstance;
1017 * Setter for the menu instance
1019 * @param $menuInstance A RenderableMenu instance
1022 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1023 $this->menuInstance = $menuInstance;
1027 * Getter for the menu instance
1029 * @return $menuInstance A RenderableMenu instance
1031 protected final function getMenuInstance () {
1032 return $this->menuInstance;
1036 * Setter for image instance
1038 * @param $imageInstance An instance of an image
1041 public final function setImageInstance (BaseImage $imageInstance) {
1042 $this->imageInstance = $imageInstance;
1046 * Getter for image instance
1048 * @return $imageInstance An instance of an image
1050 public final function getImageInstance () {
1051 return $this->imageInstance;
1055 * Setter for stacker instance
1057 * @param $stackInstance An instance of an stacker
1060 public final function setStackInstance (Stackable $stackInstance) {
1061 $this->stackInstance = $stackInstance;
1065 * Getter for stacker instance
1067 * @return $stackInstance An instance of an stacker
1069 public final function getStackInstance () {
1070 return $this->stackInstance;
1074 * Setter for compressor instance
1076 * @param $compressorInstance An instance of an compressor
1079 public final function setCompressorInstance (Compressor $compressorInstance) {
1080 $this->compressorInstance = $compressorInstance;
1084 * Getter for compressor instance
1086 * @return $compressorInstance An instance of an compressor
1088 public final function getCompressorInstance () {
1089 return $this->compressorInstance;
1093 * Setter for Parseable instance
1095 * @param $parserInstance An instance of an Parseable
1098 public final function setParserInstance (Parseable $parserInstance) {
1099 $this->parserInstance = $parserInstance;
1103 * Getter for Parseable instance
1105 * @return $parserInstance An instance of an Parseable
1107 public final function getParserInstance () {
1108 return $this->parserInstance;
1112 * Setter for HandleableProtocol instance
1114 * @param $protocolInstance An instance of an HandleableProtocol
1117 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1118 $this->protocolInstance = $protocolInstance;
1122 * Getter for HandleableProtocol instance
1124 * @return $protocolInstance An instance of an HandleableProtocol
1126 public final function getProtocolInstance () {
1127 return $this->protocolInstance;
1131 * Setter for DatabaseWrapper instance
1133 * @param $wrapperInstance An instance of an DatabaseWrapper
1136 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1137 $this->wrapperInstance = $wrapperInstance;
1141 * Getter for DatabaseWrapper instance
1143 * @return $wrapperInstance An instance of an DatabaseWrapper
1145 public final function getWrapperInstance () {
1146 return $this->wrapperInstance;
1150 * Setter for socket resource
1152 * @param $socketResource A valid socket resource
1155 public final function setSocketResource ($socketResource) {
1156 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1157 $this->socketResource = $socketResource;
1161 * Getter for socket resource
1163 * @return $socketResource A valid socket resource
1165 public final function getSocketResource () {
1166 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1167 return $this->socketResource;
1171 * Setter for regular expression
1173 * @param $regularExpression A valid regular expression
1176 public final function setRegularExpression ($regularExpression) {
1177 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1178 $this->regularExpression = $regularExpression;
1182 * Getter for regular expression
1184 * @return $regularExpression A valid regular expression
1186 public final function getRegularExpression () {
1187 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1188 return $this->regularExpression;
1192 * Setter for helper instance
1194 * @param $helperInstance An instance of a helper class
1197 protected final function setHelperInstance (Helper $helperInstance) {
1198 $this->helperInstance = $helperInstance;
1202 * Getter for helper instance
1204 * @return $helperInstance An instance of a helper class
1206 public final function getHelperInstance () {
1207 return $this->helperInstance;
1211 * Setter for a Source instance
1213 * @param $sourceInstance An instance of a Source class
1216 protected final function setSourceInstance (Source $sourceInstance) {
1217 $this->sourceInstance = $sourceInstance;
1221 * Getter for a Source instance
1223 * @return $sourceInstance An instance of a Source class
1225 protected final function getSourceInstance () {
1226 return $this->sourceInstance;
1230 * Setter for a UrlSource instance
1232 * @param $sourceInstance An instance of a UrlSource class
1235 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1236 $this->urlSourceInstance = $urlSourceInstance;
1240 * Getter for a UrlSource instance
1242 * @return $urlSourceInstance An instance of a UrlSource class
1244 protected final function getUrlSourceInstance () {
1245 return $this->urlSourceInstance;
1249 * Getter for a InputStream instance
1251 * @param $inputStreamInstance The InputStream instance
1253 protected final function getInputStreamInstance () {
1254 return $this->inputStreamInstance;
1258 * Setter for a InputStream instance
1260 * @param $inputStreamInstance The InputStream instance
1263 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1264 $this->inputStreamInstance = $inputStreamInstance;
1268 * Getter for a OutputStream instance
1270 * @param $outputStreamInstance The OutputStream instance
1272 protected final function getOutputStreamInstance () {
1273 return $this->outputStreamInstance;
1277 * Setter for a OutputStream instance
1279 * @param $outputStreamInstance The OutputStream instance
1282 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1283 $this->outputStreamInstance = $outputStreamInstance;
1287 * Setter for handler instance
1289 * @param $handlerInstance An instance of a Handleable class
1292 protected final function setHandlerInstance (Handleable $handlerInstance) {
1293 $this->handlerInstance = $handlerInstance;
1297 * Getter for handler instance
1299 * @return $handlerInstance A Networkable instance
1301 protected final function getHandlerInstance () {
1302 return $this->handlerInstance;
1306 * Setter for visitor instance
1308 * @param $visitorInstance A Visitor instance
1311 protected final function setVisitorInstance (Visitor $visitorInstance) {
1312 $this->visitorInstance = $visitorInstance;
1316 * Getter for visitor instance
1318 * @return $visitorInstance A Visitor instance
1320 protected final function getVisitorInstance () {
1321 return $this->visitorInstance;
1325 * Setter for DHT instance
1327 * @param $dhtInstance A Distributable instance
1330 protected final function setDhtInstance (Distributable $dhtInstance) {
1331 $this->dhtInstance = $dhtInstance;
1335 * Getter for DHT instance
1337 * @return $dhtInstance A Distributable instance
1339 protected final function getDhtInstance () {
1340 return $this->dhtInstance;
1344 * Setter for raw package Data
1346 * @param $packageData Raw package Data
1349 public final function setPackageData (array $packageData) {
1350 $this->packageData = $packageData;
1354 * Getter for raw package Data
1356 * @return $packageData Raw package Data
1358 public function getPackageData () {
1359 return $this->packageData;
1364 * Setter for Iterator instance
1366 * @param $iteratorInstance An instance of an Iterator
1369 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1370 $this->iteratorInstance = $iteratorInstance;
1374 * Getter for Iterator instance
1376 * @return $iteratorInstance An instance of an Iterator
1378 public final function getIteratorInstance () {
1379 return $this->iteratorInstance;
1383 * Setter for FilePointer instance
1385 * @param $pointerInstance An instance of an FilePointer class
1388 protected final function setPointerInstance (FilePointer $pointerInstance) {
1389 $this->pointerInstance = $pointerInstance;
1393 * Getter for FilePointer instance
1395 * @return $pointerInstance An instance of an FilePointer class
1397 public final function getPointerInstance () {
1398 return $this->pointerInstance;
1402 * Unsets pointer instance which triggers a call of __destruct() if the
1403 * instance is still there. This is surely not fatal on already "closed"
1404 * file pointer instances.
1406 * I don't want to mess around with above setter by giving it a default
1407 * value NULL as setter should always explicitly only set (existing) object
1408 * instances and NULL is NULL.
1412 protected final function unsetPointerInstance () {
1413 // Simply it to NULL
1414 $this->pointerInstance = NULL;
1418 * Setter for Indexable instance
1420 * @param $indexInstance An instance of an Indexable class
1423 protected final function setIndexInstance (Indexable $indexInstance) {
1424 $this->indexInstance = $indexInstance;
1428 * Getter for Indexable instance
1430 * @return $indexInstance An instance of an Indexable class
1432 public final function getIndexInstance () {
1433 return $this->indexInstance;
1437 * Setter for Block instance
1439 * @param $blockInstance An instance of an Block class
1442 protected final function setBlockInstance (Block $blockInstance) {
1443 $this->blockInstance = $blockInstance;
1447 * Getter for Block instance
1449 * @return $blockInstance An instance of an Block class
1451 public final function getBlockInstance () {
1452 return $this->blockInstance;
1456 * Setter for Minable instance
1458 * @param $minableInstance A Minable instance
1461 protected final function setMinableInstance (Minable $minableInstance) {
1462 $this->minableInstance = $minableInstance;
1466 * Getter for minable instance
1468 * @return $minableInstance A Minable instance
1470 protected final function getMinableInstance () {
1471 return $this->minableInstance;
1475 * Setter for FrameworkDirectory instance
1477 * @param $directoryInstance A FrameworkDirectoryPointer instance
1480 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1481 $this->directoryInstance = $directoryInstance;
1485 * Getter for FrameworkDirectory instance
1487 * @return $directoryInstance A FrameworkDirectory instance
1489 protected final function getDirectoryInstance () {
1490 return $this->directoryInstance;
1494 * Setter for listener instance
1496 * @param $listenerInstance A Listenable instance
1499 protected final function setListenerInstance (Listenable $listenerInstance) {
1500 $this->listenerInstance = $listenerInstance;
1504 * Getter for listener instance
1506 * @return $listenerInstance A Listenable instance
1508 protected final function getListenerInstance () {
1509 return $this->listenerInstance;
1513 * Getter for communicator instance
1515 * @return $communicatorInstance An instance of a Communicator class
1517 public final function getCommunicatorInstance () {
1518 return $this->communicatorInstance;
1522 * Setter for communicator instance
1524 * @param $communicatorInstance An instance of a Communicator class
1527 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1528 $this->communicatorInstance = $communicatorInstance;
1532 * Setter for command name
1534 * @param $commandName Last validated command name
1537 protected final function setCommandName ($commandName) {
1538 $this->commandName = $commandName;
1542 * Getter for command name
1544 * @return $commandName Last validated command name
1546 protected final function getCommandName () {
1547 return $this->commandName;
1551 * Setter for controller name
1553 * @param $controllerName Last validated controller name
1556 protected final function setControllerName ($controllerName) {
1557 $this->controllerName = $controllerName;
1561 * Getter for controller name
1563 * @return $controllerName Last validated controller name
1565 protected final function getControllerName () {
1566 return $this->controllerName;
1570 * Checks whether an object equals this object. You should overwrite this
1571 * method to implement own equality checks
1573 * @param $objectInstance An instance of a FrameworkInterface object
1574 * @return $equals Whether both objects equals
1576 public function equals (FrameworkInterface $objectInstance) {
1579 $this->__toString() == $objectInstance->__toString()
1581 $this->hashCode() == $objectInstance->hashCode()
1584 // Return the result
1589 * Generates a generic hash code of this class. You should really overwrite
1590 * this method with your own hash code generator code. But keep KISS in mind.
1592 * @return $hashCode A generic hash code respresenting this whole class
1594 public function hashCode () {
1596 return crc32($this->__toString());
1600 * Formats computer generated price values into human-understandable formats
1601 * with thousand and decimal separators.
1603 * @param $value The in computer format value for a price
1604 * @param $currency The currency symbol (use HTML-valid characters!)
1605 * @param $decNum Number of decimals after commata
1606 * @return $price The for the current language formated price string
1607 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1608 * thousands separator
1611 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1612 // Are all required attriutes set?
1613 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1614 // Throw an exception
1615 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1619 $value = (float) $value;
1621 // Reformat the US number
1622 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1624 // Return as string...
1629 * Appends a trailing slash to a string
1631 * @param $str A string (maybe) without trailing slash
1632 * @return $str A string with an auto-appended trailing slash
1634 public final function addMissingTrailingSlash ($str) {
1635 // Is there a trailing slash?
1636 if (substr($str, -1, 1) != '/') {
1640 // Return string with trailing slash
1645 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1646 * application helper instance (ApplicationHelper by default).
1648 * @param $applicationInstance An application helper instance or
1649 * null if we shall use the default
1650 * @return $templateInstance The template engine instance
1651 * @throws NullPointerException If the discovered application
1652 * instance is still null
1654 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1655 // Is the application instance set?
1656 if (is_null($applicationInstance)) {
1657 // Get the current instance
1658 $applicationInstance = $this->getApplicationInstance();
1661 if (is_null($applicationInstance)) {
1662 // Thrown an exception
1663 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1667 // Initialize the template engine
1668 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1670 // Return the prepared instance
1671 return $templateInstance;
1675 * Debugs this instance by putting out it's full content
1677 * @param $message Optional message to show in debug output
1680 public final function debugInstance ($message = '') {
1681 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1682 restore_error_handler();
1687 // Is a message set?
1688 if (!empty($message)) {
1689 // Construct message
1690 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1693 // Generate the output
1694 $content .= sprintf('<pre>%s</pre>',
1697 print_r($this, TRUE)
1703 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>',
1704 $this->__toString(),
1706 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1711 * Replaces control characters with printable output
1713 * @param $str String with control characters
1714 * @return $str Replaced string
1716 protected function replaceControlCharacters ($str) {
1719 chr(13), '[r]', str_replace(
1720 chr(10), '[n]', str_replace(
1730 * Output a partial stub message for the caller method
1732 * @param $message An optional message to display
1735 protected function partialStub ($message = '') {
1736 // Get the backtrace
1737 $backtrace = debug_backtrace();
1739 // Generate the class::method string
1740 $methodName = 'UnknownClass->unknownMethod';
1741 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1742 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1745 // Construct the full message
1746 $stubMessage = sprintf('[%s:] Partial stub!',
1750 // Is the extra message given?
1751 if (!empty($message)) {
1752 // Then add it as well
1753 $stubMessage .= ' Message: ' . $message;
1756 // Debug instance is there?
1757 if (!is_null($this->getDebugInstance())) {
1758 // Output stub message
1759 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1762 trigger_error($stubMessage);
1768 * Outputs a debug backtrace and stops further script execution
1770 * @param $message An optional message to output
1771 * @param $doExit Whether exit the program (TRUE is default)
1774 public function debugBackTrace ($message = '', $doExit = TRUE) {
1775 // Sorry, there is no other way getting this nice backtrace
1776 if (!empty($message)) {
1778 printf('Message: %s<br />' . chr(10), $message);
1782 debug_print_backtrace();
1786 if ($doExit === TRUE) {
1792 * Creates an instance of a debugger instance
1794 * @param $className Name of the class (currently unsupported)
1795 * @return $debugInstance An instance of a debugger class
1797 public final static function createDebugInstance ($className) {
1798 // Is the instance set?
1799 if (!Registry::getRegistry()->instanceExists('debug')) {
1800 // Init debug instance
1801 $debugInstance = NULL;
1805 // Get a debugger instance
1806 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'));
1807 } catch (NullPointerException $e) {
1808 // Didn't work, no instance there
1809 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1812 // Empty string should be ignored and used for testing the middleware
1813 DebugMiddleware::getSelfInstance()->output('');
1815 // Set it in its own class. This will set it in the registry
1816 $debugInstance->setDebugInstance($debugInstance);
1818 // Get instance from registry
1819 $debugInstance = Registry::getRegistry()->getDebugInstance();
1823 return $debugInstance;
1827 * Simple output of a message with line-break
1829 * @param $message Message to output
1832 public function outputLine ($message) {
1834 print($message . PHP_EOL);
1838 * Outputs a debug message whether to debug instance (should be set!) or
1839 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1840 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1842 * @param $message Message we shall send out...
1843 * @param $doPrint Whether print or die here (default: print)
1844 * @paran $stripTags Whether to strip tags (default: FALSE)
1847 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1848 // Set debug instance to NULL
1849 $debugInstance = NULL;
1853 // Get debug instance
1854 $debugInstance = $this->getDebugInstance();
1855 } catch (NullPointerException $e) {
1856 // The debug instance is not set (yet)
1859 // Is the debug instance there?
1860 if (is_object($debugInstance)) {
1861 // Use debug output handler
1862 $debugInstance->output($message, $stripTags);
1864 if ($doPrint === FALSE) {
1865 // Die here if not printed
1869 // Are debug times enabled?
1870 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1872 $message = $this->getPrintableExecutionTime() . $message;
1876 if ($doPrint === TRUE) {
1878 $this->outputLine($message);
1887 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1889 * @param $str The string, what ever it is needs to be converted
1890 * @return $className Generated class name
1892 public function convertToClassName ($str) {
1896 // Convert all dashes in underscores
1897 $str = $this->convertDashesToUnderscores($str);
1899 // Now use that underscores to get classname parts for hungarian style
1900 foreach (explode('_', $str) as $strPart) {
1901 // Make the class name part lower case and first upper case
1902 $className .= ucfirst(strtolower($strPart));
1905 // Return class name
1910 * Converts dashes to underscores, e.g. useable for configuration entries
1912 * @param $str The string with maybe dashes inside
1913 * @return $str The converted string with no dashed, but underscores
1915 public final function convertDashesToUnderscores ($str) {
1917 $str = str_replace('-', '_', $str);
1919 // Return converted string
1924 * Marks up the code by adding e.g. line numbers
1926 * @param $phpCode Unmarked PHP code
1927 * @return $markedCode Marked PHP code
1929 public function markupCode ($phpCode) {
1934 $errorArray = error_get_last();
1936 // Init the code with error message
1937 if (is_array($errorArray)) {
1939 $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>',
1940 basename($errorArray['file']),
1941 $errorArray['line'],
1942 $errorArray['message'],
1947 // Add line number to the code
1948 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1950 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1952 htmlentities($code, ENT_QUOTES)
1961 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1962 * beatiful for web-based front-ends. If null is given a message id
1963 * null_timestamp will be resolved and returned.
1965 * @param $timestamp Timestamp to prepare (filter) for display
1966 * @return $readable A readable timestamp
1968 public function doFilterFormatTimestamp ($timestamp) {
1969 // Default value to return
1972 // Is the timestamp null?
1973 if (is_null($timestamp)) {
1974 // Get a message string
1975 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1977 switch ($this->getLanguageInstance()->getLanguageCode()) {
1978 case 'de': // German format is a bit different to default
1979 // Split the GMT stamp up
1980 $dateTime = explode(' ', $timestamp );
1981 $dateArray = explode('-', $dateTime[0]);
1982 $timeArray = explode(':', $dateTime[1]);
1984 // Construct the timestamp
1985 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1995 default: // Default is pass-through
1996 $readable = $timestamp;
2006 * Filter a given number into a localized number
2008 * @param $value The raw value from e.g. database
2009 * @return $localized Localized value
2011 public function doFilterFormatNumber ($value) {
2012 // Generate it from config and localize dependencies
2013 switch ($this->getLanguageInstance()->getLanguageCode()) {
2014 case 'de': // German format is a bit different to default
2015 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2018 default: // US, etc.
2019 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2028 * "Getter" for databse entry
2030 * @return $entry An array with database entries
2031 * @throws NullPointerException If the database result is not found
2032 * @throws InvalidDatabaseResultException If the database result is invalid
2034 protected final function getDatabaseEntry () {
2035 // Is there an instance?
2036 if (!$this->getResultInstance() instanceof SearchableResult) {
2037 // Throw an exception here
2038 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2042 $this->getResultInstance()->rewind();
2044 // Do we have an entry?
2045 if ($this->getResultInstance()->valid() === FALSE) {
2046 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2047 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2051 $this->getResultInstance()->next();
2054 $entry = $this->getResultInstance()->current();
2061 * Getter for field name
2063 * @param $fieldName Field name which we shall get
2064 * @return $fieldValue Field value from the user
2065 * @throws NullPointerException If the result instance is null
2067 public final function getField ($fieldName) {
2068 // Default field value
2071 // Get result instance
2072 $resultInstance = $this->getResultInstance();
2074 // Is this instance null?
2075 if (is_null($resultInstance)) {
2076 // Then the user instance is no longer valid (expired cookies?)
2077 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2080 // Get current array
2081 $fieldArray = $resultInstance->current();
2082 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2084 // Convert dashes to underscore
2085 $fieldName2 = $this->convertDashesToUnderscores($fieldName);
2087 // Does the field exist?
2088 if ($this->isFieldSet($fieldName)) {
2090 $fieldValue = $fieldArray[$fieldName2];
2091 } elseif (defined('DEVELOPER')) {
2092 // Missing field entry, may require debugging
2093 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2095 // Missing field entry, may require debugging
2096 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2104 * Checks if given field is set
2106 * @param $fieldName Field name to check
2107 * @return $isSet Whether the given field name is set
2108 * @throws NullPointerException If the result instance is null
2110 public function isFieldSet ($fieldName) {
2111 // Get result instance
2112 $resultInstance = $this->getResultInstance();
2114 // Is this instance null?
2115 if (is_null($resultInstance)) {
2116 // Then the user instance is no longer valid (expired cookies?)
2117 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2120 // Get current array
2121 $fieldArray = $resultInstance->current();
2122 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2124 // Convert dashes to underscore
2125 $fieldName = $this->convertDashesToUnderscores($fieldName);
2128 $isSet = isset($fieldArray[$fieldName]);
2135 * Flushs all pending updates to the database layer
2139 public function flushPendingUpdates () {
2140 // Get result instance
2141 $resultInstance = $this->getResultInstance();
2143 // Do we have data to update?
2144 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2145 // Get wrapper class name config entry
2146 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2148 // Create object instance
2149 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
2151 // Yes, then send the whole result to the database layer
2152 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2157 * Outputs a deprecation warning to the developer.
2159 * @param $message The message we shall output to the developer
2161 * @todo Write a logging mechanism for productive mode
2163 public function deprecationWarning ($message) {
2164 // Is developer mode active?
2165 if (defined('DEVELOPER')) {
2166 // Debug instance is there?
2167 if (!is_null($this->getDebugInstance())) {
2168 // Output stub message
2169 self::createDebugInstance(__CLASS__)->debugOutput($message);
2172 trigger_error($message . "<br />\n");
2176 // @TODO Finish this part!
2177 $this->partialStub('Developer mode inactive. Message:' . $message);
2182 * Checks whether the given PHP extension is loaded
2184 * @param $phpExtension The PHP extension we shall check
2185 * @return $isLoaded Whether the PHP extension is loaded
2187 public final function isPhpExtensionLoaded ($phpExtension) {
2189 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2196 * "Getter" as a time() replacement but with milliseconds. You should use this
2197 * method instead of the encapsulated getimeofday() function.
2199 * @return $milliTime Timestamp with milliseconds
2201 public function getMilliTime () {
2202 // Get the time of day as float
2203 $milliTime = gettimeofday(TRUE);
2210 * Idles (sleeps) for given milliseconds
2212 * @return $hasSlept Whether it goes fine
2214 public function idle ($milliSeconds) {
2215 // Sleep is fine by default
2218 // Idle so long with found function
2219 if (function_exists('time_sleep_until')) {
2220 // Get current time and add idle time
2221 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2223 // New PHP 5.1.0 function found, ignore errors
2224 $hasSlept = @time_sleep_until($sleepUntil);
2227 * My Sun station doesn't have that function even with latest PHP
2230 usleep($milliSeconds * 1000);
2237 * Converts a hexadecimal string, even with negative sign as first string to
2238 * a decimal number using BC functions.
2240 * This work is based on comment #86673 on php.net documentation page at:
2241 * <http://de.php.net/manual/en/function.dechex.php#86673>
2243 * @param $hex Hexadecimal string
2244 * @return $dec Decimal number
2246 protected function hex2dec ($hex) {
2247 // Convert to all lower-case
2248 $hex = strtolower($hex);
2250 // Detect sign (negative/positive numbers)
2252 if (substr($hex, 0, 1) == '-') {
2254 $hex = substr($hex, 1);
2257 // Decode the hexadecimal string into a decimal number
2259 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2260 $factor = self::$hexdec[substr($hex, $i, 1)];
2261 $dec = bcadd($dec, bcmul($factor, $e));
2264 // Return the decimal number
2265 return $sign . $dec;
2269 * Converts even very large decimal numbers, also signed, to a hexadecimal
2272 * This work is based on comment #97756 on php.net documentation page at:
2273 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2275 * @param $dec Decimal number, even with negative sign
2276 * @param $maxLength Optional maximum length of the string
2277 * @return $hex Hexadecimal string
2279 protected function dec2hex ($dec, $maxLength = 0) {
2280 // maxLength can be zero or devideable by 2
2281 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2283 // Detect sign (negative/positive numbers)
2290 // Encode the decimal number into a hexadecimal string
2293 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2295 } while ($dec >= 1);
2298 * Leading zeros are required for hex-decimal "numbers". In some
2299 * situations more leading zeros are wanted, so check for both
2302 if ($maxLength > 0) {
2303 // Prepend more zeros
2304 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2305 } elseif ((strlen($hex) % 2) != 0) {
2306 // Only make string's length dividable by 2
2310 // Return the hexadecimal string
2311 return $sign . $hex;
2315 * Converts a ASCII string (0 to 255) into a decimal number.
2317 * @param $asc The ASCII string to be converted
2318 * @return $dec Decimal number
2320 protected function asc2dec ($asc) {
2321 // Convert it into a hexadecimal number
2322 $hex = bin2hex($asc);
2324 // And back into a decimal number
2325 $dec = $this->hex2dec($hex);
2332 * Converts a decimal number into an ASCII string.
2334 * @param $dec Decimal number
2335 * @return $asc An ASCII string
2337 protected function dec2asc ($dec) {
2338 // First convert the number into a hexadecimal string
2339 $hex = $this->dec2hex($dec);
2341 // Then convert it into the ASCII string
2342 $asc = $this->hex2asc($hex);
2349 * Converts a hexadecimal number into an ASCII string. Negative numbers
2352 * @param $hex Hexadecimal string
2353 * @return $asc An ASCII string
2355 protected function hex2asc ($hex) {
2356 // Check for length, it must be devideable by 2
2357 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2358 assert((strlen($hex) % 2) == 0);
2362 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2363 // Get the decimal number of the chunk
2364 $part = hexdec(substr($hex, $idx, 2));
2366 // Add it to the final string
2370 // Return the final string
2375 * Checks whether the given encoded data was encoded with Base64
2377 * @param $encodedData Encoded data we shall check
2378 * @return $isBase64 Whether the encoded data is Base64
2380 protected function isBase64Encoded ($encodedData) {
2382 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2389 * "Getter" to get response/request type from analysis of the system.
2391 * @return $responseType Analyzed response type
2393 protected static function getResponseTypeFromSystem () {
2394 // Default is console
2395 $responseType = 'console';
2397 // Is 'HTTP_HOST' set?
2398 if (isset($_SERVER['HTTP_HOST'])) {
2400 * Then it is a HTML response/request as RSS and so on may be
2401 * transfered over HTTP as well.
2403 $responseType = 'html';
2407 return $responseType;
2411 * Gets a cache key from Criteria instance
2413 * @param $criteriaInstance An instance of a Criteria class
2414 * @param $onlyKeys Only use these keys for a cache key
2415 * @return $cacheKey A cache key suitable for lookup/storage purposes
2417 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2419 $cacheKey = sprintf('%s@%s',
2420 $this->__toString(),
2421 $criteriaInstance->getCacheKey($onlyKeys)
2425 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2430 * Getter for startup time in miliseconds
2432 * @return $startupTime Startup time in miliseconds
2434 protected function getStartupTime () {
2435 return self::$startupTime;
2439 * "Getter" for a printable currently execution time in nice braces
2441 * @return $executionTime Current execution time in nice braces
2443 protected function getPrintableExecutionTime () {
2444 // Caculate the execution time
2445 $executionTime = microtime(TRUE) - $this->getStartupTime();
2447 // Pack it in nice braces
2448 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2451 return $executionTime;
2455 * Hashes a given string with a simple but stronger hash function (no salt)
2456 * and hex-encode it.
2458 * @param $str The string to be hashed
2459 * @return $hash The hash from string $str
2461 public static final function hash ($str) {
2462 // Hash given string with (better secure) hasher
2463 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2470 * "Getter" for length of hash() output. This will be "cached" to speed up
2473 * @return $length Length of hash() output
2475 public static final function getHashLength () {
2477 if (is_null(self::$hashLength)) {
2478 // No, then hash a string and save its length.
2479 self::$hashLength = strlen(self::hash('abc123'));
2483 return self::$hashLength;
2487 * Checks whether the given number is really a number (only chars 0-9).
2489 * @param $num A string consisting only chars between 0 and 9
2490 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2491 * @param $assertMismatch Whether to assert mismatches
2492 * @return $ret The (hopefully) secured numbered value
2494 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2495 // Filter all numbers out
2496 $ret = preg_replace('/[^0123456789]/', '', $num);
2499 if ($castValue === TRUE) {
2500 // Cast to biggest numeric type
2501 $ret = (double) $ret;
2504 // Assert only if requested
2505 if ($assertMismatch === TRUE) {
2506 // Has the whole value changed?
2507 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2515 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2517 * @param $num A string consisting only chars between 0 and 9
2518 * @param $assertMismatch Whether to assert mismatches
2519 * @return $ret The (hopefully) secured hext-numbered value
2521 public function hexval ($num, $assertMismatch = FALSE) {
2522 // Filter all numbers out
2523 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2525 // Assert only if requested
2526 if ($assertMismatch === TRUE) {
2527 // Has the whole value changed?
2528 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2536 * Checks whether start/end marker are set
2538 * @param $data Data to be checked
2539 * @return $isset Whether start/end marker are set
2541 public final function ifStartEndMarkersSet ($data) {
2543 $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));
2545 // ... and return it
2550 * Determines if an element is set in the generic array
2552 * @param $keyGroup Main group for the key
2553 * @param $subGroup Sub group for the key
2554 * @param $key Key to check
2555 * @param $element Element to check
2556 * @return $isset Whether the given key is set
2558 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2560 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2563 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2569 * Determines if a key is set in the generic array
2571 * @param $keyGroup Main group for the key
2572 * @param $subGroup Sub group for the key
2573 * @param $key Key to check
2574 * @return $isset Whether the given key is set
2576 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2578 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2581 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2589 * Determines if a group is set in the generic array
2591 * @param $keyGroup Main group
2592 * @param $subGroup Sub group
2593 * @return $isset Whether the given group is set
2595 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2597 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2600 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2607 * Getter for sub key group
2609 * @param $keyGroup Main key group
2610 * @param $subGroup Sub key group
2611 * @return $array An array with all array elements
2613 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2615 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2616 // No, then abort here
2617 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2622 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2625 return $this->genericArray[$keyGroup][$subGroup];
2629 * Unsets a given key in generic array
2631 * @param $keyGroup Main group for the key
2632 * @param $subGroup Sub group for the key
2633 * @param $key Key to unset
2636 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2638 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2641 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2645 * Unsets a given element in generic array
2647 * @param $keyGroup Main group for the key
2648 * @param $subGroup Sub group for the key
2649 * @param $key Key to unset
2650 * @param $element Element to unset
2653 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2655 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2658 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2662 * Append a string to a given generic array key
2664 * @param $keyGroup Main group for the key
2665 * @param $subGroup Sub group for the key
2666 * @param $key Key to unset
2667 * @param $value Value to add/append
2670 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2672 //* 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);
2674 // Is it already there?
2675 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2677 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2680 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2685 * Append a string to a given generic array element
2687 * @param $keyGroup Main group for the key
2688 * @param $subGroup Sub group for the key
2689 * @param $key Key to unset
2690 * @param $element Element to check
2691 * @param $value Value to add/append
2694 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2696 //* 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);
2698 // Is it already there?
2699 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2701 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2704 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2709 * Initializes given generic array group
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 initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2719 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2721 // Is it already set?
2722 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2723 // Already initialized
2724 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2729 $this->genericArray[$keyGroup][$subGroup] = array();
2733 * Initializes given generic array key
2735 * @param $keyGroup Main group for the key
2736 * @param $subGroup Sub group for the key
2737 * @param $key Key to use
2738 * @param $forceInit Optionally force initialization
2741 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2743 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2745 // Is it already set?
2746 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2747 // Already initialized
2748 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2753 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2757 * Initializes given generic array element
2759 * @param $keyGroup Main group for the key
2760 * @param $subGroup Sub group for the key
2761 * @param $key Key to use
2762 * @param $element Element to use
2763 * @param $forceInit Optionally force initialization
2766 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2768 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2770 // Is it already set?
2771 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2772 // Already initialized
2773 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2778 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2782 * Pushes an element to a generic key
2784 * @param $keyGroup Main group for the key
2785 * @param $subGroup Sub group for the key
2786 * @param $key Key to use
2787 * @param $value Value to add/append
2788 * @return $count Number of array elements
2790 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2792 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2795 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2797 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2801 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2804 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2805 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2810 * Pushes an element to a generic array element
2812 * @param $keyGroup Main group for the key
2813 * @param $subGroup Sub group for the key
2814 * @param $key Key to use
2815 * @param $element Element to check
2816 * @param $value Value to add/append
2817 * @return $count Number of array elements
2819 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2821 //* 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));
2824 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2826 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2830 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2833 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2834 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2839 * Pops an element from a generic group
2841 * @param $keyGroup Main group for the key
2842 * @param $subGroup Sub group for the key
2843 * @param $key Key to unset
2844 * @return $value Last "popped" value
2846 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2848 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2851 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2853 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2858 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2861 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2862 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2867 * Shifts an element from a generic group
2869 * @param $keyGroup Main group for the key
2870 * @param $subGroup Sub group for the key
2871 * @param $key Key to unset
2872 * @return $value Last "popped" value
2874 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2876 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2879 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2881 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2886 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2889 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2890 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2895 * Count generic array group
2897 * @param $keyGroup Main group for the key
2898 * @return $count Count of given group
2900 protected final function countGenericArray ($keyGroup) {
2902 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2905 if (!isset($this->genericArray[$keyGroup])) {
2907 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2912 $count = count($this->genericArray[$keyGroup]);
2915 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2922 * Count generic array sub group
2924 * @param $keyGroup Main group for the key
2925 * @param $subGroup Sub group for the key
2926 * @return $count Count of given group
2928 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2930 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2933 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2935 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2940 $count = count($this->genericArray[$keyGroup][$subGroup]);
2943 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2950 * Count generic array elements
2952 * @param $keyGroup Main group for the key
2953 * @param $subGroup Sub group for the key
2954 * @para $key Key to count
2955 * @return $count Count of given key
2957 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2959 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2962 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2964 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2966 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2968 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2973 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2976 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2983 * Getter for whole generic group array
2985 * @param $keyGroup Key group to get
2986 * @return $array Whole generic array group
2988 protected final function getGenericArray ($keyGroup) {
2990 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2993 if (!isset($this->genericArray[$keyGroup])) {
2995 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3000 return $this->genericArray[$keyGroup];
3004 * Setter for generic array key
3006 * @param $keyGroup Key group to get
3007 * @param $subGroup Sub group for the key
3008 * @param $key Key to unset
3009 * @param $value Mixed value from generic array element
3012 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3014 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3017 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3021 * Getter for generic array key
3023 * @param $keyGroup Key group to get
3024 * @param $subGroup Sub group for the key
3025 * @param $key Key to unset
3026 * @return $value Mixed value from generic array element
3028 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3030 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3033 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3035 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3040 return $this->genericArray[$keyGroup][$subGroup][$key];
3044 * Sets a value in given generic array key/element
3046 * @param $keyGroup Main group for the key
3047 * @param $subGroup Sub group for the key
3048 * @param $key Key to set
3049 * @param $element Element to set
3050 * @param $value Value to set
3053 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3055 //* 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));
3058 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3062 * Getter for generic array element
3064 * @param $keyGroup Key group to get
3065 * @param $subGroup Sub group for the key
3066 * @param $key Key to look for
3067 * @param $element Element to look for
3068 * @return $value Mixed value from generic array element
3070 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3072 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3075 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3077 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3082 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3086 * Checks if a given sub group is valid (array)
3088 * @param $keyGroup Key group to get
3089 * @param $subGroup Sub group for the key
3090 * @return $isValid Whether given sub group is valid
3092 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3094 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3097 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3104 * Checks if a given key is valid (array)
3106 * @param $keyGroup Key group to get
3107 * @param $subGroup Sub group for the key
3108 * @param $key Key to check
3109 * @return $isValid Whether given sub group is valid
3111 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3113 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3116 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3123 * Initializes the web output instance
3127 protected function initWebOutputInstance () {
3128 // Get application instance
3129 $applicationInstance = Registry::getRegistry()->getInstance('app');
3131 // Is this a response instance?
3132 if ($this instanceof Responseable) {
3133 // Then set it in application instance
3134 $applicationInstance->setResponseInstance($this);
3137 // Init web output instance
3138 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3141 $this->setWebOutputInstance($outputInstance);
3145 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3147 * @param $boolean Boolean value
3148 * @return $translated Translated boolean value
3150 public static final function translateBooleanToYesNo ($boolean) {
3151 // Make sure it is really boolean
3152 assert(is_bool($boolean));
3155 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3157 // ... and return it
3162 * Encodes raw data (almost any type) by "serializing" it and then pack it
3163 * into a "binary format".
3165 * @param $rawData Raw data (almost any type)
3166 * @return $encoded Encoded data
3168 protected function encodeData ($rawData) {
3169 // Make sure no objects or resources pass through
3170 assert(!is_object($rawData));
3171 assert(!is_resource($rawData));
3173 // First "serialize" it (json_encode() is faster than serialize())
3174 $encoded = $this->packString(json_encode($rawData));
3181 * Pack a string into a "binary format". Please execuse me that this is
3182 * widely undocumented. :-(
3184 * @param $str Unpacked string
3185 * @return $packed Packed string
3186 * @todo Improve documentation
3188 protected function packString ($str) {
3190 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3192 // First compress the string (gzcompress is okay)
3193 $str = gzcompress($str);
3198 // And start the "encoding" loop
3199 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3201 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3202 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3204 if (($idx + $i) <= strlen($str)) {
3205 $ord = ord(substr($str, ($idx + $i), 1));
3207 $add = $ord * pow(256, $factor);
3211 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3215 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3216 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3218 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3219 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3225 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');