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;
224 private $stateInstance = NULL;
227 * Thousands separator
229 private $thousands = '.'; // German
234 private $decimals = ','; // German
239 private $socketResource = FALSE;
242 * Regular expression to use for validation
244 private $regularExpression = '';
249 private $packageData = array();
254 private $genericArray = array();
259 private $commandName = '';
264 private $controllerName = '';
267 * Name of used protocol
269 private $protocolName = 'invalid';
272 * Array with bitmasks and such for pack/unpack methods to support both
273 * 32-bit and 64-bit systems
275 private $packingData = array(
278 'left' => 0xffff0000,
279 'right' => 0x0000ffff,
285 'left' => 0xffffffff00000000,
286 'right' => 0x00000000ffffffff,
293 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
295 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
297 private $archArrayElement = FALSE;
299 /***********************
300 * Exception codes.... *
301 ***********************/
303 // @todo Try to clean these constants up
304 const EXCEPTION_IS_NULL_POINTER = 0x001;
305 const EXCEPTION_IS_NO_OBJECT = 0x002;
306 const EXCEPTION_IS_NO_ARRAY = 0x003;
307 const EXCEPTION_MISSING_METHOD = 0x004;
308 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
309 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
310 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
311 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
312 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
313 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
314 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
315 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
316 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
317 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
318 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
319 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
320 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
321 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
322 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
323 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
324 const EXCEPTION_PATH_NOT_FOUND = 0x015;
325 const EXCEPTION_INVALID_PATH_NAME = 0x016;
326 const EXCEPTION_READ_PROTECED_PATH = 0x017;
327 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
328 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
329 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
330 const EXCEPTION_INVALID_RESOURCE = 0x01b;
331 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
332 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
333 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
334 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
335 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
336 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
337 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
338 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
339 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
340 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
341 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
342 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
343 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
344 const EXCEPTION_INVALID_STRING = 0x029;
345 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
346 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
347 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
348 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
349 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
350 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
351 const EXCEPTION_MISSING_ELEMENT = 0x030;
352 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
353 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
354 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
355 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
356 const EXCEPTION_FATAL_ERROR = 0x035;
357 const EXCEPTION_FILE_NOT_FOUND = 0x036;
358 const EXCEPTION_ASSERTION_FAILED = 0x037;
359 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
360 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
361 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
362 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
363 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
364 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
367 * Hexadecimal->Decimal translation array
369 private static $hexdec = array(
389 * Decimal->hexadecimal translation array
391 private static $dechex = array(
411 * Startup time in miliseconds
413 private static $startupTime = 0;
416 * Protected super constructor
418 * @param $className Name of the class
421 protected function __construct ($className) {
423 $this->setRealClass($className);
425 // Set configuration instance if no registry ...
426 if (!$this instanceof Register) {
427 // ... because registries doesn't need to be configured
428 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
431 // Is the startup time set? (0 cannot be TRUE anymore)
432 if (self::$startupTime == 0) {
434 self::$startupTime = microtime(TRUE);
438 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
442 * Destructor for all classes
446 public function __destruct () {
447 // Flush any updated entries to the database
448 $this->flushPendingUpdates();
450 // Is this object already destroyed?
451 if ($this->__toString() != 'DestructedObject') {
452 // Destroy all informations about this class but keep some text about it alive
453 $this->setRealClass('DestructedObject');
454 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
455 // Already destructed object
456 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
461 // Do not call this twice
462 trigger_error(__METHOD__ . ': Called twice.');
468 * The __call() method where all non-implemented methods end up
470 * @param $methodName Name of the missing method
471 * @args $args Arguments passed to the method
474 public final function __call ($methodName, $args) {
475 return self::__callStatic($methodName, $args);
479 * The __callStatic() method where all non-implemented static methods end up
481 * @param $methodName Name of the missing method
482 * @args $args Arguments passed to the method
485 public static final function __callStatic ($methodName, $args) {
486 // Init argument string
489 // Is it NULL, empty or an array?
490 if (is_null($args)) {
492 $argsString = 'NULL';
493 } elseif (empty($args)) {
495 $argsString = '(empty)';
496 } elseif (is_array($args)) {
497 // Some arguments are there
498 foreach ($args as $arg) {
499 // Add the value itself if not array. This prevents 'array to string conversion' message
500 if (is_array($arg)) {
501 $argsString .= 'Array';
506 // Add data about the argument
507 $argsString .= ' (' . gettype($arg);
509 if (is_string($arg)) {
510 // Add length for strings
511 $argsString .= ', ' . strlen($arg);
512 } elseif (is_array($arg)) {
513 // .. or size if array
514 $argsString .= ', ' . count($arg);
515 } elseif ($arg === TRUE) {
516 // ... is boolean 'TRUE'
517 $argsString .= ', TRUE';
518 } elseif ($arg === FALSE) {
519 // ... is boolean 'FALSE'
520 $argsString .= ', FALSE';
524 $argsString .= '), ';
528 if (substr($argsString, -2, 1) == ',') {
529 $argsString = substr($argsString, 0, -2);
532 // Invalid arguments!
533 $argsString = '!INVALID:' . gettype($args) . '!';
536 // Output stub message
537 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
538 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
548 * Getter for $realClass
550 * @return $realClass The name of the real class (not BaseFrameworkSystem)
552 public function __toString () {
553 return $this->realClass;
557 * Magic method to catch setting of missing but set class fields/attributes
559 * @param $name Name of the field/attribute
560 * @param $value Value to store
563 public final function __set ($name, $value) {
564 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
567 print_r($value, TRUE)
572 * Magic method to catch getting of missing fields/attributes
574 * @param $name Name of the field/attribute
577 public final function __get ($name) {
578 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
584 * Magic method to catch unsetting of missing fields/attributes
586 * @param $name Name of the field/attribute
589 public final function __unset ($name) {
590 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
596 * Magic method to catch object serialization
598 * @return $unsupported Unsupported method
599 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
601 public final function __sleep () {
602 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
606 * Magic method to catch object deserialization
608 * @return $unsupported Unsupported method
609 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
611 public final function __wakeup () {
612 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
616 * Magic method to catch calls when an object instance is called
618 * @return $unsupported Unsupported method
619 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
621 public final function __invoke () {
622 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
626 * Setter for the real class name
628 * @param $realClass Class name (string)
631 public final function setRealClass ($realClass) {
633 $this->realClass = (string) $realClass;
637 * Setter for database result instance
639 * @param $resultInstance An instance of a database result class
641 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
643 protected final function setResultInstance (SearchableResult $resultInstance) {
644 $this->resultInstance = $resultInstance;
648 * Getter for database result instance
650 * @return $resultInstance An instance of a database result class
652 public final function getResultInstance () {
653 return $this->resultInstance;
657 * Setter for template engine instances
659 * @param $templateInstance An instance of a template engine class
662 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
663 $this->templateInstance = $templateInstance;
667 * Getter for template engine instances
669 * @return $templateInstance An instance of a template engine class
671 protected final function getTemplateInstance () {
672 return $this->templateInstance;
676 * Setter for search instance
678 * @param $searchInstance Searchable criteria instance
681 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
682 $this->searchInstance = $searchInstance;
686 * Getter for search instance
688 * @return $searchInstance Searchable criteria instance
690 public final function getSearchInstance () {
691 return $this->searchInstance;
695 * Setter for update instance
697 * @param $updateInstance Searchable criteria instance
700 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
701 $this->updateInstance = $updateInstance;
705 * Getter for update instance
707 * @return $updateInstance Updateable criteria instance
709 public final function getUpdateInstance () {
710 return $this->updateInstance;
714 * Setter for resolver instance
716 * @param $resolverInstance Instance of a command resolver class
719 public final function setResolverInstance (Resolver $resolverInstance) {
720 $this->resolverInstance = $resolverInstance;
724 * Getter for resolver instance
726 * @return $resolverInstance Instance of a command resolver class
728 public final function getResolverInstance () {
729 return $this->resolverInstance;
733 * Setter for language instance
735 * @param $configInstance The configuration instance which shall
736 * be FrameworkConfiguration
739 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
740 Registry::getRegistry()->addInstance('config', $configInstance);
744 * Getter for configuration instance
746 * @return $configInstance Configuration instance
748 public final function getConfigInstance () {
749 $configInstance = Registry::getRegistry()->getInstance('config');
750 return $configInstance;
754 * Setter for debug instance
756 * @param $debugInstance The instance for debug output class
759 public final function setDebugInstance (DebugMiddleware $debugInstance) {
760 Registry::getRegistry()->addInstance('debug', $debugInstance);
764 * Getter for debug instance
766 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
768 public final function getDebugInstance () {
769 // Get debug instance
770 $debugInstance = Registry::getRegistry()->getInstance('debug');
773 return $debugInstance;
777 * Setter for web output instance
779 * @param $webInstance The instance for web output class
782 public final function setWebOutputInstance (OutputStreamer $webInstance) {
783 Registry::getRegistry()->addInstance('web_output', $webInstance);
787 * Getter for web output instance
789 * @return $webOutputInstance - Instance to class WebOutput
791 public final function getWebOutputInstance () {
792 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
793 return $webOutputInstance;
797 * Setter for database instance
799 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
802 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
803 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
807 * Getter for database layer
809 * @return $databaseInstance The database layer instance
811 public final function getDatabaseInstance () {
813 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
816 return $databaseInstance;
820 * Setter for compressor channel
822 * @param $compressorInstance An instance of CompressorChannel
825 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
826 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
830 * Getter for compressor channel
832 * @return $compressorInstance The compressor channel
834 public final function getCompressorChannel () {
835 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
836 return $compressorInstance;
840 * Protected getter for a manageable application helper class
842 * @return $applicationInstance An instance of a manageable application helper class
844 protected final function getApplicationInstance () {
845 $applicationInstance = Registry::getRegistry()->getInstance('application');
846 return $applicationInstance;
850 * Setter for a manageable application helper class
852 * @param $applicationInstance An instance of a manageable application helper class
855 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
856 Registry::getRegistry()->addInstance('application', $applicationInstance);
860 * Setter for request instance
862 * @param $requestInstance An instance of a Requestable class
865 public final function setRequestInstance (Requestable $requestInstance) {
866 $this->requestInstance = $requestInstance;
870 * Getter for request instance
872 * @return $requestInstance An instance of a Requestable class
874 public final function getRequestInstance () {
875 return $this->requestInstance;
879 * Setter for response instance
881 * @param $responseInstance An instance of a Responseable class
884 public final function setResponseInstance (Responseable $responseInstance) {
885 $this->responseInstance = $responseInstance;
889 * Getter for response instance
891 * @return $responseInstance An instance of a Responseable class
893 public final function getResponseInstance () {
894 return $this->responseInstance;
898 * Private getter for language instance
900 * @return $langInstance An instance to the language sub-system
902 protected final function getLanguageInstance () {
903 $langInstance = Registry::getRegistry()->getInstance('language');
904 return $langInstance;
908 * Setter for language instance
910 * @param $langInstance An instance to the language sub-system
912 * @see LanguageSystem
914 public final function setLanguageInstance (ManageableLanguage $langInstance) {
915 Registry::getRegistry()->addInstance('language', $langInstance);
919 * Private getter for file IO instance
921 * @return $fileIoInstance An instance to the file I/O sub-system
923 protected final function getFileIoInstance () {
924 return $this->fileIoInstance;
928 * Setter for file I/O instance
930 * @param $fileIoInstance An instance to the file I/O sub-system
933 public final function setFileIoInstance (IoHandler $fileIoInstance) {
934 $this->fileIoInstance = $fileIoInstance;
938 * Protected setter for user instance
940 * @param $userInstance An instance of a user class
943 protected final function setUserInstance (ManageableAccount $userInstance) {
944 $this->userInstance = $userInstance;
948 * Getter for user instance
950 * @return $userInstance An instance of a user class
952 public final function getUserInstance () {
953 return $this->userInstance;
957 * Setter for controller instance (this surely breaks a bit the MVC patterm)
959 * @param $controllerInstance An instance of the controller
962 public final function setControllerInstance (Controller $controllerInstance) {
963 $this->controllerInstance = $controllerInstance;
967 * Getter for controller instance (this surely breaks a bit the MVC patterm)
969 * @return $controllerInstance An instance of the controller
971 public final function getControllerInstance () {
972 return $this->controllerInstance;
976 * Setter for RNG instance
978 * @param $rngInstance An instance of a random number generator (RNG)
981 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
982 $this->rngInstance = $rngInstance;
986 * Getter for RNG instance
988 * @return $rngInstance An instance of a random number generator (RNG)
990 public final function getRngInstance () {
991 return $this->rngInstance;
995 * Setter for Cryptable instance
997 * @param $cryptoInstance An instance of a Cryptable class
1000 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1001 $this->cryptoInstance = $cryptoInstance;
1005 * Getter for Cryptable instance
1007 * @return $cryptoInstance An instance of a Cryptable class
1009 public final function getCryptoInstance () {
1010 return $this->cryptoInstance;
1014 * Setter for the list instance
1016 * @param $listInstance A list of Listable
1019 protected final function setListInstance (Listable $listInstance) {
1020 $this->listInstance = $listInstance;
1024 * Getter for the list instance
1026 * @return $listInstance A list of Listable
1028 protected final function getListInstance () {
1029 return $this->listInstance;
1033 * Setter for the menu instance
1035 * @param $menuInstance A RenderableMenu instance
1038 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1039 $this->menuInstance = $menuInstance;
1043 * Getter for the menu instance
1045 * @return $menuInstance A RenderableMenu instance
1047 protected final function getMenuInstance () {
1048 return $this->menuInstance;
1052 * Setter for image instance
1054 * @param $imageInstance An instance of an image
1057 public final function setImageInstance (BaseImage $imageInstance) {
1058 $this->imageInstance = $imageInstance;
1062 * Getter for image instance
1064 * @return $imageInstance An instance of an image
1066 public final function getImageInstance () {
1067 return $this->imageInstance;
1071 * Setter for stacker instance
1073 * @param $stackInstance An instance of an stacker
1076 public final function setStackInstance (Stackable $stackInstance) {
1077 $this->stackInstance = $stackInstance;
1081 * Getter for stacker instance
1083 * @return $stackInstance An instance of an stacker
1085 public final function getStackInstance () {
1086 return $this->stackInstance;
1090 * Setter for compressor instance
1092 * @param $compressorInstance An instance of an compressor
1095 public final function setCompressorInstance (Compressor $compressorInstance) {
1096 $this->compressorInstance = $compressorInstance;
1100 * Getter for compressor instance
1102 * @return $compressorInstance An instance of an compressor
1104 public final function getCompressorInstance () {
1105 return $this->compressorInstance;
1109 * Setter for Parseable instance
1111 * @param $parserInstance An instance of an Parseable
1114 public final function setParserInstance (Parseable $parserInstance) {
1115 $this->parserInstance = $parserInstance;
1119 * Getter for Parseable instance
1121 * @return $parserInstance An instance of an Parseable
1123 public final function getParserInstance () {
1124 return $this->parserInstance;
1128 * Setter for HandleableProtocol instance
1130 * @param $protocolInstance An instance of an HandleableProtocol
1133 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1134 $this->protocolInstance = $protocolInstance;
1138 * Getter for HandleableProtocol instance
1140 * @return $protocolInstance An instance of an HandleableProtocol
1142 public final function getProtocolInstance () {
1143 return $this->protocolInstance;
1147 * Setter for DatabaseWrapper instance
1149 * @param $wrapperInstance An instance of an DatabaseWrapper
1152 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1153 $this->wrapperInstance = $wrapperInstance;
1157 * Getter for DatabaseWrapper instance
1159 * @return $wrapperInstance An instance of an DatabaseWrapper
1161 public final function getWrapperInstance () {
1162 return $this->wrapperInstance;
1166 * Setter for socket resource
1168 * @param $socketResource A valid socket resource
1171 public final function setSocketResource ($socketResource) {
1172 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1173 $this->socketResource = $socketResource;
1177 * Getter for socket resource
1179 * @return $socketResource A valid socket resource
1181 public final function getSocketResource () {
1182 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1183 return $this->socketResource;
1187 * Setter for regular expression
1189 * @param $regularExpression A valid regular expression
1192 public final function setRegularExpression ($regularExpression) {
1193 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1194 $this->regularExpression = $regularExpression;
1198 * Getter for regular expression
1200 * @return $regularExpression A valid regular expression
1202 public final function getRegularExpression () {
1203 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1204 return $this->regularExpression;
1208 * Setter for helper instance
1210 * @param $helperInstance An instance of a helper class
1213 protected final function setHelperInstance (Helper $helperInstance) {
1214 $this->helperInstance = $helperInstance;
1218 * Getter for helper instance
1220 * @return $helperInstance An instance of a helper class
1222 public final function getHelperInstance () {
1223 return $this->helperInstance;
1227 * Setter for a Source instance
1229 * @param $sourceInstance An instance of a Source class
1232 protected final function setSourceInstance (Source $sourceInstance) {
1233 $this->sourceInstance = $sourceInstance;
1237 * Getter for a Source instance
1239 * @return $sourceInstance An instance of a Source class
1241 protected final function getSourceInstance () {
1242 return $this->sourceInstance;
1246 * Setter for a UrlSource instance
1248 * @param $sourceInstance An instance of a UrlSource class
1251 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1252 $this->urlSourceInstance = $urlSourceInstance;
1256 * Getter for a UrlSource instance
1258 * @return $urlSourceInstance An instance of a UrlSource class
1260 protected final function getUrlSourceInstance () {
1261 return $this->urlSourceInstance;
1265 * Getter for a InputStream instance
1267 * @param $inputStreamInstance The InputStream instance
1269 protected final function getInputStreamInstance () {
1270 return $this->inputStreamInstance;
1274 * Setter for a InputStream instance
1276 * @param $inputStreamInstance The InputStream instance
1279 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1280 $this->inputStreamInstance = $inputStreamInstance;
1284 * Getter for a OutputStream instance
1286 * @param $outputStreamInstance The OutputStream instance
1288 protected final function getOutputStreamInstance () {
1289 return $this->outputStreamInstance;
1293 * Setter for a OutputStream instance
1295 * @param $outputStreamInstance The OutputStream instance
1298 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1299 $this->outputStreamInstance = $outputStreamInstance;
1303 * Setter for handler instance
1305 * @param $handlerInstance An instance of a Handleable class
1308 protected final function setHandlerInstance (Handleable $handlerInstance) {
1309 $this->handlerInstance = $handlerInstance;
1313 * Getter for handler instance
1315 * @return $handlerInstance A Networkable instance
1317 protected final function getHandlerInstance () {
1318 return $this->handlerInstance;
1322 * Setter for visitor instance
1324 * @param $visitorInstance A Visitor instance
1327 protected final function setVisitorInstance (Visitor $visitorInstance) {
1328 $this->visitorInstance = $visitorInstance;
1332 * Getter for visitor instance
1334 * @return $visitorInstance A Visitor instance
1336 protected final function getVisitorInstance () {
1337 return $this->visitorInstance;
1341 * Setter for DHT instance
1343 * @param $dhtInstance A Distributable instance
1346 protected final function setDhtInstance (Distributable $dhtInstance) {
1347 $this->dhtInstance = $dhtInstance;
1351 * Getter for DHT instance
1353 * @return $dhtInstance A Distributable instance
1355 protected final function getDhtInstance () {
1356 return $this->dhtInstance;
1360 * Setter for raw package Data
1362 * @param $packageData Raw package Data
1365 public final function setPackageData (array $packageData) {
1366 $this->packageData = $packageData;
1370 * Getter for raw package Data
1372 * @return $packageData Raw package Data
1374 public function getPackageData () {
1375 return $this->packageData;
1380 * Setter for Iterator instance
1382 * @param $iteratorInstance An instance of an Iterator
1385 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1386 $this->iteratorInstance = $iteratorInstance;
1390 * Getter for Iterator instance
1392 * @return $iteratorInstance An instance of an Iterator
1394 public final function getIteratorInstance () {
1395 return $this->iteratorInstance;
1399 * Setter for FilePointer instance
1401 * @param $pointerInstance An instance of an FilePointer class
1404 protected final function setPointerInstance (FilePointer $pointerInstance) {
1405 $this->pointerInstance = $pointerInstance;
1409 * Getter for FilePointer instance
1411 * @return $pointerInstance An instance of an FilePointer class
1413 public final function getPointerInstance () {
1414 return $this->pointerInstance;
1418 * Unsets pointer instance which triggers a call of __destruct() if the
1419 * instance is still there. This is surely not fatal on already "closed"
1420 * file pointer instances.
1422 * I don't want to mess around with above setter by giving it a default
1423 * value NULL as setter should always explicitly only set (existing) object
1424 * instances and NULL is NULL.
1428 protected final function unsetPointerInstance () {
1429 // Simply it to NULL
1430 $this->pointerInstance = NULL;
1434 * Setter for Indexable instance
1436 * @param $indexInstance An instance of an Indexable class
1439 protected final function setIndexInstance (Indexable $indexInstance) {
1440 $this->indexInstance = $indexInstance;
1444 * Getter for Indexable instance
1446 * @return $indexInstance An instance of an Indexable class
1448 public final function getIndexInstance () {
1449 return $this->indexInstance;
1453 * Setter for Block instance
1455 * @param $blockInstance An instance of an Block class
1458 protected final function setBlockInstance (Block $blockInstance) {
1459 $this->blockInstance = $blockInstance;
1463 * Getter for Block instance
1465 * @return $blockInstance An instance of an Block class
1467 public final function getBlockInstance () {
1468 return $this->blockInstance;
1472 * Setter for Minable instance
1474 * @param $minableInstance A Minable instance
1477 protected final function setMinableInstance (Minable $minableInstance) {
1478 $this->minableInstance = $minableInstance;
1482 * Getter for minable instance
1484 * @return $minableInstance A Minable instance
1486 protected final function getMinableInstance () {
1487 return $this->minableInstance;
1491 * Setter for FrameworkDirectory instance
1493 * @param $directoryInstance A FrameworkDirectoryPointer instance
1496 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1497 $this->directoryInstance = $directoryInstance;
1501 * Getter for FrameworkDirectory instance
1503 * @return $directoryInstance A FrameworkDirectory instance
1505 protected final function getDirectoryInstance () {
1506 return $this->directoryInstance;
1510 * Setter for listener instance
1512 * @param $listenerInstance A Listenable instance
1515 protected final function setListenerInstance (Listenable $listenerInstance) {
1516 $this->listenerInstance = $listenerInstance;
1520 * Getter for listener instance
1522 * @return $listenerInstance A Listenable instance
1524 protected final function getListenerInstance () {
1525 return $this->listenerInstance;
1529 * Getter for communicator instance
1531 * @return $communicatorInstance An instance of a Communicator class
1533 public final function getCommunicatorInstance () {
1534 return $this->communicatorInstance;
1538 * Setter for communicator instance
1540 * @param $communicatorInstance An instance of a Communicator class
1543 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1544 $this->communicatorInstance = $communicatorInstance;
1548 * Setter for state instance
1550 * @param $stateInstance A Stateable instance
1553 public final function setStateInstance (Stateable $stateInstance) {
1554 $this->stateInstance = $stateInstance;
1558 * Getter for state instance
1560 * @return $stateInstance A Stateable instance
1562 public final function getStateInstance () {
1563 return $this->stateInstance;
1567 * Setter for command name
1569 * @param $commandName Last validated command name
1572 protected final function setCommandName ($commandName) {
1573 $this->commandName = $commandName;
1577 * Getter for command name
1579 * @return $commandName Last validated command name
1581 protected final function getCommandName () {
1582 return $this->commandName;
1586 * Setter for controller name
1588 * @param $controllerName Last validated controller name
1591 protected final function setControllerName ($controllerName) {
1592 $this->controllerName = $controllerName;
1596 * Getter for controller name
1598 * @return $controllerName Last validated controller name
1600 protected final function getControllerName () {
1601 return $this->controllerName;
1605 * Getter for protocol name
1607 * @return $protocolName Name of used protocol
1609 public final function getProtocolName () {
1610 return $this->protocolName;
1614 * Setter for protocol name
1616 * @param $protocolName Name of used protocol
1619 protected final function setProtocolName ($protocolName) {
1620 $this->protocolName = $protocolName;
1624 * Checks whether an object equals this object. You should overwrite this
1625 * method to implement own equality checks
1627 * @param $objectInstance An instance of a FrameworkInterface object
1628 * @return $equals Whether both objects equals
1630 public function equals (FrameworkInterface $objectInstance) {
1633 $this->__toString() == $objectInstance->__toString()
1635 $this->hashCode() == $objectInstance->hashCode()
1638 // Return the result
1643 * Generates a generic hash code of this class. You should really overwrite
1644 * this method with your own hash code generator code. But keep KISS in mind.
1646 * @return $hashCode A generic hash code respresenting this whole class
1648 public function hashCode () {
1650 return crc32($this->__toString());
1654 * Formats computer generated price values into human-understandable formats
1655 * with thousand and decimal separators.
1657 * @param $value The in computer format value for a price
1658 * @param $currency The currency symbol (use HTML-valid characters!)
1659 * @param $decNum Number of decimals after commata
1660 * @return $price The for the current language formated price string
1661 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1662 * thousands separator
1665 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1666 // Are all required attriutes set?
1667 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1668 // Throw an exception
1669 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1673 $value = (float) $value;
1675 // Reformat the US number
1676 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1678 // Return as string...
1683 * Appends a trailing slash to a string
1685 * @param $str A string (maybe) without trailing slash
1686 * @return $str A string with an auto-appended trailing slash
1688 public final function addMissingTrailingSlash ($str) {
1689 // Is there a trailing slash?
1690 if (substr($str, -1, 1) != '/') {
1694 // Return string with trailing slash
1699 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1700 * application helper instance (ApplicationHelper by default).
1702 * @param $applicationInstance An application helper instance or
1703 * null if we shall use the default
1704 * @return $templateInstance The template engine instance
1705 * @throws NullPointerException If the discovered application
1706 * instance is still null
1708 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1709 // Is the application instance set?
1710 if (is_null($applicationInstance)) {
1711 // Get the current instance
1712 $applicationInstance = $this->getApplicationInstance();
1715 if (is_null($applicationInstance)) {
1716 // Thrown an exception
1717 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1721 // Initialize the template engine
1722 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1724 // Return the prepared instance
1725 return $templateInstance;
1729 * Debugs this instance by putting out it's full content
1731 * @param $message Optional message to show in debug output
1734 public final function debugInstance ($message = '') {
1735 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1736 restore_error_handler();
1741 // Is a message set?
1742 if (!empty($message)) {
1743 // Construct message
1744 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1747 // Generate the output
1748 $content .= sprintf('<pre>%s</pre>',
1751 print_r($this, TRUE)
1757 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>',
1758 $this->__toString(),
1760 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1765 * Replaces control characters with printable output
1767 * @param $str String with control characters
1768 * @return $str Replaced string
1770 protected function replaceControlCharacters ($str) {
1773 chr(13), '[r]', str_replace(
1774 chr(10), '[n]', str_replace(
1784 * Output a partial stub message for the caller method
1786 * @param $message An optional message to display
1789 protected function partialStub ($message = '') {
1790 // Get the backtrace
1791 $backtrace = debug_backtrace();
1793 // Generate the class::method string
1794 $methodName = 'UnknownClass->unknownMethod';
1795 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1796 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1799 // Construct the full message
1800 $stubMessage = sprintf('[%s:] Partial stub!',
1804 // Is the extra message given?
1805 if (!empty($message)) {
1806 // Then add it as well
1807 $stubMessage .= ' Message: ' . $message;
1810 // Debug instance is there?
1811 if (!is_null($this->getDebugInstance())) {
1812 // Output stub message
1813 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1816 trigger_error($stubMessage);
1822 * Outputs a debug backtrace and stops further script execution
1824 * @param $message An optional message to output
1825 * @param $doExit Whether exit the program (TRUE is default)
1828 public function debugBackTrace ($message = '', $doExit = TRUE) {
1829 // Sorry, there is no other way getting this nice backtrace
1830 if (!empty($message)) {
1832 printf('Message: %s<br />' . chr(10), $message);
1836 debug_print_backtrace();
1840 if ($doExit === TRUE) {
1846 * Creates an instance of a debugger instance
1848 * @param $className Name of the class (currently unsupported)
1849 * @return $debugInstance An instance of a debugger class
1851 public final static function createDebugInstance ($className) {
1852 // Is the instance set?
1853 if (!Registry::getRegistry()->instanceExists('debug')) {
1854 // Init debug instance
1855 $debugInstance = NULL;
1859 // Get a debugger instance
1860 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'));
1861 } catch (NullPointerException $e) {
1862 // Didn't work, no instance there
1863 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1866 // Empty string should be ignored and used for testing the middleware
1867 DebugMiddleware::getSelfInstance()->output('');
1869 // Set it in its own class. This will set it in the registry
1870 $debugInstance->setDebugInstance($debugInstance);
1872 // Get instance from registry
1873 $debugInstance = Registry::getRegistry()->getDebugInstance();
1877 return $debugInstance;
1881 * Simple output of a message with line-break
1883 * @param $message Message to output
1886 public function outputLine ($message) {
1888 print($message . PHP_EOL);
1892 * Outputs a debug message whether to debug instance (should be set!) or
1893 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1894 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1896 * @param $message Message we shall send out...
1897 * @param $doPrint Whether print or die here (default: print)
1898 * @paran $stripTags Whether to strip tags (default: FALSE)
1901 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1902 // Set debug instance to NULL
1903 $debugInstance = NULL;
1907 // Get debug instance
1908 $debugInstance = $this->getDebugInstance();
1909 } catch (NullPointerException $e) {
1910 // The debug instance is not set (yet)
1913 // Is the debug instance there?
1914 if (is_object($debugInstance)) {
1915 // Use debug output handler
1916 $debugInstance->output($message, $stripTags);
1918 if ($doPrint === FALSE) {
1919 // Die here if not printed
1923 // Are debug times enabled?
1924 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1926 $message = $this->getPrintableExecutionTime() . $message;
1930 if ($doPrint === TRUE) {
1932 $this->outputLine($message);
1941 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1943 * @param $str The string, what ever it is needs to be converted
1944 * @return $className Generated class name
1946 public static final function convertToClassName ($str) {
1950 // Convert all dashes in underscores
1951 $str = self::convertDashesToUnderscores($str);
1953 // Now use that underscores to get classname parts for hungarian style
1954 foreach (explode('_', $str) as $strPart) {
1955 // Make the class name part lower case and first upper case
1956 $className .= ucfirst(strtolower($strPart));
1959 // Return class name
1964 * Converts dashes to underscores, e.g. useable for configuration entries
1966 * @param $str The string with maybe dashes inside
1967 * @return $str The converted string with no dashed, but underscores
1969 public static final function convertDashesToUnderscores ($str) {
1971 $str = str_replace('-', '_', $str);
1973 // Return converted string
1978 * Marks up the code by adding e.g. line numbers
1980 * @param $phpCode Unmarked PHP code
1981 * @return $markedCode Marked PHP code
1983 public function markupCode ($phpCode) {
1988 $errorArray = error_get_last();
1990 // Init the code with error message
1991 if (is_array($errorArray)) {
1993 $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>',
1994 basename($errorArray['file']),
1995 $errorArray['line'],
1996 $errorArray['message'],
2001 // Add line number to the code
2002 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2004 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
2006 htmlentities($code, ENT_QUOTES)
2015 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2016 * beatiful for web-based front-ends. If null is given a message id
2017 * null_timestamp will be resolved and returned.
2019 * @param $timestamp Timestamp to prepare (filter) for display
2020 * @return $readable A readable timestamp
2022 public function doFilterFormatTimestamp ($timestamp) {
2023 // Default value to return
2026 // Is the timestamp null?
2027 if (is_null($timestamp)) {
2028 // Get a message string
2029 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2031 switch ($this->getLanguageInstance()->getLanguageCode()) {
2032 case 'de': // German format is a bit different to default
2033 // Split the GMT stamp up
2034 $dateTime = explode(' ', $timestamp );
2035 $dateArray = explode('-', $dateTime[0]);
2036 $timeArray = explode(':', $dateTime[1]);
2038 // Construct the timestamp
2039 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2049 default: // Default is pass-through
2050 $readable = $timestamp;
2060 * Filter a given number into a localized number
2062 * @param $value The raw value from e.g. database
2063 * @return $localized Localized value
2065 public function doFilterFormatNumber ($value) {
2066 // Generate it from config and localize dependencies
2067 switch ($this->getLanguageInstance()->getLanguageCode()) {
2068 case 'de': // German format is a bit different to default
2069 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2072 default: // US, etc.
2073 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2082 * "Getter" for databse entry
2084 * @return $entry An array with database entries
2085 * @throws NullPointerException If the database result is not found
2086 * @throws InvalidDatabaseResultException If the database result is invalid
2088 protected final function getDatabaseEntry () {
2089 // Is there an instance?
2090 if (!$this->getResultInstance() instanceof SearchableResult) {
2091 // Throw an exception here
2092 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2096 $this->getResultInstance()->rewind();
2098 // Do we have an entry?
2099 if ($this->getResultInstance()->valid() === FALSE) {
2100 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2101 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2105 $this->getResultInstance()->next();
2108 $entry = $this->getResultInstance()->current();
2115 * Getter for field name
2117 * @param $fieldName Field name which we shall get
2118 * @return $fieldValue Field value from the user
2119 * @throws NullPointerException If the result instance is null
2121 public final function getField ($fieldName) {
2122 // Default field value
2125 // Get result instance
2126 $resultInstance = $this->getResultInstance();
2128 // Is this instance null?
2129 if (is_null($resultInstance)) {
2130 // Then the user instance is no longer valid (expired cookies?)
2131 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2134 // Get current array
2135 $fieldArray = $resultInstance->current();
2136 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2138 // Convert dashes to underscore
2139 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2141 // Does the field exist?
2142 if ($this->isFieldSet($fieldName)) {
2144 $fieldValue = $fieldArray[$fieldName2];
2145 } elseif (defined('DEVELOPER')) {
2146 // Missing field entry, may require debugging
2147 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2149 // Missing field entry, may require debugging
2150 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2158 * Checks if given field is set
2160 * @param $fieldName Field name to check
2161 * @return $isSet Whether the given field name is set
2162 * @throws NullPointerException If the result instance is null
2164 public function isFieldSet ($fieldName) {
2165 // Get result instance
2166 $resultInstance = $this->getResultInstance();
2168 // Is this instance null?
2169 if (is_null($resultInstance)) {
2170 // Then the user instance is no longer valid (expired cookies?)
2171 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2174 // Get current array
2175 $fieldArray = $resultInstance->current();
2176 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2178 // Convert dashes to underscore
2179 $fieldName = self::convertDashesToUnderscores($fieldName);
2182 $isSet = isset($fieldArray[$fieldName]);
2189 * Flushs all pending updates to the database layer
2193 public function flushPendingUpdates () {
2194 // Get result instance
2195 $resultInstance = $this->getResultInstance();
2197 // Do we have data to update?
2198 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2199 // Get wrapper class name config entry
2200 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2202 // Create object instance
2203 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2205 // Yes, then send the whole result to the database layer
2206 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2211 * Outputs a deprecation warning to the developer.
2213 * @param $message The message we shall output to the developer
2215 * @todo Write a logging mechanism for productive mode
2217 public function deprecationWarning ($message) {
2218 // Is developer mode active?
2219 if (defined('DEVELOPER')) {
2220 // Debug instance is there?
2221 if (!is_null($this->getDebugInstance())) {
2222 // Output stub message
2223 self::createDebugInstance(__CLASS__)->debugOutput($message);
2226 trigger_error($message . "<br />\n");
2230 // @TODO Finish this part!
2231 $this->partialStub('Developer mode inactive. Message:' . $message);
2236 * Checks whether the given PHP extension is loaded
2238 * @param $phpExtension The PHP extension we shall check
2239 * @return $isLoaded Whether the PHP extension is loaded
2241 public final function isPhpExtensionLoaded ($phpExtension) {
2243 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2250 * "Getter" as a time() replacement but with milliseconds. You should use this
2251 * method instead of the encapsulated getimeofday() function.
2253 * @return $milliTime Timestamp with milliseconds
2255 public function getMilliTime () {
2256 // Get the time of day as float
2257 $milliTime = gettimeofday(TRUE);
2264 * Idles (sleeps) for given milliseconds
2266 * @return $hasSlept Whether it goes fine
2268 public function idle ($milliSeconds) {
2269 // Sleep is fine by default
2272 // Idle so long with found function
2273 if (function_exists('time_sleep_until')) {
2274 // Get current time and add idle time
2275 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2277 // New PHP 5.1.0 function found, ignore errors
2278 $hasSlept = @time_sleep_until($sleepUntil);
2281 * My Sun station doesn't have that function even with latest PHP
2284 usleep($milliSeconds * 1000);
2291 * Converts a hexadecimal string, even with negative sign as first string to
2292 * a decimal number using BC functions.
2294 * This work is based on comment #86673 on php.net documentation page at:
2295 * <http://de.php.net/manual/en/function.dechex.php#86673>
2297 * @param $hex Hexadecimal string
2298 * @return $dec Decimal number
2300 protected function hex2dec ($hex) {
2301 // Convert to all lower-case
2302 $hex = strtolower($hex);
2304 // Detect sign (negative/positive numbers)
2306 if (substr($hex, 0, 1) == '-') {
2308 $hex = substr($hex, 1);
2311 // Decode the hexadecimal string into a decimal number
2313 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2314 $factor = self::$hexdec[substr($hex, $i, 1)];
2315 $dec = bcadd($dec, bcmul($factor, $e));
2318 // Return the decimal number
2319 return $sign . $dec;
2323 * Converts even very large decimal numbers, also signed, to a hexadecimal
2326 * This work is based on comment #97756 on php.net documentation page at:
2327 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2329 * @param $dec Decimal number, even with negative sign
2330 * @param $maxLength Optional maximum length of the string
2331 * @return $hex Hexadecimal string
2333 protected function dec2hex ($dec, $maxLength = 0) {
2334 // maxLength can be zero or devideable by 2
2335 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2337 // Detect sign (negative/positive numbers)
2344 // Encode the decimal number into a hexadecimal string
2347 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2349 } while ($dec >= 1);
2352 * Leading zeros are required for hex-decimal "numbers". In some
2353 * situations more leading zeros are wanted, so check for both
2356 if ($maxLength > 0) {
2357 // Prepend more zeros
2358 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2359 } elseif ((strlen($hex) % 2) != 0) {
2360 // Only make string's length dividable by 2
2364 // Return the hexadecimal string
2365 return $sign . $hex;
2369 * Converts a ASCII string (0 to 255) into a decimal number.
2371 * @param $asc The ASCII string to be converted
2372 * @return $dec Decimal number
2374 protected function asc2dec ($asc) {
2375 // Convert it into a hexadecimal number
2376 $hex = bin2hex($asc);
2378 // And back into a decimal number
2379 $dec = $this->hex2dec($hex);
2386 * Converts a decimal number into an ASCII string.
2388 * @param $dec Decimal number
2389 * @return $asc An ASCII string
2391 protected function dec2asc ($dec) {
2392 // First convert the number into a hexadecimal string
2393 $hex = $this->dec2hex($dec);
2395 // Then convert it into the ASCII string
2396 $asc = $this->hex2asc($hex);
2403 * Converts a hexadecimal number into an ASCII string. Negative numbers
2406 * @param $hex Hexadecimal string
2407 * @return $asc An ASCII string
2409 protected function hex2asc ($hex) {
2410 // Check for length, it must be devideable by 2
2411 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2412 assert((strlen($hex) % 2) == 0);
2416 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2417 // Get the decimal number of the chunk
2418 $part = hexdec(substr($hex, $idx, 2));
2420 // Add it to the final string
2424 // Return the final string
2429 * Checks whether the given encoded data was encoded with Base64
2431 * @param $encodedData Encoded data we shall check
2432 * @return $isBase64 Whether the encoded data is Base64
2434 protected function isBase64Encoded ($encodedData) {
2436 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2443 * "Getter" to get response/request type from analysis of the system.
2445 * @return $responseType Analyzed response type
2447 protected static function getResponseTypeFromSystem () {
2448 // Default is console
2449 $responseType = 'console';
2451 // Is 'HTTP_HOST' set?
2452 if (isset($_SERVER['HTTP_HOST'])) {
2454 * Then it is a HTML response/request as RSS and so on may be
2455 * transfered over HTTP as well.
2457 $responseType = 'html';
2461 return $responseType;
2465 * Gets a cache key from Criteria instance
2467 * @param $criteriaInstance An instance of a Criteria class
2468 * @param $onlyKeys Only use these keys for a cache key
2469 * @return $cacheKey A cache key suitable for lookup/storage purposes
2471 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2473 $cacheKey = sprintf('%s@%s',
2474 $this->__toString(),
2475 $criteriaInstance->getCacheKey($onlyKeys)
2479 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2484 * Getter for startup time in miliseconds
2486 * @return $startupTime Startup time in miliseconds
2488 protected function getStartupTime () {
2489 return self::$startupTime;
2493 * "Getter" for a printable currently execution time in nice braces
2495 * @return $executionTime Current execution time in nice braces
2497 protected function getPrintableExecutionTime () {
2498 // Caculate the execution time
2499 $executionTime = microtime(TRUE) - $this->getStartupTime();
2501 // Pack it in nice braces
2502 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2505 return $executionTime;
2509 * Hashes a given string with a simple but stronger hash function (no salt)
2510 * and hex-encode it.
2512 * @param $str The string to be hashed
2513 * @return $hash The hash from string $str
2515 public static final function hash ($str) {
2516 // Hash given string with (better secure) hasher
2517 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2524 * "Getter" for length of hash() output. This will be "cached" to speed up
2527 * @return $length Length of hash() output
2529 public static final function getHashLength () {
2531 if (is_null(self::$hashLength)) {
2532 // No, then hash a string and save its length.
2533 self::$hashLength = strlen(self::hash('abc123'));
2537 return self::$hashLength;
2541 * Checks whether the given number is really a number (only chars 0-9).
2543 * @param $num A string consisting only chars between 0 and 9
2544 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2545 * @param $assertMismatch Whether to assert mismatches
2546 * @return $ret The (hopefully) secured numbered value
2548 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2549 // Filter all numbers out
2550 $ret = preg_replace('/[^0123456789]/', '', $num);
2553 if ($castValue === TRUE) {
2554 // Cast to biggest numeric type
2555 $ret = (double) $ret;
2558 // Assert only if requested
2559 if ($assertMismatch === TRUE) {
2560 // Has the whole value changed?
2561 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2569 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2571 * @param $num A string consisting only chars between 0 and 9
2572 * @param $assertMismatch Whether to assert mismatches
2573 * @return $ret The (hopefully) secured hext-numbered value
2575 public function hexval ($num, $assertMismatch = FALSE) {
2576 // Filter all numbers out
2577 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2579 // Assert only if requested
2580 if ($assertMismatch === TRUE) {
2581 // Has the whole value changed?
2582 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2590 * Checks whether start/end marker are set
2592 * @param $data Data to be checked
2593 * @return $isset Whether start/end marker are set
2595 public final function ifStartEndMarkersSet ($data) {
2597 $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));
2599 // ... and return it
2604 * Determines if an element is set in the generic array
2606 * @param $keyGroup Main group for the key
2607 * @param $subGroup Sub group for the key
2608 * @param $key Key to check
2609 * @param $element Element to check
2610 * @return $isset Whether the given key is set
2612 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2614 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2617 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2623 * Determines if a key is set in the generic array
2625 * @param $keyGroup Main group for the key
2626 * @param $subGroup Sub group for the key
2627 * @param $key Key to check
2628 * @return $isset Whether the given key is set
2630 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2632 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2635 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2643 * Determines if a group is set in the generic array
2645 * @param $keyGroup Main group
2646 * @param $subGroup Sub group
2647 * @return $isset Whether the given group is set
2649 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2651 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2654 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2661 * Getter for sub key group
2663 * @param $keyGroup Main key group
2664 * @param $subGroup Sub key group
2665 * @return $array An array with all array elements
2667 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2669 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2670 // No, then abort here
2671 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2676 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2679 return $this->genericArray[$keyGroup][$subGroup];
2683 * Unsets a given key in generic array
2685 * @param $keyGroup Main group for the key
2686 * @param $subGroup Sub group for the key
2687 * @param $key Key to unset
2690 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2692 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2695 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2699 * Unsets a given element in generic array
2701 * @param $keyGroup Main group for the key
2702 * @param $subGroup Sub group for the key
2703 * @param $key Key to unset
2704 * @param $element Element to unset
2707 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2709 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2712 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2716 * Append a string to a given generic array key
2718 * @param $keyGroup Main group for the key
2719 * @param $subGroup Sub group for the key
2720 * @param $key Key to unset
2721 * @param $value Value to add/append
2724 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2726 //* 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);
2728 // Is it already there?
2729 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2731 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2734 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2739 * Append a string to a given generic array element
2741 * @param $keyGroup Main group for the key
2742 * @param $subGroup Sub group for the key
2743 * @param $key Key to unset
2744 * @param $element Element to check
2745 * @param $value Value to add/append
2748 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2750 //* 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);
2752 // Is it already there?
2753 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2755 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2758 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2763 * Initializes given generic array group
2765 * @param $keyGroup Main group for the key
2766 * @param $subGroup Sub group for the key
2767 * @param $key Key to use
2768 * @param $forceInit Optionally force initialization
2771 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2773 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2775 // Is it already set?
2776 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2777 // Already initialized
2778 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2783 $this->genericArray[$keyGroup][$subGroup] = array();
2787 * Initializes given generic array key
2789 * @param $keyGroup Main group for the key
2790 * @param $subGroup Sub group for the key
2791 * @param $key Key to use
2792 * @param $forceInit Optionally force initialization
2795 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2797 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2799 // Is it already set?
2800 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2801 // Already initialized
2802 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2807 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2811 * Initializes given generic array element
2813 * @param $keyGroup Main group for the key
2814 * @param $subGroup Sub group for the key
2815 * @param $key Key to use
2816 * @param $element Element to use
2817 * @param $forceInit Optionally force initialization
2820 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2822 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2824 // Is it already set?
2825 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2826 // Already initialized
2827 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2832 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2836 * Pushes an element to a generic key
2838 * @param $keyGroup Main group for the key
2839 * @param $subGroup Sub group for the key
2840 * @param $key Key to use
2841 * @param $value Value to add/append
2842 * @return $count Number of array elements
2844 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2846 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2849 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2851 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2855 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2858 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2859 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2864 * Pushes an element to a generic array element
2866 * @param $keyGroup Main group for the key
2867 * @param $subGroup Sub group for the key
2868 * @param $key Key to use
2869 * @param $element Element to check
2870 * @param $value Value to add/append
2871 * @return $count Number of array elements
2873 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2875 //* 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));
2878 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2880 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2884 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2887 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2888 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2893 * Pops an element from a generic group
2895 * @param $keyGroup Main group for the key
2896 * @param $subGroup Sub group for the key
2897 * @param $key Key to unset
2898 * @return $value Last "popped" value
2900 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2902 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2905 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2907 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2912 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2915 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2916 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2921 * Shifts an element from a generic group
2923 * @param $keyGroup Main group for the key
2924 * @param $subGroup Sub group for the key
2925 * @param $key Key to unset
2926 * @return $value Last "popped" value
2928 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2930 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2933 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2935 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2940 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2943 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2944 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2949 * Count generic array group
2951 * @param $keyGroup Main group for the key
2952 * @return $count Count of given group
2954 protected final function countGenericArray ($keyGroup) {
2956 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2959 if (!isset($this->genericArray[$keyGroup])) {
2961 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2966 $count = count($this->genericArray[$keyGroup]);
2969 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2976 * Count generic array sub group
2978 * @param $keyGroup Main group for the key
2979 * @param $subGroup Sub group for the key
2980 * @return $count Count of given group
2982 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2984 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2987 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2989 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2994 $count = count($this->genericArray[$keyGroup][$subGroup]);
2997 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3004 * Count generic array elements
3006 * @param $keyGroup Main group for the key
3007 * @param $subGroup Sub group for the key
3008 * @para $key Key to count
3009 * @return $count Count of given key
3011 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3013 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3016 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3018 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3020 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3022 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3027 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3030 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3037 * Getter for whole generic group array
3039 * @param $keyGroup Key group to get
3040 * @return $array Whole generic array group
3042 protected final function getGenericArray ($keyGroup) {
3044 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3047 if (!isset($this->genericArray[$keyGroup])) {
3049 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3054 return $this->genericArray[$keyGroup];
3058 * Setter for generic array key
3060 * @param $keyGroup Key group to get
3061 * @param $subGroup Sub group for the key
3062 * @param $key Key to unset
3063 * @param $value Mixed value from generic array element
3066 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3068 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3071 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3075 * Getter for generic array key
3077 * @param $keyGroup Key group to get
3078 * @param $subGroup Sub group for the key
3079 * @param $key Key to unset
3080 * @return $value Mixed value from generic array element
3082 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3084 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3087 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3089 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3094 return $this->genericArray[$keyGroup][$subGroup][$key];
3098 * Sets a value in given generic array key/element
3100 * @param $keyGroup Main group for the key
3101 * @param $subGroup Sub group for the key
3102 * @param $key Key to set
3103 * @param $element Element to set
3104 * @param $value Value to set
3107 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3109 //* 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));
3112 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3116 * Getter for generic array element
3118 * @param $keyGroup Key group to get
3119 * @param $subGroup Sub group for the key
3120 * @param $key Key to look for
3121 * @param $element Element to look for
3122 * @return $value Mixed value from generic array element
3124 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3126 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3129 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3131 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3136 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3140 * Checks if a given sub group is valid (array)
3142 * @param $keyGroup Key group to get
3143 * @param $subGroup Sub group for the key
3144 * @return $isValid Whether given sub group is valid
3146 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3148 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3151 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3158 * Checks if a given key is valid (array)
3160 * @param $keyGroup Key group to get
3161 * @param $subGroup Sub group for the key
3162 * @param $key Key to check
3163 * @return $isValid Whether given sub group is valid
3165 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3167 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3170 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3177 * Initializes the web output instance
3181 protected function initWebOutputInstance () {
3182 // Get application instance
3183 $applicationInstance = Registry::getRegistry()->getInstance('app');
3185 // Is this a response instance?
3186 if ($this instanceof Responseable) {
3187 // Then set it in application instance
3188 $applicationInstance->setResponseInstance($this);
3191 // Init web output instance
3192 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3195 $this->setWebOutputInstance($outputInstance);
3199 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3201 * @param $boolean Boolean value
3202 * @return $translated Translated boolean value
3204 public static final function translateBooleanToYesNo ($boolean) {
3205 // Make sure it is really boolean
3206 assert(is_bool($boolean));
3209 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3211 // ... and return it
3216 * Encodes raw data (almost any type) by "serializing" it and then pack it
3217 * into a "binary format".
3219 * @param $rawData Raw data (almost any type)
3220 * @return $encoded Encoded data
3222 protected function encodeData ($rawData) {
3223 // Make sure no objects or resources pass through
3224 assert(!is_object($rawData));
3225 assert(!is_resource($rawData));
3227 // First "serialize" it (json_encode() is faster than serialize())
3228 $encoded = $this->packString(json_encode($rawData));
3235 * Pack a string into a "binary format". Please execuse me that this is
3236 * widely undocumented. :-(
3238 * @param $str Unpacked string
3239 * @return $packed Packed string
3240 * @todo Improve documentation
3242 protected function packString ($str) {
3244 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3246 // First compress the string (gzcompress is okay)
3247 $str = gzcompress($str);
3252 // And start the "encoding" loop
3253 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3255 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3256 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3258 if (($idx + $i) <= strlen($str)) {
3259 $ord = ord(substr($str, ($idx + $i), 1));
3261 $add = $ord * pow(256, $factor);
3265 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3269 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3270 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3272 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3273 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3279 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');
3284 * Checks whether the given file/path is in open_basedir(). This does not
3285 * gurantee that the file is actually readable and/or writeable. If you need
3286 * such gurantee then please use isReadableFile() instead.
3288 * @param $filePathName Name of the file/path to be checked
3289 * @return $isReachable Whether it is within open_basedir()
3291 public static function isReachableFilePath ($filePathName) {
3292 // Is not reachable by default
3293 $isReachable = FALSE;
3295 // Get open_basedir parameter
3296 $openBaseDir = ini_get('open_basedir');
3299 if (!empty($openBaseDir)) {
3300 // Check all entries
3301 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3302 // Check on existence
3303 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3305 $isReachable = TRUE;
3309 // If open_basedir is not set, all is allowed
3310 $isReachable = TRUE;
3314 return $isReachable;
3318 * Checks whether the give file is within open_basedir() (done by
3319 * isReachableFilePath()), is actually a file and is readable.
3321 * @param $fileName Name of the file to be checked
3322 * @return $isReadable Whether the file is readable (and therefor exists)
3324 public static function isReadableFile ($fileName) {
3325 // Default is not readable
3326 $isReadable = FALSE;
3328 // Is within parameters, so check if it is a file and readable
3329 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));