3 namespace CoreFramework\Object;
5 // Load framework stuff
6 use CoreFramework\Generic\FrameworkInterface;
9 * The simulator system class is the super class of all other classes. This
10 * class handles saving of games etc.
12 * @author Roland Haeder <webmaster@shipsimu.org>
14 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
15 * @license GNU GPL 3.0 or any newer version
16 * @link http://www.shipsimu.org
18 * This program is free software: you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation, either version 3 of the License, or
21 * (at your option) any later version.
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
28 * You should have received a copy of the GNU General Public License
29 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
33 * Length of output from hash()
35 private static $hashLength = NULL;
40 private $realClass = 'BaseFrameworkSystem';
43 * Instance of a request class
45 private $requestInstance = NULL;
48 * Instance of a response class
50 private $responseInstance = NULL;
53 * Search criteria instance
55 private $searchInstance = NULL;
58 * Update criteria instance
60 private $updateInstance = NULL;
63 * The file I/O instance for the template loader
65 private $fileIoInstance = NULL;
70 private $resolverInstance = NULL;
73 * Template engine instance
75 private $templateInstance = NULL;
78 * Database result instance
80 private $resultInstance = NULL;
83 * Instance for user class
85 private $userInstance = NULL;
88 * A controller instance
90 private $controllerInstance = NULL;
95 private $rngInstance = NULL;
98 * Instance of a crypto helper
100 private $cryptoInstance = NULL;
103 * Instance of an Iterator class
105 private $iteratorInstance = NULL;
108 * Instance of the list
110 private $listInstance = NULL;
115 private $menuInstance = NULL;
118 * Instance of the image
120 private $imageInstance = NULL;
123 * Instance of the stacker
125 private $stackInstance = NULL;
128 * A Compressor instance
130 private $compressorInstance = NULL;
133 * A Parseable instance
135 private $parserInstance = NULL;
138 * A HandleableProtocol instance
140 private $protocolInstance = NULL;
143 * A database wrapper instance
145 private $databaseInstance = NULL;
148 * A helper instance for the form
150 private $helperInstance = NULL;
153 * An instance of a Source class
155 private $sourceInstance = NULL;
158 * An instance of a UrlSource class
160 private $urlSourceInstance = NULL;
163 * An instance of a InputStream class
165 private $inputStreamInstance = NULL;
168 * An instance of a OutputStream class
170 private $outputStreamInstance = NULL;
173 * Networkable handler instance
175 private $handlerInstance = NULL;
178 * Visitor handler instance
180 private $visitorInstance = NULL;
185 private $dhtInstance = NULL;
188 * An instance of a database wrapper class
190 private $wrapperInstance = NULL;
193 * An instance of a file I/O pointer class (not handler)
195 private $pointerInstance = NULL;
198 * An instance of an Indexable class
200 private $indexInstance = NULL;
203 * An instance of a Block class
205 private $blockInstance = NULL;
210 private $minableInstance = NULL;
213 * A FrameworkDirectory instance
215 private $directoryInstance = NULL;
220 private $listenerInstance = NULL;
223 * An instance of a communicator
225 private $communicatorInstance = NULL;
228 * The concrete output instance
230 private $outputInstance = NULL;
235 private $stateInstance = NULL;
238 * Thousands separator
240 private $thousands = '.'; // German
245 private $decimals = ','; // German
250 private $socketResource = FALSE;
253 * Regular expression to use for validation
255 private $regularExpression = '';
260 private $packageData = array();
265 private $genericArray = array();
270 private $commandName = '';
275 private $controllerName = '';
278 * Name of used protocol
280 private $protocolName = 'invalid';
283 * Array with bitmasks and such for pack/unpack methods to support both
284 * 32-bit and 64-bit systems
286 private $packingData = array(
289 'left' => 0xffff0000,
290 'right' => 0x0000ffff,
296 'left' => 0xffffffff00000000,
297 'right' => 0x00000000ffffffff,
304 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
306 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
308 private $archArrayElement = FALSE;
310 /***********************
311 * Exception codes.... *
312 ***********************/
314 // @todo Try to clean these constants up
315 const EXCEPTION_IS_NULL_POINTER = 0x001;
316 const EXCEPTION_IS_NO_OBJECT = 0x002;
317 const EXCEPTION_IS_NO_ARRAY = 0x003;
318 const EXCEPTION_MISSING_METHOD = 0x004;
319 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
320 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
321 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
322 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
323 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
324 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
325 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
326 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
327 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
328 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
329 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
330 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
331 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
332 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
333 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
334 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
335 const EXCEPTION_PATH_NOT_FOUND = 0x015;
336 const EXCEPTION_INVALID_PATH_NAME = 0x016;
337 const EXCEPTION_READ_PROTECED_PATH = 0x017;
338 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
339 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
340 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
341 const EXCEPTION_INVALID_RESOURCE = 0x01b;
342 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
343 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
344 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
345 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
346 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
347 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
348 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
349 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
350 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
351 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
352 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
353 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
354 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
355 const EXCEPTION_INVALID_STRING = 0x029;
356 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
357 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
358 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
359 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
360 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
361 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
362 const EXCEPTION_MISSING_ELEMENT = 0x030;
363 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
364 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
365 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
366 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
367 const EXCEPTION_FATAL_ERROR = 0x035;
368 const EXCEPTION_FILE_NOT_FOUND = 0x036;
369 const EXCEPTION_ASSERTION_FAILED = 0x037;
370 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
371 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
372 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
373 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
374 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
375 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
378 * Hexadecimal->Decimal translation array
380 private static $hexdec = array(
400 * Decimal->hexadecimal translation array
402 private static $dechex = array(
422 * Startup time in miliseconds
424 private static $startupTime = 0;
427 * Protected super constructor
429 * @param $className Name of the class
432 protected function __construct ($className) {
434 $this->setRealClass($className);
436 // Set configuration instance if no registry ...
437 if (!$this instanceof Register) {
438 // ... because registries doesn't need to be configured
439 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
442 // Is the startup time set? (0 cannot be TRUE anymore)
443 if (self::$startupTime == 0) {
445 self::$startupTime = microtime(TRUE);
449 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
453 * Destructor for all classes. You should not call this method on your own.
457 public function __destruct () {
458 // Flush any updated entries to the database
459 $this->flushPendingUpdates();
461 // Is this object already destroyed?
462 if ($this->__toString() != 'DestructedObject') {
463 // Destroy all informations about this class but keep some text about it alive
464 $this->setRealClass('DestructedObject');
465 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
466 // Already destructed object
467 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
472 // Do not call this twice
473 trigger_error(__METHOD__ . ': Called twice.');
479 * The __call() method where all non-implemented methods end up
481 * @param $methodName Name of the missing method
482 * @args $args Arguments passed to the method
485 public final function __call ($methodName, $args) {
486 return self::__callStatic($methodName, $args);
490 * The __callStatic() method where all non-implemented static methods end up
492 * @param $methodName Name of the missing method
493 * @args $args Arguments passed to the method
496 public static final function __callStatic ($methodName, $args) {
497 // Init argument string
500 // Is it NULL, empty or an array?
501 if (is_null($args)) {
503 $argsString = 'NULL';
504 } elseif (is_array($args)) {
508 // Some arguments are there
509 foreach ($args as $arg) {
510 // Add data about the argument
511 $argsString .= gettype($arg) . ':';
514 // Found a NULL argument
515 $argsString .= 'NULL';
516 } elseif (is_string($arg)) {
517 // Add length for strings
518 $argsString .= strlen($arg);
519 } elseif ((is_int($arg)) || (is_float($arg))) {
522 } elseif (is_array($arg)) {
523 // .. or size if array
524 $argsString .= count($arg);
525 } elseif (is_object($arg)) {
527 $reflection = new ReflectionClass($arg);
529 // Is an other object, maybe no __toString() available
530 $argsString .= $reflection->getName();
531 } elseif ($arg === TRUE) {
532 // ... is boolean 'TRUE'
533 $argsString .= 'TRUE';
534 } elseif ($arg === FALSE) {
535 // ... is boolean 'FALSE'
536 $argsString .= 'FALSE';
539 // Comma for next one
544 if (substr($argsString, -2, 1) == ',') {
545 $argsString = substr($argsString, 0, -2);
551 // Invalid arguments!
552 $argsString = '!INVALID:' . gettype($args) . '!';
555 // Output stub message
556 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
557 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
567 * Getter for $realClass
569 * @return $realClass The name of the real class (not BaseFrameworkSystem)
571 public function __toString () {
572 return $this->realClass;
576 * Magic method to catch setting of missing but set class fields/attributes
578 * @param $name Name of the field/attribute
579 * @param $value Value to store
582 public final function __set ($name, $value) {
583 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
586 print_r($value, TRUE)
591 * Magic method to catch getting of missing fields/attributes
593 * @param $name Name of the field/attribute
596 public final function __get ($name) {
597 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
603 * Magic method to catch unsetting of missing fields/attributes
605 * @param $name Name of the field/attribute
608 public final function __unset ($name) {
609 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
615 * Magic method to catch object serialization
617 * @return $unsupported Unsupported method
618 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
620 public final function __sleep () {
621 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
625 * Magic method to catch object deserialization
627 * @return $unsupported Unsupported method
628 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
630 public final function __wakeup () {
631 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
635 * Magic method to catch calls when an object instance is called
637 * @return $unsupported Unsupported method
638 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
640 public final function __invoke () {
641 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
645 * Setter for the real class name
647 * @param $realClass Class name (string)
650 public final function setRealClass ($realClass) {
652 $this->realClass = (string) $realClass;
656 * Setter for database result instance
658 * @param $resultInstance An instance of a database result class
660 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
662 protected final function setResultInstance (SearchableResult $resultInstance) {
663 $this->resultInstance = $resultInstance;
667 * Getter for database result instance
669 * @return $resultInstance An instance of a database result class
671 public final function getResultInstance () {
672 return $this->resultInstance;
676 * Setter for template engine instances
678 * @param $templateInstance An instance of a template engine class
681 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
682 $this->templateInstance = $templateInstance;
686 * Getter for template engine instances
688 * @return $templateInstance An instance of a template engine class
690 protected final function getTemplateInstance () {
691 return $this->templateInstance;
695 * Setter for search instance
697 * @param $searchInstance Searchable criteria instance
700 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
701 $this->searchInstance = $searchInstance;
705 * Getter for search instance
707 * @return $searchInstance Searchable criteria instance
709 public final function getSearchInstance () {
710 return $this->searchInstance;
714 * Setter for update instance
716 * @param $updateInstance Searchable criteria instance
719 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
720 $this->updateInstance = $updateInstance;
724 * Getter for update instance
726 * @return $updateInstance Updateable criteria instance
728 public final function getUpdateInstance () {
729 return $this->updateInstance;
733 * Setter for resolver instance
735 * @param $resolverInstance Instance of a command resolver class
738 public final function setResolverInstance (Resolver $resolverInstance) {
739 $this->resolverInstance = $resolverInstance;
743 * Getter for resolver instance
745 * @return $resolverInstance Instance of a command resolver class
747 public final function getResolverInstance () {
748 return $this->resolverInstance;
752 * Setter for language instance
754 * @param $configInstance The configuration instance which shall
755 * be FrameworkConfiguration
758 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
759 Registry::getRegistry()->addInstance('config', $configInstance);
763 * Getter for configuration instance
765 * @return $configInstance Configuration instance
767 public final function getConfigInstance () {
768 $configInstance = Registry::getRegistry()->getInstance('config');
769 return $configInstance;
773 * Setter for debug instance
775 * @param $debugInstance The instance for debug output class
778 public final function setDebugInstance (DebugMiddleware $debugInstance) {
779 Registry::getRegistry()->addInstance('debug', $debugInstance);
783 * Getter for debug instance
785 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
787 public final function getDebugInstance () {
788 // Get debug instance
789 $debugInstance = Registry::getRegistry()->getInstance('debug');
792 return $debugInstance;
796 * Setter for web output instance
798 * @param $webInstance The instance for web output class
801 public final function setWebOutputInstance (OutputStreamer $webInstance) {
802 Registry::getRegistry()->addInstance('web_output', $webInstance);
806 * Getter for web output instance
808 * @return $webOutputInstance - Instance to class WebOutput
810 public final function getWebOutputInstance () {
811 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
812 return $webOutputInstance;
816 * Setter for database instance
818 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
821 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
822 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
826 * Getter for database layer
828 * @return $databaseInstance The database layer instance
830 public final function getDatabaseInstance () {
832 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
835 return $databaseInstance;
839 * Setter for compressor channel
841 * @param $compressorInstance An instance of CompressorChannel
844 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
845 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
849 * Getter for compressor channel
851 * @return $compressorInstance The compressor channel
853 public final function getCompressorChannel () {
854 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
855 return $compressorInstance;
859 * Protected getter for a manageable application helper class
861 * @return $applicationInstance An instance of a manageable application helper class
863 protected final function getApplicationInstance () {
864 $applicationInstance = Registry::getRegistry()->getInstance('application');
865 return $applicationInstance;
869 * Setter for a manageable application helper class
871 * @param $applicationInstance An instance of a manageable application helper class
874 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
875 Registry::getRegistry()->addInstance('application', $applicationInstance);
879 * Setter for request instance
881 * @param $requestInstance An instance of a Requestable class
884 public final function setRequestInstance (Requestable $requestInstance) {
885 $this->requestInstance = $requestInstance;
889 * Getter for request instance
891 * @return $requestInstance An instance of a Requestable class
893 public final function getRequestInstance () {
894 return $this->requestInstance;
898 * Setter for response instance
900 * @param $responseInstance An instance of a Responseable class
903 public final function setResponseInstance (Responseable $responseInstance) {
904 $this->responseInstance = $responseInstance;
908 * Getter for response instance
910 * @return $responseInstance An instance of a Responseable class
912 public final function getResponseInstance () {
913 return $this->responseInstance;
917 * Private getter for language instance
919 * @return $langInstance An instance to the language sub-system
921 protected final function getLanguageInstance () {
922 $langInstance = Registry::getRegistry()->getInstance('language');
923 return $langInstance;
927 * Setter for language instance
929 * @param $langInstance An instance to the language sub-system
931 * @see LanguageSystem
933 public final function setLanguageInstance (ManageableLanguage $langInstance) {
934 Registry::getRegistry()->addInstance('language', $langInstance);
938 * Private getter for file IO instance
940 * @return $fileIoInstance An instance to the file I/O sub-system
942 protected final function getFileIoInstance () {
943 return $this->fileIoInstance;
947 * Setter for file I/O instance
949 * @param $fileIoInstance An instance to the file I/O sub-system
952 public final function setFileIoInstance (IoHandler $fileIoInstance) {
953 $this->fileIoInstance = $fileIoInstance;
957 * Protected setter for user instance
959 * @param $userInstance An instance of a user class
962 protected final function setUserInstance (ManageableAccount $userInstance) {
963 $this->userInstance = $userInstance;
967 * Getter for user instance
969 * @return $userInstance An instance of a user class
971 public final function getUserInstance () {
972 return $this->userInstance;
976 * Setter for controller instance (this surely breaks a bit the MVC patterm)
978 * @param $controllerInstance An instance of the controller
981 public final function setControllerInstance (Controller $controllerInstance) {
982 $this->controllerInstance = $controllerInstance;
986 * Getter for controller instance (this surely breaks a bit the MVC patterm)
988 * @return $controllerInstance An instance of the controller
990 public final function getControllerInstance () {
991 return $this->controllerInstance;
995 * Setter for RNG instance
997 * @param $rngInstance An instance of a random number generator (RNG)
1000 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1001 $this->rngInstance = $rngInstance;
1005 * Getter for RNG instance
1007 * @return $rngInstance An instance of a random number generator (RNG)
1009 public final function getRngInstance () {
1010 return $this->rngInstance;
1014 * Setter for Cryptable instance
1016 * @param $cryptoInstance An instance of a Cryptable class
1019 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1020 $this->cryptoInstance = $cryptoInstance;
1024 * Getter for Cryptable instance
1026 * @return $cryptoInstance An instance of a Cryptable class
1028 public final function getCryptoInstance () {
1029 return $this->cryptoInstance;
1033 * Setter for the list instance
1035 * @param $listInstance A list of Listable
1038 protected final function setListInstance (Listable $listInstance) {
1039 $this->listInstance = $listInstance;
1043 * Getter for the list instance
1045 * @return $listInstance A list of Listable
1047 protected final function getListInstance () {
1048 return $this->listInstance;
1052 * Setter for the menu instance
1054 * @param $menuInstance A RenderableMenu instance
1057 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1058 $this->menuInstance = $menuInstance;
1062 * Getter for the menu instance
1064 * @return $menuInstance A RenderableMenu instance
1066 protected final function getMenuInstance () {
1067 return $this->menuInstance;
1071 * Setter for image instance
1073 * @param $imageInstance An instance of an image
1076 public final function setImageInstance (BaseImage $imageInstance) {
1077 $this->imageInstance = $imageInstance;
1081 * Getter for image instance
1083 * @return $imageInstance An instance of an image
1085 public final function getImageInstance () {
1086 return $this->imageInstance;
1090 * Setter for stacker instance
1092 * @param $stackInstance An instance of an stacker
1095 public final function setStackInstance (Stackable $stackInstance) {
1096 $this->stackInstance = $stackInstance;
1100 * Getter for stacker instance
1102 * @return $stackInstance An instance of an stacker
1104 public final function getStackInstance () {
1105 return $this->stackInstance;
1109 * Setter for compressor instance
1111 * @param $compressorInstance An instance of an compressor
1114 public final function setCompressorInstance (Compressor $compressorInstance) {
1115 $this->compressorInstance = $compressorInstance;
1119 * Getter for compressor instance
1121 * @return $compressorInstance An instance of an compressor
1123 public final function getCompressorInstance () {
1124 return $this->compressorInstance;
1128 * Setter for Parseable instance
1130 * @param $parserInstance An instance of an Parseable
1133 public final function setParserInstance (Parseable $parserInstance) {
1134 $this->parserInstance = $parserInstance;
1138 * Getter for Parseable instance
1140 * @return $parserInstance An instance of an Parseable
1142 public final function getParserInstance () {
1143 return $this->parserInstance;
1147 * Setter for HandleableProtocol instance
1149 * @param $protocolInstance An instance of an HandleableProtocol
1152 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1153 $this->protocolInstance = $protocolInstance;
1157 * Getter for HandleableProtocol instance
1159 * @return $protocolInstance An instance of an HandleableProtocol
1161 public final function getProtocolInstance () {
1162 return $this->protocolInstance;
1166 * Setter for DatabaseWrapper instance
1168 * @param $wrapperInstance An instance of an DatabaseWrapper
1171 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1172 $this->wrapperInstance = $wrapperInstance;
1176 * Getter for DatabaseWrapper instance
1178 * @return $wrapperInstance An instance of an DatabaseWrapper
1180 public final function getWrapperInstance () {
1181 return $this->wrapperInstance;
1185 * Setter for socket resource
1187 * @param $socketResource A valid socket resource
1190 public final function setSocketResource ($socketResource) {
1191 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1192 $this->socketResource = $socketResource;
1196 * Getter for socket resource
1198 * @return $socketResource A valid socket resource
1200 public final function getSocketResource () {
1201 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1202 return $this->socketResource;
1206 * Setter for regular expression
1208 * @param $regularExpression A valid regular expression
1211 public final function setRegularExpression ($regularExpression) {
1212 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1213 $this->regularExpression = $regularExpression;
1217 * Getter for regular expression
1219 * @return $regularExpression A valid regular expression
1221 public final function getRegularExpression () {
1222 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1223 return $this->regularExpression;
1227 * Setter for helper instance
1229 * @param $helperInstance An instance of a helper class
1232 protected final function setHelperInstance (Helper $helperInstance) {
1233 $this->helperInstance = $helperInstance;
1237 * Getter for helper instance
1239 * @return $helperInstance An instance of a helper class
1241 public final function getHelperInstance () {
1242 return $this->helperInstance;
1246 * Setter for a Source instance
1248 * @param $sourceInstance An instance of a Source class
1251 protected final function setSourceInstance (Source $sourceInstance) {
1252 $this->sourceInstance = $sourceInstance;
1256 * Getter for a Source instance
1258 * @return $sourceInstance An instance of a Source class
1260 protected final function getSourceInstance () {
1261 return $this->sourceInstance;
1265 * Setter for a UrlSource instance
1267 * @param $sourceInstance An instance of a UrlSource class
1270 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1271 $this->urlSourceInstance = $urlSourceInstance;
1275 * Getter for a UrlSource instance
1277 * @return $urlSourceInstance An instance of a UrlSource class
1279 protected final function getUrlSourceInstance () {
1280 return $this->urlSourceInstance;
1284 * Getter for a InputStream instance
1286 * @param $inputStreamInstance The InputStream instance
1288 protected final function getInputStreamInstance () {
1289 return $this->inputStreamInstance;
1293 * Setter for a InputStream instance
1295 * @param $inputStreamInstance The InputStream instance
1298 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1299 $this->inputStreamInstance = $inputStreamInstance;
1303 * Getter for a OutputStream instance
1305 * @param $outputStreamInstance The OutputStream instance
1307 protected final function getOutputStreamInstance () {
1308 return $this->outputStreamInstance;
1312 * Setter for a OutputStream instance
1314 * @param $outputStreamInstance The OutputStream instance
1317 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1318 $this->outputStreamInstance = $outputStreamInstance;
1322 * Setter for handler instance
1324 * @param $handlerInstance An instance of a Handleable class
1327 protected final function setHandlerInstance (Handleable $handlerInstance) {
1328 $this->handlerInstance = $handlerInstance;
1332 * Getter for handler instance
1334 * @return $handlerInstance A Networkable instance
1336 protected final function getHandlerInstance () {
1337 return $this->handlerInstance;
1341 * Setter for visitor instance
1343 * @param $visitorInstance A Visitor instance
1346 protected final function setVisitorInstance (Visitor $visitorInstance) {
1347 $this->visitorInstance = $visitorInstance;
1351 * Getter for visitor instance
1353 * @return $visitorInstance A Visitor instance
1355 protected final function getVisitorInstance () {
1356 return $this->visitorInstance;
1360 * Setter for DHT instance
1362 * @param $dhtInstance A Distributable instance
1365 protected final function setDhtInstance (Distributable $dhtInstance) {
1366 $this->dhtInstance = $dhtInstance;
1370 * Getter for DHT instance
1372 * @return $dhtInstance A Distributable instance
1374 protected final function getDhtInstance () {
1375 return $this->dhtInstance;
1379 * Setter for raw package Data
1381 * @param $packageData Raw package Data
1384 public final function setPackageData (array $packageData) {
1385 $this->packageData = $packageData;
1389 * Getter for raw package Data
1391 * @return $packageData Raw package Data
1393 public function getPackageData () {
1394 return $this->packageData;
1399 * Setter for Iterator instance
1401 * @param $iteratorInstance An instance of an Iterator
1404 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1405 $this->iteratorInstance = $iteratorInstance;
1409 * Getter for Iterator instance
1411 * @return $iteratorInstance An instance of an Iterator
1413 public final function getIteratorInstance () {
1414 return $this->iteratorInstance;
1418 * Setter for FilePointer instance
1420 * @param $pointerInstance An instance of an FilePointer class
1423 protected final function setPointerInstance (FilePointer $pointerInstance) {
1424 $this->pointerInstance = $pointerInstance;
1428 * Getter for FilePointer instance
1430 * @return $pointerInstance An instance of an FilePointer class
1432 public final function getPointerInstance () {
1433 return $this->pointerInstance;
1437 * Unsets pointer instance which triggers a call of __destruct() if the
1438 * instance is still there. This is surely not fatal on already "closed"
1439 * file pointer instances.
1441 * I don't want to mess around with above setter by giving it a default
1442 * value NULL as setter should always explicitly only set (existing) object
1443 * instances and NULL is NULL.
1447 protected final function unsetPointerInstance () {
1448 // Simply it to NULL
1449 $this->pointerInstance = NULL;
1453 * Setter for Indexable instance
1455 * @param $indexInstance An instance of an Indexable class
1458 protected final function setIndexInstance (Indexable $indexInstance) {
1459 $this->indexInstance = $indexInstance;
1463 * Getter for Indexable instance
1465 * @return $indexInstance An instance of an Indexable class
1467 public final function getIndexInstance () {
1468 return $this->indexInstance;
1472 * Setter for Block instance
1474 * @param $blockInstance An instance of an Block class
1477 protected final function setBlockInstance (Block $blockInstance) {
1478 $this->blockInstance = $blockInstance;
1482 * Getter for Block instance
1484 * @return $blockInstance An instance of an Block class
1486 public final function getBlockInstance () {
1487 return $this->blockInstance;
1491 * Setter for Minable instance
1493 * @param $minableInstance A Minable instance
1496 protected final function setMinableInstance (Minable $minableInstance) {
1497 $this->minableInstance = $minableInstance;
1501 * Getter for minable instance
1503 * @return $minableInstance A Minable instance
1505 protected final function getMinableInstance () {
1506 return $this->minableInstance;
1510 * Setter for FrameworkDirectory instance
1512 * @param $directoryInstance A FrameworkDirectoryPointer instance
1515 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1516 $this->directoryInstance = $directoryInstance;
1520 * Getter for FrameworkDirectory instance
1522 * @return $directoryInstance A FrameworkDirectory instance
1524 protected final function getDirectoryInstance () {
1525 return $this->directoryInstance;
1529 * Setter for listener instance
1531 * @param $listenerInstance A Listenable instance
1534 protected final function setListenerInstance (Listenable $listenerInstance) {
1535 $this->listenerInstance = $listenerInstance;
1539 * Getter for listener instance
1541 * @return $listenerInstance A Listenable instance
1543 protected final function getListenerInstance () {
1544 return $this->listenerInstance;
1548 * Getter for communicator instance
1550 * @return $communicatorInstance An instance of a Communicator class
1552 public final function getCommunicatorInstance () {
1553 return $this->communicatorInstance;
1557 * Setter for communicator instance
1559 * @param $communicatorInstance An instance of a Communicator class
1562 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1563 $this->communicatorInstance = $communicatorInstance;
1567 * Setter for state instance
1569 * @param $stateInstance A Stateable instance
1572 public final function setStateInstance (Stateable $stateInstance) {
1573 $this->stateInstance = $stateInstance;
1577 * Getter for state instance
1579 * @return $stateInstance A Stateable instance
1581 public final function getStateInstance () {
1582 return $this->stateInstance;
1586 * Setter for output instance
1588 * @param $outputInstance The debug output instance
1591 public final function setOutputInstance (OutputStreamer $outputInstance) {
1592 $this->outputInstance = $outputInstance;
1596 * Getter for output instance
1598 * @return $outputInstance The debug output instance
1600 public final function getOutputInstance () {
1601 return $this->outputInstance;
1605 * Setter for command name
1607 * @param $commandName Last validated command name
1610 protected final function setCommandName ($commandName) {
1611 $this->commandName = $commandName;
1615 * Getter for command name
1617 * @return $commandName Last validated command name
1619 protected final function getCommandName () {
1620 return $this->commandName;
1624 * Setter for controller name
1626 * @param $controllerName Last validated controller name
1629 protected final function setControllerName ($controllerName) {
1630 $this->controllerName = $controllerName;
1634 * Getter for controller name
1636 * @return $controllerName Last validated controller name
1638 protected final function getControllerName () {
1639 return $this->controllerName;
1643 * Getter for protocol name
1645 * @return $protocolName Name of used protocol
1647 public final function getProtocolName () {
1648 return $this->protocolName;
1652 * Setter for protocol name
1654 * @param $protocolName Name of used protocol
1657 protected final function setProtocolName ($protocolName) {
1658 $this->protocolName = $protocolName;
1662 * Checks whether an object equals this object. You should overwrite this
1663 * method to implement own equality checks
1665 * @param $objectInstance An instance of a FrameworkInterface object
1666 * @return $equals Whether both objects equals
1668 public function equals (FrameworkInterface $objectInstance) {
1671 $this->__toString() == $objectInstance->__toString()
1673 $this->hashCode() == $objectInstance->hashCode()
1676 // Return the result
1681 * Generates a generic hash code of this class. You should really overwrite
1682 * this method with your own hash code generator code. But keep KISS in mind.
1684 * @return $hashCode A generic hash code respresenting this whole class
1686 public function hashCode () {
1688 return crc32($this->__toString());
1692 * Formats computer generated price values into human-understandable formats
1693 * with thousand and decimal separators.
1695 * @param $value The in computer format value for a price
1696 * @param $currency The currency symbol (use HTML-valid characters!)
1697 * @param $decNum Number of decimals after commata
1698 * @return $price The for the current language formated price string
1699 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1700 * thousands separator
1703 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1704 // Are all required attriutes set?
1705 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1706 // Throw an exception
1707 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1711 $value = (float) $value;
1713 // Reformat the US number
1714 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1716 // Return as string...
1721 * Appends a trailing slash to a string
1723 * @param $str A string (maybe) without trailing slash
1724 * @return $str A string with an auto-appended trailing slash
1726 public final function addMissingTrailingSlash ($str) {
1727 // Is there a trailing slash?
1728 if (substr($str, -1, 1) != '/') {
1732 // Return string with trailing slash
1737 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1738 * application helper instance (ApplicationHelper by default).
1740 * @param $applicationInstance An application helper instance or
1741 * null if we shall use the default
1742 * @return $templateInstance The template engine instance
1743 * @throws NullPointerException If the discovered application
1744 * instance is still null
1746 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1747 // Is the application instance set?
1748 if (is_null($applicationInstance)) {
1749 // Get the current instance
1750 $applicationInstance = $this->getApplicationInstance();
1753 if (is_null($applicationInstance)) {
1754 // Thrown an exception
1755 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1759 // Initialize the template engine
1760 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1762 // Return the prepared instance
1763 return $templateInstance;
1767 * Debugs this instance by putting out it's full content
1769 * @param $message Optional message to show in debug output
1772 public final function debugInstance ($message = '') {
1773 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1774 restore_error_handler();
1779 // Is a message set?
1780 if (!empty($message)) {
1781 // Construct message
1782 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1785 // Generate the output
1786 $content .= sprintf('<pre>%s</pre>',
1789 print_r($this, TRUE)
1795 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>',
1796 $this->__toString(),
1798 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1803 * Replaces control characters with printable output
1805 * @param $str String with control characters
1806 * @return $str Replaced string
1808 protected function replaceControlCharacters ($str) {
1811 chr(13), '[r]', str_replace(
1812 chr(10), '[n]', str_replace(
1822 * Output a partial stub message for the caller method
1824 * @param $message An optional message to display
1827 protected function partialStub ($message = '') {
1828 // Get the backtrace
1829 $backtrace = debug_backtrace();
1831 // Generate the class::method string
1832 $methodName = 'UnknownClass->unknownMethod';
1833 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1834 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1837 // Construct the full message
1838 $stubMessage = sprintf('[%s:] Partial stub!',
1842 // Is the extra message given?
1843 if (!empty($message)) {
1844 // Then add it as well
1845 $stubMessage .= ' Message: ' . $message;
1848 // Debug instance is there?
1849 if (!is_null($this->getDebugInstance())) {
1850 // Output stub message
1851 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1854 trigger_error($stubMessage);
1860 * Outputs a debug backtrace and stops further script execution
1862 * @param $message An optional message to output
1863 * @param $doExit Whether exit the program (TRUE is default)
1866 public function debugBackTrace ($message = '', $doExit = TRUE) {
1867 // Sorry, there is no other way getting this nice backtrace
1868 if (!empty($message)) {
1870 printf('Message: %s<br />' . PHP_EOL, $message);
1874 debug_print_backtrace();
1878 if ($doExit === TRUE) {
1884 * Creates an instance of a debugger instance
1886 * @param $className Name of the class (currently unsupported)
1887 * @return $debugInstance An instance of a debugger class
1888 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1890 public final static function createDebugInstance ($className) {
1891 // Is the instance set?
1892 if (!Registry::getRegistry()->instanceExists('debug')) {
1893 // Init debug instance
1894 $debugInstance = NULL;
1898 // Get a debugger instance
1899 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1900 } catch (NullPointerException $e) {
1901 // Didn't work, no instance there
1902 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1905 // Empty string should be ignored and used for testing the middleware
1906 DebugMiddleware::getSelfInstance()->output('');
1908 // Set it in its own class. This will set it in the registry
1909 $debugInstance->setDebugInstance($debugInstance);
1911 // Get instance from registry
1912 $debugInstance = Registry::getRegistry()->getDebugInstance();
1916 return $debugInstance;
1920 * Simple output of a message with line-break
1922 * @param $message Message to output
1925 public function outputLine ($message) {
1927 print($message . PHP_EOL);
1931 * Outputs a debug message whether to debug instance (should be set!) or
1932 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1933 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1935 * @param $message Message we shall send out...
1936 * @param $doPrint Whether print or die here (default: print)
1937 * @paran $stripTags Whether to strip tags (default: FALSE)
1940 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1941 // Set debug instance to NULL
1942 $debugInstance = NULL;
1946 // Get debug instance
1947 $debugInstance = $this->getDebugInstance();
1948 } catch (NullPointerException $e) {
1949 // The debug instance is not set (yet)
1952 // Is the debug instance there?
1953 if (is_object($debugInstance)) {
1954 // Use debug output handler
1955 $debugInstance->output($message, $stripTags);
1957 if ($doPrint === FALSE) {
1958 // Die here if not printed
1962 // Are debug times enabled?
1963 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1965 $message = $this->getPrintableExecutionTime() . $message;
1969 if ($doPrint === TRUE) {
1971 $this->outputLine($message);
1980 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1982 * @param $str The string, what ever it is needs to be converted
1983 * @return $className Generated class name
1985 public static final function convertToClassName ($str) {
1989 // Convert all dashes in underscores
1990 $str = self::convertDashesToUnderscores($str);
1992 // Now use that underscores to get classname parts for hungarian style
1993 foreach (explode('_', $str) as $strPart) {
1994 // Make the class name part lower case and first upper case
1995 $className .= ucfirst(strtolower($strPart));
1998 // Return class name
2003 * Converts dashes to underscores, e.g. useable for configuration entries
2005 * @param $str The string with maybe dashes inside
2006 * @return $str The converted string with no dashed, but underscores
2008 public static final function convertDashesToUnderscores ($str) {
2010 $str = str_replace('-', '_', $str);
2012 // Return converted string
2017 * Marks up the code by adding e.g. line numbers
2019 * @param $phpCode Unmarked PHP code
2020 * @return $markedCode Marked PHP code
2022 public function markupCode ($phpCode) {
2027 $errorArray = error_get_last();
2029 // Init the code with error message
2030 if (is_array($errorArray)) {
2032 $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>',
2033 basename($errorArray['file']),
2034 $errorArray['line'],
2035 $errorArray['message'],
2040 // Add line number to the code
2041 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2043 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2045 htmlentities($code, ENT_QUOTES)
2054 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2055 * beatiful for web-based front-ends. If null is given a message id
2056 * null_timestamp will be resolved and returned.
2058 * @param $timestamp Timestamp to prepare (filter) for display
2059 * @return $readable A readable timestamp
2061 public function doFilterFormatTimestamp ($timestamp) {
2062 // Default value to return
2065 // Is the timestamp null?
2066 if (is_null($timestamp)) {
2067 // Get a message string
2068 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2070 switch ($this->getLanguageInstance()->getLanguageCode()) {
2071 case 'de': // German format is a bit different to default
2072 // Split the GMT stamp up
2073 $dateTime = explode(' ', $timestamp );
2074 $dateArray = explode('-', $dateTime[0]);
2075 $timeArray = explode(':', $dateTime[1]);
2077 // Construct the timestamp
2078 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2088 default: // Default is pass-through
2089 $readable = $timestamp;
2099 * Filter a given number into a localized number
2101 * @param $value The raw value from e.g. database
2102 * @return $localized Localized value
2104 public function doFilterFormatNumber ($value) {
2105 // Generate it from config and localize dependencies
2106 switch ($this->getLanguageInstance()->getLanguageCode()) {
2107 case 'de': // German format is a bit different to default
2108 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2111 default: // US, etc.
2112 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2121 * "Getter" for databse entry
2123 * @return $entry An array with database entries
2124 * @throws NullPointerException If the database result is not found
2125 * @throws InvalidDatabaseResultException If the database result is invalid
2127 protected final function getDatabaseEntry () {
2128 // Is there an instance?
2129 if (!$this->getResultInstance() instanceof SearchableResult) {
2130 // Throw an exception here
2131 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2135 $this->getResultInstance()->rewind();
2137 // Do we have an entry?
2138 if ($this->getResultInstance()->valid() === FALSE) {
2139 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2140 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2144 $this->getResultInstance()->next();
2147 $entry = $this->getResultInstance()->current();
2154 * Getter for field name
2156 * @param $fieldName Field name which we shall get
2157 * @return $fieldValue Field value from the user
2158 * @throws NullPointerException If the result instance is null
2160 public final function getField ($fieldName) {
2161 // Default field value
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 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2177 // Convert dashes to underscore
2178 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2180 // Does the field exist?
2181 if ($this->isFieldSet($fieldName)) {
2183 $fieldValue = $fieldArray[$fieldName2];
2184 } elseif (defined('DEVELOPER')) {
2185 // Missing field entry, may require debugging
2186 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2188 // Missing field entry, may require debugging
2189 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2197 * Checks if given field is set
2199 * @param $fieldName Field name to check
2200 * @return $isSet Whether the given field name is set
2201 * @throws NullPointerException If the result instance is null
2203 public function isFieldSet ($fieldName) {
2204 // Get result instance
2205 $resultInstance = $this->getResultInstance();
2207 // Is this instance null?
2208 if (is_null($resultInstance)) {
2209 // Then the user instance is no longer valid (expired cookies?)
2210 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2213 // Get current array
2214 $fieldArray = $resultInstance->current();
2215 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2217 // Convert dashes to underscore
2218 $fieldName = self::convertDashesToUnderscores($fieldName);
2221 $isSet = isset($fieldArray[$fieldName]);
2228 * Flushs all pending updates to the database layer
2232 public function flushPendingUpdates () {
2233 // Get result instance
2234 $resultInstance = $this->getResultInstance();
2236 // Do we have data to update?
2237 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2238 // Get wrapper class name config entry
2239 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2241 // Create object instance
2242 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2244 // Yes, then send the whole result to the database layer
2245 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2250 * Outputs a deprecation warning to the developer.
2252 * @param $message The message we shall output to the developer
2254 * @todo Write a logging mechanism for productive mode
2256 public function deprecationWarning ($message) {
2257 // Is developer mode active?
2258 if (defined('DEVELOPER')) {
2259 // Debug instance is there?
2260 if (!is_null($this->getDebugInstance())) {
2261 // Output stub message
2262 self::createDebugInstance(__CLASS__)->debugOutput($message);
2265 trigger_error($message . "<br />\n");
2269 // @TODO Finish this part!
2270 $this->partialStub('Developer mode inactive. Message:' . $message);
2275 * Checks whether the given PHP extension is loaded
2277 * @param $phpExtension The PHP extension we shall check
2278 * @return $isLoaded Whether the PHP extension is loaded
2280 public final function isPhpExtensionLoaded ($phpExtension) {
2282 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2289 * "Getter" as a time() replacement but with milliseconds. You should use this
2290 * method instead of the encapsulated getimeofday() function.
2292 * @return $milliTime Timestamp with milliseconds
2294 public function getMilliTime () {
2295 // Get the time of day as float
2296 $milliTime = gettimeofday(TRUE);
2303 * Idles (sleeps) for given milliseconds
2305 * @return $hasSlept Whether it goes fine
2307 public function idle ($milliSeconds) {
2308 // Sleep is fine by default
2311 // Idle so long with found function
2312 if (function_exists('time_sleep_until')) {
2313 // Get current time and add idle time
2314 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2316 // New PHP 5.1.0 function found, ignore errors
2317 $hasSlept = @time_sleep_until($sleepUntil);
2320 * My Sun station doesn't have that function even with latest PHP
2323 usleep($milliSeconds * 1000);
2330 * Converts a hexadecimal string, even with negative sign as first string to
2331 * a decimal number using BC functions.
2333 * This work is based on comment #86673 on php.net documentation page at:
2334 * <http://de.php.net/manual/en/function.dechex.php#86673>
2336 * @param $hex Hexadecimal string
2337 * @return $dec Decimal number
2339 protected function hex2dec ($hex) {
2340 // Convert to all lower-case
2341 $hex = strtolower($hex);
2343 // Detect sign (negative/positive numbers)
2345 if (substr($hex, 0, 1) == '-') {
2347 $hex = substr($hex, 1);
2350 // Decode the hexadecimal string into a decimal number
2352 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2353 $factor = self::$hexdec[substr($hex, $i, 1)];
2354 $dec = bcadd($dec, bcmul($factor, $e));
2357 // Return the decimal number
2358 return $sign . $dec;
2362 * Converts even very large decimal numbers, also signed, to a hexadecimal
2365 * This work is based on comment #97756 on php.net documentation page at:
2366 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2368 * @param $dec Decimal number, even with negative sign
2369 * @param $maxLength Optional maximum length of the string
2370 * @return $hex Hexadecimal string
2372 protected function dec2hex ($dec, $maxLength = 0) {
2373 // maxLength can be zero or devideable by 2
2374 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2376 // Detect sign (negative/positive numbers)
2383 // Encode the decimal number into a hexadecimal string
2386 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2388 } while ($dec >= 1);
2391 * Leading zeros are required for hex-decimal "numbers". In some
2392 * situations more leading zeros are wanted, so check for both
2395 if ($maxLength > 0) {
2396 // Prepend more zeros
2397 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2398 } elseif ((strlen($hex) % 2) != 0) {
2399 // Only make string's length dividable by 2
2403 // Return the hexadecimal string
2404 return $sign . $hex;
2408 * Converts a ASCII string (0 to 255) into a decimal number.
2410 * @param $asc The ASCII string to be converted
2411 * @return $dec Decimal number
2413 protected function asc2dec ($asc) {
2414 // Convert it into a hexadecimal number
2415 $hex = bin2hex($asc);
2417 // And back into a decimal number
2418 $dec = $this->hex2dec($hex);
2425 * Converts a decimal number into an ASCII string.
2427 * @param $dec Decimal number
2428 * @return $asc An ASCII string
2430 protected function dec2asc ($dec) {
2431 // First convert the number into a hexadecimal string
2432 $hex = $this->dec2hex($dec);
2434 // Then convert it into the ASCII string
2435 $asc = $this->hex2asc($hex);
2442 * Converts a hexadecimal number into an ASCII string. Negative numbers
2445 * @param $hex Hexadecimal string
2446 * @return $asc An ASCII string
2448 protected function hex2asc ($hex) {
2449 // Check for length, it must be devideable by 2
2450 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2451 assert((strlen($hex) % 2) == 0);
2455 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2456 // Get the decimal number of the chunk
2457 $part = hexdec(substr($hex, $idx, 2));
2459 // Add it to the final string
2463 // Return the final string
2468 * Checks whether the given encoded data was encoded with Base64
2470 * @param $encodedData Encoded data we shall check
2471 * @return $isBase64 Whether the encoded data is Base64
2473 protected function isBase64Encoded ($encodedData) {
2475 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2482 * "Getter" to get response/request type from analysis of the system.
2484 * @return $responseType Analyzed response type
2486 protected static function getResponseTypeFromSystem () {
2487 // Default is console
2488 $responseType = 'console';
2490 // Is 'HTTP_HOST' set?
2491 if (isset($_SERVER['HTTP_HOST'])) {
2493 * Then it is a HTML response/request as RSS and so on may be
2494 * transfered over HTTP as well.
2496 $responseType = 'html';
2500 return $responseType;
2504 * Gets a cache key from Criteria instance
2506 * @param $criteriaInstance An instance of a Criteria class
2507 * @param $onlyKeys Only use these keys for a cache key
2508 * @return $cacheKey A cache key suitable for lookup/storage purposes
2510 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2512 $cacheKey = sprintf('%s@%s',
2513 $this->__toString(),
2514 $criteriaInstance->getCacheKey($onlyKeys)
2518 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2523 * Getter for startup time in miliseconds
2525 * @return $startupTime Startup time in miliseconds
2527 protected function getStartupTime () {
2528 return self::$startupTime;
2532 * "Getter" for a printable currently execution time in nice braces
2534 * @return $executionTime Current execution time in nice braces
2536 protected function getPrintableExecutionTime () {
2537 // Caculate the execution time
2538 $executionTime = microtime(TRUE) - $this->getStartupTime();
2540 // Pack it in nice braces
2541 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2544 return $executionTime;
2548 * Hashes a given string with a simple but stronger hash function (no salt)
2549 * and hex-encode it.
2551 * @param $str The string to be hashed
2552 * @return $hash The hash from string $str
2554 public static final function hash ($str) {
2555 // Hash given string with (better secure) hasher
2556 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2563 * "Getter" for length of hash() output. This will be "cached" to speed up
2566 * @return $length Length of hash() output
2568 public static final function getHashLength () {
2570 if (is_null(self::$hashLength)) {
2571 // No, then hash a string and save its length.
2572 self::$hashLength = strlen(self::hash('abc123'));
2576 return self::$hashLength;
2580 * Checks whether the given number is really a number (only chars 0-9).
2582 * @param $num A string consisting only chars between 0 and 9
2583 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2584 * @param $assertMismatch Whether to assert mismatches
2585 * @return $ret The (hopefully) secured numbered value
2587 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2588 // Filter all numbers out
2589 $ret = preg_replace('/[^0123456789]/', '', $num);
2592 if ($castValue === TRUE) {
2593 // Cast to biggest numeric type
2594 $ret = (double) $ret;
2597 // Assert only if requested
2598 if ($assertMismatch === TRUE) {
2599 // Has the whole value changed?
2600 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2608 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2610 * @param $num A string consisting only chars between 0 and 9
2611 * @param $assertMismatch Whether to assert mismatches
2612 * @return $ret The (hopefully) secured hext-numbered value
2614 public function hexval ($num, $assertMismatch = FALSE) {
2615 // Filter all numbers out
2616 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2618 // Assert only if requested
2619 if ($assertMismatch === TRUE) {
2620 // Has the whole value changed?
2621 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2629 * Checks whether start/end marker are set
2631 * @param $data Data to be checked
2632 * @return $isset Whether start/end marker are set
2634 public final function ifStartEndMarkersSet ($data) {
2636 $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));
2638 // ... and return it
2643 * Determines if an element is set in the generic array
2645 * @param $keyGroup Main group for the key
2646 * @param $subGroup Sub group for the key
2647 * @param $key Key to check
2648 * @param $element Element to check
2649 * @return $isset Whether the given key is set
2651 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2653 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2656 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2662 * Determines if a key is set in the generic array
2664 * @param $keyGroup Main group for the key
2665 * @param $subGroup Sub group for the key
2666 * @param $key Key to check
2667 * @return $isset Whether the given key is set
2669 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2671 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2674 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2682 * Determines if a group is set in the generic array
2684 * @param $keyGroup Main group
2685 * @param $subGroup Sub group
2686 * @return $isset Whether the given group is set
2688 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2690 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2693 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2700 * Getter for sub key group
2702 * @param $keyGroup Main key group
2703 * @param $subGroup Sub key group
2704 * @return $array An array with all array elements
2706 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2708 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2709 // No, then abort here
2710 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2715 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2718 return $this->genericArray[$keyGroup][$subGroup];
2722 * Unsets a given key in generic array
2724 * @param $keyGroup Main group for the key
2725 * @param $subGroup Sub group for the key
2726 * @param $key Key to unset
2729 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2731 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2734 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2738 * Unsets a given element in generic array
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 unset
2746 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2748 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2751 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2755 * Append a string to a given generic array key
2757 * @param $keyGroup Main group for the key
2758 * @param $subGroup Sub group for the key
2759 * @param $key Key to unset
2760 * @param $value Value to add/append
2763 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2765 //* 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);
2767 // Is it already there?
2768 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2770 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2773 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2778 * Append a string to a given generic array element
2780 * @param $keyGroup Main group for the key
2781 * @param $subGroup Sub group for the key
2782 * @param $key Key to unset
2783 * @param $element Element to check
2784 * @param $value Value to add/append
2787 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2789 //* 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);
2791 // Is it already there?
2792 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2794 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2797 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2802 * Sets a string in a given generic array element
2804 * @param $keyGroup Main group for the key
2805 * @param $subGroup Sub group for the key
2806 * @param $key Key to unset
2807 * @param $element Element to check
2808 * @param $value Value to add/append
2811 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2813 //* 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);
2816 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2820 * Initializes given generic array group
2822 * @param $keyGroup Main group for the key
2823 * @param $subGroup Sub group for the key
2824 * @param $key Key to use
2825 * @param $forceInit Optionally force initialization
2828 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2830 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2832 // Is it already set?
2833 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2834 // Already initialized
2835 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2840 $this->genericArray[$keyGroup][$subGroup] = array();
2844 * Initializes given generic array key
2846 * @param $keyGroup Main group for the key
2847 * @param $subGroup Sub group for the key
2848 * @param $key Key to use
2849 * @param $forceInit Optionally force initialization
2852 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2854 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2856 // Is it already set?
2857 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2858 // Already initialized
2859 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2864 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2868 * Initializes given generic array element
2870 * @param $keyGroup Main group for the key
2871 * @param $subGroup Sub group for the key
2872 * @param $key Key to use
2873 * @param $element Element to use
2874 * @param $forceInit Optionally force initialization
2877 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2879 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2881 // Is it already set?
2882 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2883 // Already initialized
2884 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2889 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2893 * Pushes an element to a generic key
2895 * @param $keyGroup Main group for the key
2896 * @param $subGroup Sub group for the key
2897 * @param $key Key to use
2898 * @param $value Value to add/append
2899 * @return $count Number of array elements
2901 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2903 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2906 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2908 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2912 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2915 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2916 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2921 * Pushes an element to a generic array element
2923 * @param $keyGroup Main group for the key
2924 * @param $subGroup Sub group for the key
2925 * @param $key Key to use
2926 * @param $element Element to check
2927 * @param $value Value to add/append
2928 * @return $count Number of array elements
2930 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2932 //* 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));
2935 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2937 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2941 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2944 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2945 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2950 * Pops an element from a generic group
2952 * @param $keyGroup Main group for the key
2953 * @param $subGroup Sub group for the key
2954 * @param $key Key to unset
2955 * @return $value Last "popped" value
2957 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2959 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2962 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2964 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2969 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2972 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2973 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2978 * Shifts an element from a generic group
2980 * @param $keyGroup Main group for the key
2981 * @param $subGroup Sub group for the key
2982 * @param $key Key to unset
2983 * @return $value Last "popped" value
2985 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2987 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2990 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2992 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2997 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3000 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3001 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3006 * Count generic array group
3008 * @param $keyGroup Main group for the key
3009 * @return $count Count of given group
3011 protected final function countGenericArray ($keyGroup) {
3013 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3016 if (!isset($this->genericArray[$keyGroup])) {
3018 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3023 $count = count($this->genericArray[$keyGroup]);
3026 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3033 * Count generic array sub group
3035 * @param $keyGroup Main group for the key
3036 * @param $subGroup Sub group for the key
3037 * @return $count Count of given group
3039 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3041 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3044 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3046 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3051 $count = count($this->genericArray[$keyGroup][$subGroup]);
3054 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3061 * Count generic array elements
3063 * @param $keyGroup Main group for the key
3064 * @param $subGroup Sub group for the key
3065 * @para $key Key to count
3066 * @return $count Count of given key
3068 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3070 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3073 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3075 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3077 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3079 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3084 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3087 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3094 * Getter for whole generic group array
3096 * @param $keyGroup Key group to get
3097 * @return $array Whole generic array group
3099 protected final function getGenericArray ($keyGroup) {
3101 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3104 if (!isset($this->genericArray[$keyGroup])) {
3106 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3111 return $this->genericArray[$keyGroup];
3115 * Setter for generic array key
3117 * @param $keyGroup Key group to get
3118 * @param $subGroup Sub group for the key
3119 * @param $key Key to unset
3120 * @param $value Mixed value from generic array element
3123 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3125 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3128 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3132 * Getter for generic array key
3134 * @param $keyGroup Key group to get
3135 * @param $subGroup Sub group for the key
3136 * @param $key Key to unset
3137 * @return $value Mixed value from generic array element
3139 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3141 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3144 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3146 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3151 return $this->genericArray[$keyGroup][$subGroup][$key];
3155 * Sets a value in given generic array key/element
3157 * @param $keyGroup Main group for the key
3158 * @param $subGroup Sub group for the key
3159 * @param $key Key to set
3160 * @param $element Element to set
3161 * @param $value Value to set
3164 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3166 //* 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));
3169 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3173 * Getter for generic array element
3175 * @param $keyGroup Key group to get
3176 * @param $subGroup Sub group for the key
3177 * @param $key Key to look for
3178 * @param $element Element to look for
3179 * @return $value Mixed value from generic array element
3181 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3183 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3186 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3188 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3193 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3197 * Checks if a given sub group is valid (array)
3199 * @param $keyGroup Key group to get
3200 * @param $subGroup Sub group for the key
3201 * @return $isValid Whether given sub group is valid
3203 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3205 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3208 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3215 * Checks if a given key is valid (array)
3217 * @param $keyGroup Key group to get
3218 * @param $subGroup Sub group for the key
3219 * @param $key Key to check
3220 * @return $isValid Whether given sub group is valid
3222 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3224 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3227 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3234 * Initializes the web output instance
3238 protected function initWebOutputInstance () {
3239 // Get application instance
3240 $applicationInstance = Registry::getRegistry()->getInstance('app');
3242 // Is this a response instance?
3243 if ($this instanceof Responseable) {
3244 // Then set it in application instance
3245 $applicationInstance->setResponseInstance($this);
3248 // Init web output instance
3249 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3252 $this->setWebOutputInstance($outputInstance);
3256 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3258 * @param $boolean Boolean value
3259 * @return $translated Translated boolean value
3261 public static final function translateBooleanToYesNo ($boolean) {
3262 // Make sure it is really boolean
3263 assert(is_bool($boolean));
3266 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3268 // ... and return it
3273 * Encodes raw data (almost any type) by "serializing" it and then pack it
3274 * into a "binary format".
3276 * @param $rawData Raw data (almost any type)
3277 * @return $encoded Encoded data
3279 protected function encodeData ($rawData) {
3280 // Make sure no objects or resources pass through
3281 assert(!is_object($rawData));
3282 assert(!is_resource($rawData));
3284 // First "serialize" it (json_encode() is faster than serialize())
3285 $encoded = $this->packString(json_encode($rawData));
3292 * Pack a string into a "binary format". Please execuse me that this is
3293 * widely undocumented. :-(
3295 * @param $str Unpacked string
3296 * @return $packed Packed string
3297 * @todo Improve documentation
3299 protected function packString ($str) {
3301 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3303 // First compress the string (gzcompress is okay)
3304 $str = gzcompress($str);
3309 // And start the "encoding" loop
3310 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3312 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3313 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3315 if (($idx + $i) <= strlen($str)) {
3316 $ord = ord(substr($str, ($idx + $i), 1));
3318 $add = $ord * pow(256, $factor);
3322 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3326 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3327 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3329 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3330 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3336 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');
3341 * Checks whether the given file/path is in open_basedir(). This does not
3342 * gurantee that the file is actually readable and/or writeable. If you need
3343 * such gurantee then please use isReadableFile() instead.
3345 * @param $filePathName Name of the file/path to be checked
3346 * @return $isReachable Whether it is within open_basedir()
3348 protected static function isReachableFilePath ($filePathName) {
3349 // Is not reachable by default
3350 $isReachable = FALSE;
3352 // Get open_basedir parameter
3353 $openBaseDir = ini_get('open_basedir');
3356 if (!empty($openBaseDir)) {
3357 // Check all entries
3358 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3359 // Check on existence
3360 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3362 $isReachable = TRUE;
3366 // If open_basedir is not set, all is allowed
3367 $isReachable = TRUE;
3371 return $isReachable;
3375 * Checks whether the give file is within open_basedir() (done by
3376 * isReachableFilePath()), is actually a file and is readable.
3378 * @param $fileName Name of the file to be checked
3379 * @return $isReadable Whether the file is readable (and therefor exists)
3381 public static function isReadableFile ($fileName) {
3382 // Default is not readable
3383 $isReadable = FALSE;
3385 // Is within parameters, so check if it is a file and readable
3386 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3393 * Creates a full-qualified file name (FQFN) for given file name by adding
3394 * a configured temporary file path to it.
3396 * @param $fileName Name for temporary file
3397 * @return $fqfn Full-qualified file name
3398 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3399 * @throws FileIoException If the file cannot be written
3401 protected static function createTempPathForFile ($fileName) {
3403 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3405 // Is the path writeable?
3406 if (!is_writable($basePath)) {
3407 // Path is write-protected
3408 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3412 $fqfn = $basePath . '/' . $fileName;
3415 if (!self::isReachableFilePath($fqfn)) {
3417 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3425 * "Getter" for a printable state name
3427 * @return $stateName Name of the node's state in a printable format
3429 public final function getPrintableState () {
3430 // Default is 'null'
3431 $stateName = 'null';
3433 // Get the state instance
3434 $stateInstance = $this->getStateInstance();
3436 // Is it an instance of Stateable?
3437 if ($stateInstance instanceof Stateable) {
3438 // Then use that state name
3439 $stateName = $stateInstance->getStateName();
3447 * Handles socket error for given socket resource and peer data. This method
3448 * validates $socketResource if it is a valid resource (see is_resource())
3449 * but assumes valid data in array $recipientData, except that
3450 * count($recipientData) is always 2.
3452 * @param $method Value of __METHOD__ from calling method
3453 * @param $line Value of __LINE__ from calling method
3454 * @param $socketResource A valid socket resource
3455 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3457 * @throws InvalidSocketException If $socketResource is no socket resource
3458 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3459 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3461 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3462 // This method handles only socket resources
3463 if (!is_resource($socketResource)) {
3464 // No resource, abort here
3465 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3468 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3469 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3470 assert(isset($socketData[0]));
3471 assert(isset($socketData[1]));
3473 // Get error code for first validation (0 is not an error)
3474 $errorCode = socket_last_error($socketResource);
3476 // If the error code is zero, someone called this method without an error
3477 if ($errorCode == 0) {
3478 // No error detected (or previously cleared outside this method)
3479 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3482 // Get handler (method) name
3483 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3485 // Call-back the error handler method
3486 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3488 // Finally clear the error because it has been handled
3489 socket_clear_error($socketResource);