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_DATABASE_UPDATED_NOT_ALLOWED = 0x03b;
363 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03c;
366 * Hexadecimal->Decimal translation array
368 private static $hexdec = array(
388 * Decimal->hexadecimal translation array
390 private static $dechex = array(
410 * Startup time in miliseconds
412 private static $startupTime = 0;
415 * Protected super constructor
417 * @param $className Name of the class
420 protected function __construct ($className) {
422 $this->setRealClass($className);
424 // Set configuration instance if no registry ...
425 if (!$this instanceof Register) {
426 // ... because registries doesn't need to be configured
427 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
430 // Is the startup time set? (0 cannot be TRUE anymore)
431 if (self::$startupTime == 0) {
433 self::$startupTime = microtime(TRUE);
437 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
441 * Destructor for all classes
445 public function __destruct () {
446 // Flush any updated entries to the database
447 $this->flushPendingUpdates();
449 // Is this object already destroyed?
450 if ($this->__toString() != 'DestructedObject') {
451 // Destroy all informations about this class but keep some text about it alive
452 $this->setRealClass('DestructedObject');
453 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
454 // Already destructed object
455 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
460 // Do not call this twice
461 trigger_error(__METHOD__ . ': Called twice.');
467 * The __call() method where all non-implemented methods end up
469 * @param $methodName Name of the missing method
470 * @args $args Arguments passed to the method
473 public final function __call ($methodName, $args) {
474 return self::__callStatic($methodName, $args);
478 * The __callStatic() method where all non-implemented static methods end up
480 * @param $methodName Name of the missing method
481 * @args $args Arguments passed to the method
484 public static final function __callStatic ($methodName, $args) {
485 // Init argument string
488 // Is it NULL, empty or an array?
489 if (is_null($args)) {
491 $argsString = 'NULL';
492 } elseif (empty($args)) {
494 $argsString = '(empty)';
495 } elseif (is_array($args)) {
496 // Some arguments are there
497 foreach ($args as $arg) {
498 // Add the value itself if not array. This prevents 'array to string conversion' message
499 if (is_array($arg)) {
500 $argsString .= 'Array';
505 // Add data about the argument
506 $argsString .= ' (' . gettype($arg);
508 if (is_string($arg)) {
509 // Add length for strings
510 $argsString .= ', ' . strlen($arg);
511 } elseif (is_array($arg)) {
512 // .. or size if array
513 $argsString .= ', ' . count($arg);
514 } elseif ($arg === TRUE) {
515 // ... is boolean 'TRUE'
516 $argsString .= ', TRUE';
517 } elseif ($arg === FALSE) {
518 // ... is boolean 'FALSE'
519 $argsString .= ', FALSE';
523 $argsString .= '), ';
527 if (substr($argsString, -2, 1) == ',') {
528 $argsString = substr($argsString, 0, -2);
531 // Invalid arguments!
532 $argsString = '!INVALID:' . gettype($args) . '!';
535 // Output stub message
536 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
537 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
547 * Getter for $realClass
549 * @return $realClass The name of the real class (not BaseFrameworkSystem)
551 public function __toString () {
552 return $this->realClass;
556 * Magic method to catch setting of missing but set class fields/attributes
558 * @param $name Name of the field/attribute
559 * @param $value Value to store
562 public final function __set ($name, $value) {
563 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
566 print_r($value, TRUE)
571 * Magic method to catch getting of missing fields/attributes
573 * @param $name Name of the field/attribute
576 public final function __get ($name) {
577 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
583 * Magic method to catch unsetting of missing fields/attributes
585 * @param $name Name of the field/attribute
588 public final function __unset ($name) {
589 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
595 * Magic method to catch object serialization
597 * @return $unsupported Unsupported method
598 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
600 public final function __sleep () {
601 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
605 * Magic method to catch object deserialization
607 * @return $unsupported Unsupported method
608 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
610 public final function __wakeup () {
611 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
615 * Magic method to catch calls when an object instance is called
617 * @return $unsupported Unsupported method
618 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
620 public final function __invoke () {
621 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
625 * Setter for the real class name
627 * @param $realClass Class name (string)
630 public final function setRealClass ($realClass) {
632 $this->realClass = (string) $realClass;
636 * Setter for database result instance
638 * @param $resultInstance An instance of a database result class
640 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
642 protected final function setResultInstance (SearchableResult $resultInstance) {
643 $this->resultInstance = $resultInstance;
647 * Getter for database result instance
649 * @return $resultInstance An instance of a database result class
651 public final function getResultInstance () {
652 return $this->resultInstance;
656 * Setter for template engine instances
658 * @param $templateInstance An instance of a template engine class
661 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
662 $this->templateInstance = $templateInstance;
666 * Getter for template engine instances
668 * @return $templateInstance An instance of a template engine class
670 protected final function getTemplateInstance () {
671 return $this->templateInstance;
675 * Setter for search instance
677 * @param $searchInstance Searchable criteria instance
680 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
681 $this->searchInstance = $searchInstance;
685 * Getter for search instance
687 * @return $searchInstance Searchable criteria instance
689 public final function getSearchInstance () {
690 return $this->searchInstance;
694 * Setter for update instance
696 * @param $updateInstance Searchable criteria instance
699 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
700 $this->updateInstance = $updateInstance;
704 * Getter for update instance
706 * @return $updateInstance Updateable criteria instance
708 public final function getUpdateInstance () {
709 return $this->updateInstance;
713 * Setter for resolver instance
715 * @param $resolverInstance Instance of a command resolver class
718 public final function setResolverInstance (Resolver $resolverInstance) {
719 $this->resolverInstance = $resolverInstance;
723 * Getter for resolver instance
725 * @return $resolverInstance Instance of a command resolver class
727 public final function getResolverInstance () {
728 return $this->resolverInstance;
732 * Setter for language instance
734 * @param $configInstance The configuration instance which shall
735 * be FrameworkConfiguration
738 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
739 Registry::getRegistry()->addInstance('config', $configInstance);
743 * Getter for configuration instance
745 * @return $configInstance Configuration instance
747 public final function getConfigInstance () {
748 $configInstance = Registry::getRegistry()->getInstance('config');
749 return $configInstance;
753 * Setter for debug instance
755 * @param $debugInstance The instance for debug output class
758 public final function setDebugInstance (DebugMiddleware $debugInstance) {
759 Registry::getRegistry()->addInstance('debug', $debugInstance);
763 * Getter for debug instance
765 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
767 public final function getDebugInstance () {
768 // Get debug instance
769 $debugInstance = Registry::getRegistry()->getInstance('debug');
772 return $debugInstance;
776 * Setter for web output instance
778 * @param $webInstance The instance for web output class
781 public final function setWebOutputInstance (OutputStreamer $webInstance) {
782 Registry::getRegistry()->addInstance('web_output', $webInstance);
786 * Getter for web output instance
788 * @return $webOutputInstance - Instance to class WebOutput
790 public final function getWebOutputInstance () {
791 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
792 return $webOutputInstance;
796 * Setter for database instance
798 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
801 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
802 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
806 * Getter for database layer
808 * @return $databaseInstance The database layer instance
810 public final function getDatabaseInstance () {
812 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
815 return $databaseInstance;
819 * Setter for compressor channel
821 * @param $compressorInstance An instance of CompressorChannel
824 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
825 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
829 * Getter for compressor channel
831 * @return $compressorInstance The compressor channel
833 public final function getCompressorChannel () {
834 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
835 return $compressorInstance;
839 * Protected getter for a manageable application helper class
841 * @return $applicationInstance An instance of a manageable application helper class
843 protected final function getApplicationInstance () {
844 $applicationInstance = Registry::getRegistry()->getInstance('application');
845 return $applicationInstance;
849 * Setter for a manageable application helper class
851 * @param $applicationInstance An instance of a manageable application helper class
854 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
855 Registry::getRegistry()->addInstance('application', $applicationInstance);
859 * Setter for request instance
861 * @param $requestInstance An instance of a Requestable class
864 public final function setRequestInstance (Requestable $requestInstance) {
865 $this->requestInstance = $requestInstance;
869 * Getter for request instance
871 * @return $requestInstance An instance of a Requestable class
873 public final function getRequestInstance () {
874 return $this->requestInstance;
878 * Setter for response instance
880 * @param $responseInstance An instance of a Responseable class
883 public final function setResponseInstance (Responseable $responseInstance) {
884 $this->responseInstance = $responseInstance;
888 * Getter for response instance
890 * @return $responseInstance An instance of a Responseable class
892 public final function getResponseInstance () {
893 return $this->responseInstance;
897 * Private getter for language instance
899 * @return $langInstance An instance to the language sub-system
901 protected final function getLanguageInstance () {
902 $langInstance = Registry::getRegistry()->getInstance('language');
903 return $langInstance;
907 * Setter for language instance
909 * @param $langInstance An instance to the language sub-system
911 * @see LanguageSystem
913 public final function setLanguageInstance (ManageableLanguage $langInstance) {
914 Registry::getRegistry()->addInstance('language', $langInstance);
918 * Private getter for file IO instance
920 * @return $fileIoInstance An instance to the file I/O sub-system
922 protected final function getFileIoInstance () {
923 return $this->fileIoInstance;
927 * Setter for file I/O instance
929 * @param $fileIoInstance An instance to the file I/O sub-system
932 public final function setFileIoInstance (IoHandler $fileIoInstance) {
933 $this->fileIoInstance = $fileIoInstance;
937 * Protected setter for user instance
939 * @param $userInstance An instance of a user class
942 protected final function setUserInstance (ManageableAccount $userInstance) {
943 $this->userInstance = $userInstance;
947 * Getter for user instance
949 * @return $userInstance An instance of a user class
951 public final function getUserInstance () {
952 return $this->userInstance;
956 * Setter for controller instance (this surely breaks a bit the MVC patterm)
958 * @param $controllerInstance An instance of the controller
961 public final function setControllerInstance (Controller $controllerInstance) {
962 $this->controllerInstance = $controllerInstance;
966 * Getter for controller instance (this surely breaks a bit the MVC patterm)
968 * @return $controllerInstance An instance of the controller
970 public final function getControllerInstance () {
971 return $this->controllerInstance;
975 * Setter for RNG instance
977 * @param $rngInstance An instance of a random number generator (RNG)
980 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
981 $this->rngInstance = $rngInstance;
985 * Getter for RNG instance
987 * @return $rngInstance An instance of a random number generator (RNG)
989 public final function getRngInstance () {
990 return $this->rngInstance;
994 * Setter for Cryptable instance
996 * @param $cryptoInstance An instance of a Cryptable class
999 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1000 $this->cryptoInstance = $cryptoInstance;
1004 * Getter for Cryptable instance
1006 * @return $cryptoInstance An instance of a Cryptable class
1008 public final function getCryptoInstance () {
1009 return $this->cryptoInstance;
1013 * Setter for the list instance
1015 * @param $listInstance A list of Listable
1018 protected final function setListInstance (Listable $listInstance) {
1019 $this->listInstance = $listInstance;
1023 * Getter for the list instance
1025 * @return $listInstance A list of Listable
1027 protected final function getListInstance () {
1028 return $this->listInstance;
1032 * Setter for the menu instance
1034 * @param $menuInstance A RenderableMenu instance
1037 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1038 $this->menuInstance = $menuInstance;
1042 * Getter for the menu instance
1044 * @return $menuInstance A RenderableMenu instance
1046 protected final function getMenuInstance () {
1047 return $this->menuInstance;
1051 * Setter for image instance
1053 * @param $imageInstance An instance of an image
1056 public final function setImageInstance (BaseImage $imageInstance) {
1057 $this->imageInstance = $imageInstance;
1061 * Getter for image instance
1063 * @return $imageInstance An instance of an image
1065 public final function getImageInstance () {
1066 return $this->imageInstance;
1070 * Setter for stacker instance
1072 * @param $stackInstance An instance of an stacker
1075 public final function setStackInstance (Stackable $stackInstance) {
1076 $this->stackInstance = $stackInstance;
1080 * Getter for stacker instance
1082 * @return $stackInstance An instance of an stacker
1084 public final function getStackInstance () {
1085 return $this->stackInstance;
1089 * Setter for compressor instance
1091 * @param $compressorInstance An instance of an compressor
1094 public final function setCompressorInstance (Compressor $compressorInstance) {
1095 $this->compressorInstance = $compressorInstance;
1099 * Getter for compressor instance
1101 * @return $compressorInstance An instance of an compressor
1103 public final function getCompressorInstance () {
1104 return $this->compressorInstance;
1108 * Setter for Parseable instance
1110 * @param $parserInstance An instance of an Parseable
1113 public final function setParserInstance (Parseable $parserInstance) {
1114 $this->parserInstance = $parserInstance;
1118 * Getter for Parseable instance
1120 * @return $parserInstance An instance of an Parseable
1122 public final function getParserInstance () {
1123 return $this->parserInstance;
1127 * Setter for HandleableProtocol instance
1129 * @param $protocolInstance An instance of an HandleableProtocol
1132 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1133 $this->protocolInstance = $protocolInstance;
1137 * Getter for HandleableProtocol instance
1139 * @return $protocolInstance An instance of an HandleableProtocol
1141 public final function getProtocolInstance () {
1142 return $this->protocolInstance;
1146 * Setter for DatabaseWrapper instance
1148 * @param $wrapperInstance An instance of an DatabaseWrapper
1151 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1152 $this->wrapperInstance = $wrapperInstance;
1156 * Getter for DatabaseWrapper instance
1158 * @return $wrapperInstance An instance of an DatabaseWrapper
1160 public final function getWrapperInstance () {
1161 return $this->wrapperInstance;
1165 * Setter for socket resource
1167 * @param $socketResource A valid socket resource
1170 public final function setSocketResource ($socketResource) {
1171 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1172 $this->socketResource = $socketResource;
1176 * Getter for socket resource
1178 * @return $socketResource A valid socket resource
1180 public final function getSocketResource () {
1181 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1182 return $this->socketResource;
1186 * Setter for regular expression
1188 * @param $regularExpression A valid regular expression
1191 public final function setRegularExpression ($regularExpression) {
1192 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1193 $this->regularExpression = $regularExpression;
1197 * Getter for regular expression
1199 * @return $regularExpression A valid regular expression
1201 public final function getRegularExpression () {
1202 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1203 return $this->regularExpression;
1207 * Setter for helper instance
1209 * @param $helperInstance An instance of a helper class
1212 protected final function setHelperInstance (Helper $helperInstance) {
1213 $this->helperInstance = $helperInstance;
1217 * Getter for helper instance
1219 * @return $helperInstance An instance of a helper class
1221 public final function getHelperInstance () {
1222 return $this->helperInstance;
1226 * Setter for a Source instance
1228 * @param $sourceInstance An instance of a Source class
1231 protected final function setSourceInstance (Source $sourceInstance) {
1232 $this->sourceInstance = $sourceInstance;
1236 * Getter for a Source instance
1238 * @return $sourceInstance An instance of a Source class
1240 protected final function getSourceInstance () {
1241 return $this->sourceInstance;
1245 * Setter for a UrlSource instance
1247 * @param $sourceInstance An instance of a UrlSource class
1250 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1251 $this->urlSourceInstance = $urlSourceInstance;
1255 * Getter for a UrlSource instance
1257 * @return $urlSourceInstance An instance of a UrlSource class
1259 protected final function getUrlSourceInstance () {
1260 return $this->urlSourceInstance;
1264 * Getter for a InputStream instance
1266 * @param $inputStreamInstance The InputStream instance
1268 protected final function getInputStreamInstance () {
1269 return $this->inputStreamInstance;
1273 * Setter for a InputStream instance
1275 * @param $inputStreamInstance The InputStream instance
1278 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1279 $this->inputStreamInstance = $inputStreamInstance;
1283 * Getter for a OutputStream instance
1285 * @param $outputStreamInstance The OutputStream instance
1287 protected final function getOutputStreamInstance () {
1288 return $this->outputStreamInstance;
1292 * Setter for a OutputStream instance
1294 * @param $outputStreamInstance The OutputStream instance
1297 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1298 $this->outputStreamInstance = $outputStreamInstance;
1302 * Setter for handler instance
1304 * @param $handlerInstance An instance of a Handleable class
1307 protected final function setHandlerInstance (Handleable $handlerInstance) {
1308 $this->handlerInstance = $handlerInstance;
1312 * Getter for handler instance
1314 * @return $handlerInstance A Networkable instance
1316 protected final function getHandlerInstance () {
1317 return $this->handlerInstance;
1321 * Setter for visitor instance
1323 * @param $visitorInstance A Visitor instance
1326 protected final function setVisitorInstance (Visitor $visitorInstance) {
1327 $this->visitorInstance = $visitorInstance;
1331 * Getter for visitor instance
1333 * @return $visitorInstance A Visitor instance
1335 protected final function getVisitorInstance () {
1336 return $this->visitorInstance;
1340 * Setter for DHT instance
1342 * @param $dhtInstance A Distributable instance
1345 protected final function setDhtInstance (Distributable $dhtInstance) {
1346 $this->dhtInstance = $dhtInstance;
1350 * Getter for DHT instance
1352 * @return $dhtInstance A Distributable instance
1354 protected final function getDhtInstance () {
1355 return $this->dhtInstance;
1359 * Setter for raw package Data
1361 * @param $packageData Raw package Data
1364 public final function setPackageData (array $packageData) {
1365 $this->packageData = $packageData;
1369 * Getter for raw package Data
1371 * @return $packageData Raw package Data
1373 public function getPackageData () {
1374 return $this->packageData;
1379 * Setter for Iterator instance
1381 * @param $iteratorInstance An instance of an Iterator
1384 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1385 $this->iteratorInstance = $iteratorInstance;
1389 * Getter for Iterator instance
1391 * @return $iteratorInstance An instance of an Iterator
1393 public final function getIteratorInstance () {
1394 return $this->iteratorInstance;
1398 * Setter for FilePointer instance
1400 * @param $pointerInstance An instance of an FilePointer class
1403 protected final function setPointerInstance (FilePointer $pointerInstance) {
1404 $this->pointerInstance = $pointerInstance;
1408 * Getter for FilePointer instance
1410 * @return $pointerInstance An instance of an FilePointer class
1412 public final function getPointerInstance () {
1413 return $this->pointerInstance;
1417 * Unsets pointer instance which triggers a call of __destruct() if the
1418 * instance is still there. This is surely not fatal on already "closed"
1419 * file pointer instances.
1421 * I don't want to mess around with above setter by giving it a default
1422 * value NULL as setter should always explicitly only set (existing) object
1423 * instances and NULL is NULL.
1427 protected final function unsetPointerInstance () {
1428 // Simply it to NULL
1429 $this->pointerInstance = NULL;
1433 * Setter for Indexable instance
1435 * @param $indexInstance An instance of an Indexable class
1438 protected final function setIndexInstance (Indexable $indexInstance) {
1439 $this->indexInstance = $indexInstance;
1443 * Getter for Indexable instance
1445 * @return $indexInstance An instance of an Indexable class
1447 public final function getIndexInstance () {
1448 return $this->indexInstance;
1452 * Setter for Block instance
1454 * @param $blockInstance An instance of an Block class
1457 protected final function setBlockInstance (Block $blockInstance) {
1458 $this->blockInstance = $blockInstance;
1462 * Getter for Block instance
1464 * @return $blockInstance An instance of an Block class
1466 public final function getBlockInstance () {
1467 return $this->blockInstance;
1471 * Setter for Minable instance
1473 * @param $minableInstance A Minable instance
1476 protected final function setMinableInstance (Minable $minableInstance) {
1477 $this->minableInstance = $minableInstance;
1481 * Getter for minable instance
1483 * @return $minableInstance A Minable instance
1485 protected final function getMinableInstance () {
1486 return $this->minableInstance;
1490 * Setter for FrameworkDirectory instance
1492 * @param $directoryInstance A FrameworkDirectoryPointer instance
1495 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1496 $this->directoryInstance = $directoryInstance;
1500 * Getter for FrameworkDirectory instance
1502 * @return $directoryInstance A FrameworkDirectory instance
1504 protected final function getDirectoryInstance () {
1505 return $this->directoryInstance;
1509 * Setter for listener instance
1511 * @param $listenerInstance A Listenable instance
1514 protected final function setListenerInstance (Listenable $listenerInstance) {
1515 $this->listenerInstance = $listenerInstance;
1519 * Getter for listener instance
1521 * @return $listenerInstance A Listenable instance
1523 protected final function getListenerInstance () {
1524 return $this->listenerInstance;
1528 * Getter for communicator instance
1530 * @return $communicatorInstance An instance of a Communicator class
1532 public final function getCommunicatorInstance () {
1533 return $this->communicatorInstance;
1537 * Setter for communicator instance
1539 * @param $communicatorInstance An instance of a Communicator class
1542 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1543 $this->communicatorInstance = $communicatorInstance;
1547 * Setter for state instance
1549 * @param $stateInstance A Stateable instance
1552 public final function setStateInstance (Stateable $stateInstance) {
1553 $this->stateInstance = $stateInstance;
1557 * Getter for state instance
1559 * @return $stateInstance A Stateable instance
1561 public final function getStateInstance () {
1562 return $this->stateInstance;
1566 * Setter for command name
1568 * @param $commandName Last validated command name
1571 protected final function setCommandName ($commandName) {
1572 $this->commandName = $commandName;
1576 * Getter for command name
1578 * @return $commandName Last validated command name
1580 protected final function getCommandName () {
1581 return $this->commandName;
1585 * Setter for controller name
1587 * @param $controllerName Last validated controller name
1590 protected final function setControllerName ($controllerName) {
1591 $this->controllerName = $controllerName;
1595 * Getter for controller name
1597 * @return $controllerName Last validated controller name
1599 protected final function getControllerName () {
1600 return $this->controllerName;
1604 * Getter for protocol name
1606 * @return $protocolName Name of used protocol
1608 public final function getProtocolName () {
1609 return $this->protocolName;
1613 * Setter for protocol name
1615 * @param $protocolName Name of used protocol
1618 protected final function setProtocolName ($protocolName) {
1619 $this->protocolName = $protocolName;
1623 * Checks whether an object equals this object. You should overwrite this
1624 * method to implement own equality checks
1626 * @param $objectInstance An instance of a FrameworkInterface object
1627 * @return $equals Whether both objects equals
1629 public function equals (FrameworkInterface $objectInstance) {
1632 $this->__toString() == $objectInstance->__toString()
1634 $this->hashCode() == $objectInstance->hashCode()
1637 // Return the result
1642 * Generates a generic hash code of this class. You should really overwrite
1643 * this method with your own hash code generator code. But keep KISS in mind.
1645 * @return $hashCode A generic hash code respresenting this whole class
1647 public function hashCode () {
1649 return crc32($this->__toString());
1653 * Formats computer generated price values into human-understandable formats
1654 * with thousand and decimal separators.
1656 * @param $value The in computer format value for a price
1657 * @param $currency The currency symbol (use HTML-valid characters!)
1658 * @param $decNum Number of decimals after commata
1659 * @return $price The for the current language formated price string
1660 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1661 * thousands separator
1664 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1665 // Are all required attriutes set?
1666 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1667 // Throw an exception
1668 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1672 $value = (float) $value;
1674 // Reformat the US number
1675 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1677 // Return as string...
1682 * Appends a trailing slash to a string
1684 * @param $str A string (maybe) without trailing slash
1685 * @return $str A string with an auto-appended trailing slash
1687 public final function addMissingTrailingSlash ($str) {
1688 // Is there a trailing slash?
1689 if (substr($str, -1, 1) != '/') {
1693 // Return string with trailing slash
1698 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1699 * application helper instance (ApplicationHelper by default).
1701 * @param $applicationInstance An application helper instance or
1702 * null if we shall use the default
1703 * @return $templateInstance The template engine instance
1704 * @throws NullPointerException If the discovered application
1705 * instance is still null
1707 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1708 // Is the application instance set?
1709 if (is_null($applicationInstance)) {
1710 // Get the current instance
1711 $applicationInstance = $this->getApplicationInstance();
1714 if (is_null($applicationInstance)) {
1715 // Thrown an exception
1716 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1720 // Initialize the template engine
1721 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1723 // Return the prepared instance
1724 return $templateInstance;
1728 * Debugs this instance by putting out it's full content
1730 * @param $message Optional message to show in debug output
1733 public final function debugInstance ($message = '') {
1734 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1735 restore_error_handler();
1740 // Is a message set?
1741 if (!empty($message)) {
1742 // Construct message
1743 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1746 // Generate the output
1747 $content .= sprintf('<pre>%s</pre>',
1750 print_r($this, TRUE)
1756 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>',
1757 $this->__toString(),
1759 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1764 * Replaces control characters with printable output
1766 * @param $str String with control characters
1767 * @return $str Replaced string
1769 protected function replaceControlCharacters ($str) {
1772 chr(13), '[r]', str_replace(
1773 chr(10), '[n]', str_replace(
1783 * Output a partial stub message for the caller method
1785 * @param $message An optional message to display
1788 protected function partialStub ($message = '') {
1789 // Get the backtrace
1790 $backtrace = debug_backtrace();
1792 // Generate the class::method string
1793 $methodName = 'UnknownClass->unknownMethod';
1794 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1795 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1798 // Construct the full message
1799 $stubMessage = sprintf('[%s:] Partial stub!',
1803 // Is the extra message given?
1804 if (!empty($message)) {
1805 // Then add it as well
1806 $stubMessage .= ' Message: ' . $message;
1809 // Debug instance is there?
1810 if (!is_null($this->getDebugInstance())) {
1811 // Output stub message
1812 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1815 trigger_error($stubMessage);
1821 * Outputs a debug backtrace and stops further script execution
1823 * @param $message An optional message to output
1824 * @param $doExit Whether exit the program (TRUE is default)
1827 public function debugBackTrace ($message = '', $doExit = TRUE) {
1828 // Sorry, there is no other way getting this nice backtrace
1829 if (!empty($message)) {
1831 printf('Message: %s<br />' . chr(10), $message);
1835 debug_print_backtrace();
1839 if ($doExit === TRUE) {
1845 * Creates an instance of a debugger instance
1847 * @param $className Name of the class (currently unsupported)
1848 * @return $debugInstance An instance of a debugger class
1850 public final static function createDebugInstance ($className) {
1851 // Is the instance set?
1852 if (!Registry::getRegistry()->instanceExists('debug')) {
1853 // Init debug instance
1854 $debugInstance = NULL;
1858 // Get a debugger instance
1859 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'));
1860 } catch (NullPointerException $e) {
1861 // Didn't work, no instance there
1862 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1865 // Empty string should be ignored and used for testing the middleware
1866 DebugMiddleware::getSelfInstance()->output('');
1868 // Set it in its own class. This will set it in the registry
1869 $debugInstance->setDebugInstance($debugInstance);
1871 // Get instance from registry
1872 $debugInstance = Registry::getRegistry()->getDebugInstance();
1876 return $debugInstance;
1880 * Simple output of a message with line-break
1882 * @param $message Message to output
1885 public function outputLine ($message) {
1887 print($message . PHP_EOL);
1891 * Outputs a debug message whether to debug instance (should be set!) or
1892 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1893 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1895 * @param $message Message we shall send out...
1896 * @param $doPrint Whether print or die here (default: print)
1897 * @paran $stripTags Whether to strip tags (default: FALSE)
1900 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1901 // Set debug instance to NULL
1902 $debugInstance = NULL;
1906 // Get debug instance
1907 $debugInstance = $this->getDebugInstance();
1908 } catch (NullPointerException $e) {
1909 // The debug instance is not set (yet)
1912 // Is the debug instance there?
1913 if (is_object($debugInstance)) {
1914 // Use debug output handler
1915 $debugInstance->output($message, $stripTags);
1917 if ($doPrint === FALSE) {
1918 // Die here if not printed
1922 // Are debug times enabled?
1923 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1925 $message = $this->getPrintableExecutionTime() . $message;
1929 if ($doPrint === TRUE) {
1931 $this->outputLine($message);
1940 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1942 * @param $str The string, what ever it is needs to be converted
1943 * @return $className Generated class name
1945 public static final function convertToClassName ($str) {
1949 // Convert all dashes in underscores
1950 $str = self::convertDashesToUnderscores($str);
1952 // Now use that underscores to get classname parts for hungarian style
1953 foreach (explode('_', $str) as $strPart) {
1954 // Make the class name part lower case and first upper case
1955 $className .= ucfirst(strtolower($strPart));
1958 // Return class name
1963 * Converts dashes to underscores, e.g. useable for configuration entries
1965 * @param $str The string with maybe dashes inside
1966 * @return $str The converted string with no dashed, but underscores
1968 public static final function convertDashesToUnderscores ($str) {
1970 $str = str_replace('-', '_', $str);
1972 // Return converted string
1977 * Marks up the code by adding e.g. line numbers
1979 * @param $phpCode Unmarked PHP code
1980 * @return $markedCode Marked PHP code
1982 public function markupCode ($phpCode) {
1987 $errorArray = error_get_last();
1989 // Init the code with error message
1990 if (is_array($errorArray)) {
1992 $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>',
1993 basename($errorArray['file']),
1994 $errorArray['line'],
1995 $errorArray['message'],
2000 // Add line number to the code
2001 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2003 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
2005 htmlentities($code, ENT_QUOTES)
2014 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2015 * beatiful for web-based front-ends. If null is given a message id
2016 * null_timestamp will be resolved and returned.
2018 * @param $timestamp Timestamp to prepare (filter) for display
2019 * @return $readable A readable timestamp
2021 public function doFilterFormatTimestamp ($timestamp) {
2022 // Default value to return
2025 // Is the timestamp null?
2026 if (is_null($timestamp)) {
2027 // Get a message string
2028 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2030 switch ($this->getLanguageInstance()->getLanguageCode()) {
2031 case 'de': // German format is a bit different to default
2032 // Split the GMT stamp up
2033 $dateTime = explode(' ', $timestamp );
2034 $dateArray = explode('-', $dateTime[0]);
2035 $timeArray = explode(':', $dateTime[1]);
2037 // Construct the timestamp
2038 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2048 default: // Default is pass-through
2049 $readable = $timestamp;
2059 * Filter a given number into a localized number
2061 * @param $value The raw value from e.g. database
2062 * @return $localized Localized value
2064 public function doFilterFormatNumber ($value) {
2065 // Generate it from config and localize dependencies
2066 switch ($this->getLanguageInstance()->getLanguageCode()) {
2067 case 'de': // German format is a bit different to default
2068 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2071 default: // US, etc.
2072 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2081 * "Getter" for databse entry
2083 * @return $entry An array with database entries
2084 * @throws NullPointerException If the database result is not found
2085 * @throws InvalidDatabaseResultException If the database result is invalid
2087 protected final function getDatabaseEntry () {
2088 // Is there an instance?
2089 if (!$this->getResultInstance() instanceof SearchableResult) {
2090 // Throw an exception here
2091 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2095 $this->getResultInstance()->rewind();
2097 // Do we have an entry?
2098 if ($this->getResultInstance()->valid() === FALSE) {
2099 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2100 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2104 $this->getResultInstance()->next();
2107 $entry = $this->getResultInstance()->current();
2114 * Getter for field name
2116 * @param $fieldName Field name which we shall get
2117 * @return $fieldValue Field value from the user
2118 * @throws NullPointerException If the result instance is null
2120 public final function getField ($fieldName) {
2121 // Default field value
2124 // Get result instance
2125 $resultInstance = $this->getResultInstance();
2127 // Is this instance null?
2128 if (is_null($resultInstance)) {
2129 // Then the user instance is no longer valid (expired cookies?)
2130 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2133 // Get current array
2134 $fieldArray = $resultInstance->current();
2135 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2137 // Convert dashes to underscore
2138 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2140 // Does the field exist?
2141 if ($this->isFieldSet($fieldName)) {
2143 $fieldValue = $fieldArray[$fieldName2];
2144 } elseif (defined('DEVELOPER')) {
2145 // Missing field entry, may require debugging
2146 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2148 // Missing field entry, may require debugging
2149 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2157 * Checks if given field is set
2159 * @param $fieldName Field name to check
2160 * @return $isSet Whether the given field name is set
2161 * @throws NullPointerException If the result instance is null
2163 public function isFieldSet ($fieldName) {
2164 // Get result instance
2165 $resultInstance = $this->getResultInstance();
2167 // Is this instance null?
2168 if (is_null($resultInstance)) {
2169 // Then the user instance is no longer valid (expired cookies?)
2170 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2173 // Get current array
2174 $fieldArray = $resultInstance->current();
2175 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2177 // Convert dashes to underscore
2178 $fieldName = self::convertDashesToUnderscores($fieldName);
2181 $isSet = isset($fieldArray[$fieldName]);
2188 * Flushs all pending updates to the database layer
2192 public function flushPendingUpdates () {
2193 // Get result instance
2194 $resultInstance = $this->getResultInstance();
2196 // Do we have data to update?
2197 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2198 // Get wrapper class name config entry
2199 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2201 // Create object instance
2202 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
2204 // Yes, then send the whole result to the database layer
2205 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2210 * Outputs a deprecation warning to the developer.
2212 * @param $message The message we shall output to the developer
2214 * @todo Write a logging mechanism for productive mode
2216 public function deprecationWarning ($message) {
2217 // Is developer mode active?
2218 if (defined('DEVELOPER')) {
2219 // Debug instance is there?
2220 if (!is_null($this->getDebugInstance())) {
2221 // Output stub message
2222 self::createDebugInstance(__CLASS__)->debugOutput($message);
2225 trigger_error($message . "<br />\n");
2229 // @TODO Finish this part!
2230 $this->partialStub('Developer mode inactive. Message:' . $message);
2235 * Checks whether the given PHP extension is loaded
2237 * @param $phpExtension The PHP extension we shall check
2238 * @return $isLoaded Whether the PHP extension is loaded
2240 public final function isPhpExtensionLoaded ($phpExtension) {
2242 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2249 * "Getter" as a time() replacement but with milliseconds. You should use this
2250 * method instead of the encapsulated getimeofday() function.
2252 * @return $milliTime Timestamp with milliseconds
2254 public function getMilliTime () {
2255 // Get the time of day as float
2256 $milliTime = gettimeofday(TRUE);
2263 * Idles (sleeps) for given milliseconds
2265 * @return $hasSlept Whether it goes fine
2267 public function idle ($milliSeconds) {
2268 // Sleep is fine by default
2271 // Idle so long with found function
2272 if (function_exists('time_sleep_until')) {
2273 // Get current time and add idle time
2274 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2276 // New PHP 5.1.0 function found, ignore errors
2277 $hasSlept = @time_sleep_until($sleepUntil);
2280 * My Sun station doesn't have that function even with latest PHP
2283 usleep($milliSeconds * 1000);
2290 * Converts a hexadecimal string, even with negative sign as first string to
2291 * a decimal number using BC functions.
2293 * This work is based on comment #86673 on php.net documentation page at:
2294 * <http://de.php.net/manual/en/function.dechex.php#86673>
2296 * @param $hex Hexadecimal string
2297 * @return $dec Decimal number
2299 protected function hex2dec ($hex) {
2300 // Convert to all lower-case
2301 $hex = strtolower($hex);
2303 // Detect sign (negative/positive numbers)
2305 if (substr($hex, 0, 1) == '-') {
2307 $hex = substr($hex, 1);
2310 // Decode the hexadecimal string into a decimal number
2312 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2313 $factor = self::$hexdec[substr($hex, $i, 1)];
2314 $dec = bcadd($dec, bcmul($factor, $e));
2317 // Return the decimal number
2318 return $sign . $dec;
2322 * Converts even very large decimal numbers, also signed, to a hexadecimal
2325 * This work is based on comment #97756 on php.net documentation page at:
2326 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2328 * @param $dec Decimal number, even with negative sign
2329 * @param $maxLength Optional maximum length of the string
2330 * @return $hex Hexadecimal string
2332 protected function dec2hex ($dec, $maxLength = 0) {
2333 // maxLength can be zero or devideable by 2
2334 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2336 // Detect sign (negative/positive numbers)
2343 // Encode the decimal number into a hexadecimal string
2346 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2348 } while ($dec >= 1);
2351 * Leading zeros are required for hex-decimal "numbers". In some
2352 * situations more leading zeros are wanted, so check for both
2355 if ($maxLength > 0) {
2356 // Prepend more zeros
2357 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2358 } elseif ((strlen($hex) % 2) != 0) {
2359 // Only make string's length dividable by 2
2363 // Return the hexadecimal string
2364 return $sign . $hex;
2368 * Converts a ASCII string (0 to 255) into a decimal number.
2370 * @param $asc The ASCII string to be converted
2371 * @return $dec Decimal number
2373 protected function asc2dec ($asc) {
2374 // Convert it into a hexadecimal number
2375 $hex = bin2hex($asc);
2377 // And back into a decimal number
2378 $dec = $this->hex2dec($hex);
2385 * Converts a decimal number into an ASCII string.
2387 * @param $dec Decimal number
2388 * @return $asc An ASCII string
2390 protected function dec2asc ($dec) {
2391 // First convert the number into a hexadecimal string
2392 $hex = $this->dec2hex($dec);
2394 // Then convert it into the ASCII string
2395 $asc = $this->hex2asc($hex);
2402 * Converts a hexadecimal number into an ASCII string. Negative numbers
2405 * @param $hex Hexadecimal string
2406 * @return $asc An ASCII string
2408 protected function hex2asc ($hex) {
2409 // Check for length, it must be devideable by 2
2410 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2411 assert((strlen($hex) % 2) == 0);
2415 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2416 // Get the decimal number of the chunk
2417 $part = hexdec(substr($hex, $idx, 2));
2419 // Add it to the final string
2423 // Return the final string
2428 * Checks whether the given encoded data was encoded with Base64
2430 * @param $encodedData Encoded data we shall check
2431 * @return $isBase64 Whether the encoded data is Base64
2433 protected function isBase64Encoded ($encodedData) {
2435 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2442 * "Getter" to get response/request type from analysis of the system.
2444 * @return $responseType Analyzed response type
2446 protected static function getResponseTypeFromSystem () {
2447 // Default is console
2448 $responseType = 'console';
2450 // Is 'HTTP_HOST' set?
2451 if (isset($_SERVER['HTTP_HOST'])) {
2453 * Then it is a HTML response/request as RSS and so on may be
2454 * transfered over HTTP as well.
2456 $responseType = 'html';
2460 return $responseType;
2464 * Gets a cache key from Criteria instance
2466 * @param $criteriaInstance An instance of a Criteria class
2467 * @param $onlyKeys Only use these keys for a cache key
2468 * @return $cacheKey A cache key suitable for lookup/storage purposes
2470 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2472 $cacheKey = sprintf('%s@%s',
2473 $this->__toString(),
2474 $criteriaInstance->getCacheKey($onlyKeys)
2478 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2483 * Getter for startup time in miliseconds
2485 * @return $startupTime Startup time in miliseconds
2487 protected function getStartupTime () {
2488 return self::$startupTime;
2492 * "Getter" for a printable currently execution time in nice braces
2494 * @return $executionTime Current execution time in nice braces
2496 protected function getPrintableExecutionTime () {
2497 // Caculate the execution time
2498 $executionTime = microtime(TRUE) - $this->getStartupTime();
2500 // Pack it in nice braces
2501 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2504 return $executionTime;
2508 * Hashes a given string with a simple but stronger hash function (no salt)
2509 * and hex-encode it.
2511 * @param $str The string to be hashed
2512 * @return $hash The hash from string $str
2514 public static final function hash ($str) {
2515 // Hash given string with (better secure) hasher
2516 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2523 * "Getter" for length of hash() output. This will be "cached" to speed up
2526 * @return $length Length of hash() output
2528 public static final function getHashLength () {
2530 if (is_null(self::$hashLength)) {
2531 // No, then hash a string and save its length.
2532 self::$hashLength = strlen(self::hash('abc123'));
2536 return self::$hashLength;
2540 * Checks whether the given number is really a number (only chars 0-9).
2542 * @param $num A string consisting only chars between 0 and 9
2543 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2544 * @param $assertMismatch Whether to assert mismatches
2545 * @return $ret The (hopefully) secured numbered value
2547 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2548 // Filter all numbers out
2549 $ret = preg_replace('/[^0123456789]/', '', $num);
2552 if ($castValue === TRUE) {
2553 // Cast to biggest numeric type
2554 $ret = (double) $ret;
2557 // Assert only if requested
2558 if ($assertMismatch === TRUE) {
2559 // Has the whole value changed?
2560 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2568 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2570 * @param $num A string consisting only chars between 0 and 9
2571 * @param $assertMismatch Whether to assert mismatches
2572 * @return $ret The (hopefully) secured hext-numbered value
2574 public function hexval ($num, $assertMismatch = FALSE) {
2575 // Filter all numbers out
2576 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2578 // Assert only if requested
2579 if ($assertMismatch === TRUE) {
2580 // Has the whole value changed?
2581 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2589 * Checks whether start/end marker are set
2591 * @param $data Data to be checked
2592 * @return $isset Whether start/end marker are set
2594 public final function ifStartEndMarkersSet ($data) {
2596 $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));
2598 // ... and return it
2603 * Determines if an element is set in the generic array
2605 * @param $keyGroup Main group for the key
2606 * @param $subGroup Sub group for the key
2607 * @param $key Key to check
2608 * @param $element Element to check
2609 * @return $isset Whether the given key is set
2611 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2613 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2616 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2622 * Determines if a key is set in the generic array
2624 * @param $keyGroup Main group for the key
2625 * @param $subGroup Sub group for the key
2626 * @param $key Key to check
2627 * @return $isset Whether the given key is set
2629 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2631 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2634 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2642 * Determines if a group is set in the generic array
2644 * @param $keyGroup Main group
2645 * @param $subGroup Sub group
2646 * @return $isset Whether the given group is set
2648 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2650 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2653 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2660 * Getter for sub key group
2662 * @param $keyGroup Main key group
2663 * @param $subGroup Sub key group
2664 * @return $array An array with all array elements
2666 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2668 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2669 // No, then abort here
2670 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2675 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2678 return $this->genericArray[$keyGroup][$subGroup];
2682 * Unsets a given key in generic array
2684 * @param $keyGroup Main group for the key
2685 * @param $subGroup Sub group for the key
2686 * @param $key Key to unset
2689 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2691 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2694 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2698 * Unsets a given element in generic array
2700 * @param $keyGroup Main group for the key
2701 * @param $subGroup Sub group for the key
2702 * @param $key Key to unset
2703 * @param $element Element to unset
2706 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2708 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2711 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2715 * Append a string to a given generic array key
2717 * @param $keyGroup Main group for the key
2718 * @param $subGroup Sub group for the key
2719 * @param $key Key to unset
2720 * @param $value Value to add/append
2723 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2725 //* 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);
2727 // Is it already there?
2728 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2730 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2733 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2738 * Append a string to a given generic array element
2740 * @param $keyGroup Main group for the key
2741 * @param $subGroup Sub group for the key
2742 * @param $key Key to unset
2743 * @param $element Element to check
2744 * @param $value Value to add/append
2747 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2749 //* 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);
2751 // Is it already there?
2752 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2754 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2757 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2762 * Initializes given generic array group
2764 * @param $keyGroup Main group for the key
2765 * @param $subGroup Sub group for the key
2766 * @param $key Key to use
2767 * @param $forceInit Optionally force initialization
2770 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2772 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2774 // Is it already set?
2775 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2776 // Already initialized
2777 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2782 $this->genericArray[$keyGroup][$subGroup] = array();
2786 * Initializes given generic array key
2788 * @param $keyGroup Main group for the key
2789 * @param $subGroup Sub group for the key
2790 * @param $key Key to use
2791 * @param $forceInit Optionally force initialization
2794 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2796 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2798 // Is it already set?
2799 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2800 // Already initialized
2801 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2806 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2810 * Initializes given 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 use
2816 * @param $forceInit Optionally force initialization
2819 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2821 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2823 // Is it already set?
2824 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2825 // Already initialized
2826 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2831 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2835 * Pushes an element to a generic key
2837 * @param $keyGroup Main group for the key
2838 * @param $subGroup Sub group for the key
2839 * @param $key Key to use
2840 * @param $value Value to add/append
2841 * @return $count Number of array elements
2843 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2845 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2848 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2850 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2854 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2857 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2858 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2863 * Pushes an element to a generic array element
2865 * @param $keyGroup Main group for the key
2866 * @param $subGroup Sub group for the key
2867 * @param $key Key to use
2868 * @param $element Element to check
2869 * @param $value Value to add/append
2870 * @return $count Number of array elements
2872 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2874 //* 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));
2877 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2879 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2883 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2886 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2887 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2892 * Pops an element from a generic group
2894 * @param $keyGroup Main group for the key
2895 * @param $subGroup Sub group for the key
2896 * @param $key Key to unset
2897 * @return $value Last "popped" value
2899 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2901 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2904 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2906 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2911 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2914 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2915 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2920 * Shifts an element from a generic group
2922 * @param $keyGroup Main group for the key
2923 * @param $subGroup Sub group for the key
2924 * @param $key Key to unset
2925 * @return $value Last "popped" value
2927 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2929 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2932 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2934 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2939 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2942 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2943 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2948 * Count generic array group
2950 * @param $keyGroup Main group for the key
2951 * @return $count Count of given group
2953 protected final function countGenericArray ($keyGroup) {
2955 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2958 if (!isset($this->genericArray[$keyGroup])) {
2960 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2965 $count = count($this->genericArray[$keyGroup]);
2968 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2975 * Count generic array sub group
2977 * @param $keyGroup Main group for the key
2978 * @param $subGroup Sub group for the key
2979 * @return $count Count of given group
2981 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2983 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2986 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2988 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2993 $count = count($this->genericArray[$keyGroup][$subGroup]);
2996 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3003 * Count generic array elements
3005 * @param $keyGroup Main group for the key
3006 * @param $subGroup Sub group for the key
3007 * @para $key Key to count
3008 * @return $count Count of given key
3010 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3012 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3015 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3017 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3019 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3021 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3026 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3029 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3036 * Getter for whole generic group array
3038 * @param $keyGroup Key group to get
3039 * @return $array Whole generic array group
3041 protected final function getGenericArray ($keyGroup) {
3043 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3046 if (!isset($this->genericArray[$keyGroup])) {
3048 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3053 return $this->genericArray[$keyGroup];
3057 * Setter for generic array key
3059 * @param $keyGroup Key group to get
3060 * @param $subGroup Sub group for the key
3061 * @param $key Key to unset
3062 * @param $value Mixed value from generic array element
3065 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3067 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3070 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3074 * Getter for generic array key
3076 * @param $keyGroup Key group to get
3077 * @param $subGroup Sub group for the key
3078 * @param $key Key to unset
3079 * @return $value Mixed value from generic array element
3081 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3083 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3086 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3088 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3093 return $this->genericArray[$keyGroup][$subGroup][$key];
3097 * Sets a value in given generic array key/element
3099 * @param $keyGroup Main group for the key
3100 * @param $subGroup Sub group for the key
3101 * @param $key Key to set
3102 * @param $element Element to set
3103 * @param $value Value to set
3106 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3108 //* 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));
3111 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3115 * Getter for generic array element
3117 * @param $keyGroup Key group to get
3118 * @param $subGroup Sub group for the key
3119 * @param $key Key to look for
3120 * @param $element Element to look for
3121 * @return $value Mixed value from generic array element
3123 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3125 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3128 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3130 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3135 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3139 * Checks if a given sub group is valid (array)
3141 * @param $keyGroup Key group to get
3142 * @param $subGroup Sub group for the key
3143 * @return $isValid Whether given sub group is valid
3145 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3147 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3150 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3157 * Checks if a given key is valid (array)
3159 * @param $keyGroup Key group to get
3160 * @param $subGroup Sub group for the key
3161 * @param $key Key to check
3162 * @return $isValid Whether given sub group is valid
3164 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3166 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3169 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3176 * Initializes the web output instance
3180 protected function initWebOutputInstance () {
3181 // Get application instance
3182 $applicationInstance = Registry::getRegistry()->getInstance('app');
3184 // Is this a response instance?
3185 if ($this instanceof Responseable) {
3186 // Then set it in application instance
3187 $applicationInstance->setResponseInstance($this);
3190 // Init web output instance
3191 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3194 $this->setWebOutputInstance($outputInstance);
3198 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3200 * @param $boolean Boolean value
3201 * @return $translated Translated boolean value
3203 public static final function translateBooleanToYesNo ($boolean) {
3204 // Make sure it is really boolean
3205 assert(is_bool($boolean));
3208 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3210 // ... and return it
3215 * Encodes raw data (almost any type) by "serializing" it and then pack it
3216 * into a "binary format".
3218 * @param $rawData Raw data (almost any type)
3219 * @return $encoded Encoded data
3221 protected function encodeData ($rawData) {
3222 // Make sure no objects or resources pass through
3223 assert(!is_object($rawData));
3224 assert(!is_resource($rawData));
3226 // First "serialize" it (json_encode() is faster than serialize())
3227 $encoded = $this->packString(json_encode($rawData));
3234 * Pack a string into a "binary format". Please execuse me that this is
3235 * widely undocumented. :-(
3237 * @param $str Unpacked string
3238 * @return $packed Packed string
3239 * @todo Improve documentation
3241 protected function packString ($str) {
3243 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3245 // First compress the string (gzcompress is okay)
3246 $str = gzcompress($str);
3251 // And start the "encoding" loop
3252 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3254 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3255 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3257 if (($idx + $i) <= strlen($str)) {
3258 $ord = ord(substr($str, ($idx + $i), 1));
3260 $add = $ord * pow(256, $factor);
3264 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3268 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3269 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3271 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3272 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3278 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');
3283 * Checks whether the given file/path is in open_basedir(). This does not
3284 * gurantee that the file is actually readable and/or writeable. If you need
3285 * such gurantee then please use isReadableFile() instead.
3287 * @param $filePathName Name of the file/path to be checked
3288 * @return $isReachable Whether it is within open_basedir()
3290 public static function isReachableFilePath ($filePathName) {
3291 // Is not reachable by default
3292 $isReachable = FALSE;
3294 // Get open_basedir parameter
3295 $openBaseDir = ini_get('open_basedir');
3298 if (!empty($openBaseDir)) {
3299 // Check all entries
3300 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3301 // Check on existence
3302 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3304 $isReachable = TRUE;
3308 // If open_basedir is not set, all is allowed
3309 $isReachable = TRUE;
3313 return $isReachable;
3317 * Checks whether the give file is within open_basedir() (done by
3318 * isReachableFilePath()), is actually a file and is readable.
3320 * @param $fileName Name of the file to be checked
3321 * @return $isReadable Whether the file is readable (and therefor exists)
3323 public static function isReadableFile ($fileName) {
3324 // Default is not readable
3325 $isReadable = FALSE;
3327 // Is within parameters, so check if it is a file and readable
3328 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));