3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Generic\FrameworkInterface;
8 use CoreFramework\Manager\ManageableApplication;
14 * The simulator system class is the super class of all other classes. This
15 * class handles saving of games etc.
17 * @author Roland Haeder <webmaster@shipsimu.org>
19 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
20 * @license GNU GPL 3.0 or any newer version
21 * @link http://www.shipsimu.org
23 * This program is free software: you can redistribute it and/or modify
24 * it under the terms of the GNU General Public License as published by
25 * the Free Software Foundation, either version 3 of the License, or
26 * (at your option) any later version.
28 * This program is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU General Public License for more details.
33 * You should have received a copy of the GNU General Public License
34 * along with this program. If not, see <http://www.gnu.org/licenses/>.
36 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
38 * Length of output from hash()
40 private static $hashLength = NULL;
45 private $realClass = 'BaseFrameworkSystem';
48 * Instance of a request class
50 private $requestInstance = NULL;
53 * Instance of a response class
55 private $responseInstance = NULL;
58 * Search criteria instance
60 private $searchInstance = NULL;
63 * Update criteria instance
65 private $updateInstance = NULL;
68 * The file I/O instance for the template loader
70 private $fileIoInstance = NULL;
75 private $resolverInstance = NULL;
78 * Template engine instance
80 private $templateInstance = NULL;
83 * Database result instance
85 private $resultInstance = NULL;
88 * Instance for user class
90 private $userInstance = NULL;
93 * A controller instance
95 private $controllerInstance = NULL;
100 private $rngInstance = NULL;
103 * Instance of a crypto helper
105 private $cryptoInstance = NULL;
108 * Instance of an Iterator class
110 private $iteratorInstance = NULL;
113 * Instance of the list
115 private $listInstance = NULL;
120 private $menuInstance = NULL;
123 * Instance of the image
125 private $imageInstance = NULL;
128 * Instance of the stacker
130 private $stackInstance = NULL;
133 * A Compressor instance
135 private $compressorInstance = NULL;
138 * A Parseable instance
140 private $parserInstance = NULL;
143 * A HandleableProtocol instance
145 private $protocolInstance = NULL;
148 * A database wrapper instance
150 private $databaseInstance = NULL;
153 * A helper instance for the form
155 private $helperInstance = NULL;
158 * An instance of a Source class
160 private $sourceInstance = NULL;
163 * An instance of a UrlSource class
165 private $urlSourceInstance = NULL;
168 * An instance of a InputStream class
170 private $inputStreamInstance = NULL;
173 * An instance of a OutputStream class
175 private $outputStreamInstance = NULL;
178 * Networkable handler instance
180 private $handlerInstance = NULL;
183 * Visitor handler instance
185 private $visitorInstance = NULL;
190 private $dhtInstance = NULL;
193 * An instance of a database wrapper class
195 private $wrapperInstance = NULL;
198 * An instance of a file I/O pointer class (not handler)
200 private $pointerInstance = NULL;
203 * An instance of an Indexable class
205 private $indexInstance = NULL;
208 * An instance of a Block class
210 private $blockInstance = NULL;
215 private $minableInstance = NULL;
218 * A FrameworkDirectory instance
220 private $directoryInstance = NULL;
225 private $listenerInstance = NULL;
228 * An instance of a communicator
230 private $communicatorInstance = NULL;
233 * The concrete output instance
235 private $outputInstance = NULL;
240 private $stateInstance = NULL;
243 * Thousands separator
245 private $thousands = '.'; // German
250 private $decimals = ','; // German
255 private $socketResource = FALSE;
258 * Regular expression to use for validation
260 private $regularExpression = '';
265 private $packageData = array();
270 private $genericArray = array();
275 private $commandName = '';
280 private $controllerName = '';
283 * Name of used protocol
285 private $protocolName = 'invalid';
288 * Array with bitmasks and such for pack/unpack methods to support both
289 * 32-bit and 64-bit systems
291 private $packingData = array(
294 'left' => 0xffff0000,
295 'right' => 0x0000ffff,
301 'left' => 0xffffffff00000000,
302 'right' => 0x00000000ffffffff,
309 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
311 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
313 private $archArrayElement = FALSE;
315 /***********************
316 * Exception codes.... *
317 ***********************/
319 // @todo Try to clean these constants up
320 const EXCEPTION_IS_NULL_POINTER = 0x001;
321 const EXCEPTION_IS_NO_OBJECT = 0x002;
322 const EXCEPTION_IS_NO_ARRAY = 0x003;
323 const EXCEPTION_MISSING_METHOD = 0x004;
324 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
325 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
326 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
327 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
328 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
329 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
330 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
331 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
332 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
333 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
334 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
335 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
336 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
337 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
338 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
339 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
340 const EXCEPTION_PATH_NOT_FOUND = 0x015;
341 const EXCEPTION_INVALID_PATH_NAME = 0x016;
342 const EXCEPTION_READ_PROTECED_PATH = 0x017;
343 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
344 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
345 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
346 const EXCEPTION_INVALID_RESOURCE = 0x01b;
347 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
348 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
349 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
350 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
351 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
352 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
353 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
354 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
355 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
356 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
357 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
358 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
359 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
360 const EXCEPTION_INVALID_STRING = 0x029;
361 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
362 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
363 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
364 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
365 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
366 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
367 const EXCEPTION_MISSING_ELEMENT = 0x030;
368 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
369 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
370 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
371 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
372 const EXCEPTION_FATAL_ERROR = 0x035;
373 const EXCEPTION_FILE_NOT_FOUND = 0x036;
374 const EXCEPTION_ASSERTION_FAILED = 0x037;
375 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
376 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
377 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
378 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
379 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
380 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
383 * Hexadecimal->Decimal translation array
385 private static $hexdec = array(
405 * Decimal->hexadecimal translation array
407 private static $dechex = array(
427 * Startup time in miliseconds
429 private static $startupTime = 0;
432 * Protected super constructor
434 * @param $className Name of the class
437 protected function __construct ($className) {
439 $this->setRealClass($className);
441 // Set configuration instance if no registry ...
442 if (!$this instanceof Register) {
443 // ... because registries doesn't need to be configured
444 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
447 // Is the startup time set? (0 cannot be TRUE anymore)
448 if (self::$startupTime == 0) {
450 self::$startupTime = microtime(TRUE);
454 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
458 * Destructor for all classes. You should not call this method on your own.
462 public function __destruct () {
463 // Flush any updated entries to the database
464 $this->flushPendingUpdates();
466 // Is this object already destroyed?
467 if ($this->__toString() != 'DestructedObject') {
468 // Destroy all informations about this class but keep some text about it alive
469 $this->setRealClass('DestructedObject');
470 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
471 // Already destructed object
472 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
477 // Do not call this twice
478 trigger_error(__METHOD__ . ': Called twice.');
484 * The __call() method where all non-implemented methods end up
486 * @param $methodName Name of the missing method
487 * @args $args Arguments passed to the method
490 public final function __call ($methodName, $args) {
491 return self::__callStatic($methodName, $args);
495 * The __callStatic() method where all non-implemented static methods end up
497 * @param $methodName Name of the missing method
498 * @args $args Arguments passed to the method
501 public static final function __callStatic ($methodName, $args) {
502 // Init argument string
505 // Is it NULL, empty or an array?
506 if (is_null($args)) {
508 $argsString = 'NULL';
509 } elseif (is_array($args)) {
513 // Some arguments are there
514 foreach ($args as $arg) {
515 // Add data about the argument
516 $argsString .= gettype($arg) . ':';
519 // Found a NULL argument
520 $argsString .= 'NULL';
521 } elseif (is_string($arg)) {
522 // Add length for strings
523 $argsString .= strlen($arg);
524 } elseif ((is_int($arg)) || (is_float($arg))) {
527 } elseif (is_array($arg)) {
528 // .. or size if array
529 $argsString .= count($arg);
530 } elseif (is_object($arg)) {
532 $reflection = new ReflectionClass($arg);
534 // Is an other object, maybe no __toString() available
535 $argsString .= $reflection->getName();
536 } elseif ($arg === TRUE) {
537 // ... is boolean 'TRUE'
538 $argsString .= 'TRUE';
539 } elseif ($arg === FALSE) {
540 // ... is boolean 'FALSE'
541 $argsString .= 'FALSE';
544 // Comma for next one
549 if (substr($argsString, -2, 1) == ',') {
550 $argsString = substr($argsString, 0, -2);
556 // Invalid arguments!
557 $argsString = '!INVALID:' . gettype($args) . '!';
560 // Output stub message
561 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
562 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
572 * Getter for $realClass
574 * @return $realClass The name of the real class (not BaseFrameworkSystem)
576 public function __toString () {
577 return $this->realClass;
581 * Magic method to catch setting of missing but set class fields/attributes
583 * @param $name Name of the field/attribute
584 * @param $value Value to store
587 public final function __set ($name, $value) {
588 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
591 print_r($value, TRUE)
596 * Magic method to catch getting of missing fields/attributes
598 * @param $name Name of the field/attribute
601 public final function __get ($name) {
602 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
608 * Magic method to catch unsetting of missing fields/attributes
610 * @param $name Name of the field/attribute
613 public final function __unset ($name) {
614 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
620 * Magic method to catch object serialization
622 * @return $unsupported Unsupported method
623 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
625 public final function __sleep () {
626 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
630 * Magic method to catch object deserialization
632 * @return $unsupported Unsupported method
633 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
635 public final function __wakeup () {
636 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
640 * Magic method to catch calls when an object instance is called
642 * @return $unsupported Unsupported method
643 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
645 public final function __invoke () {
646 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
650 * Setter for the real class name
652 * @param $realClass Class name (string)
655 public final function setRealClass ($realClass) {
657 $this->realClass = (string) $realClass;
661 * Setter for database result instance
663 * @param $resultInstance An instance of a database result class
665 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
667 protected final function setResultInstance (SearchableResult $resultInstance) {
668 $this->resultInstance = $resultInstance;
672 * Getter for database result instance
674 * @return $resultInstance An instance of a database result class
676 public final function getResultInstance () {
677 return $this->resultInstance;
681 * Setter for template engine instances
683 * @param $templateInstance An instance of a template engine class
686 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
687 $this->templateInstance = $templateInstance;
691 * Getter for template engine instances
693 * @return $templateInstance An instance of a template engine class
695 protected final function getTemplateInstance () {
696 return $this->templateInstance;
700 * Setter for search instance
702 * @param $searchInstance Searchable criteria instance
705 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
706 $this->searchInstance = $searchInstance;
710 * Getter for search instance
712 * @return $searchInstance Searchable criteria instance
714 public final function getSearchInstance () {
715 return $this->searchInstance;
719 * Setter for update instance
721 * @param $updateInstance Searchable criteria instance
724 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
725 $this->updateInstance = $updateInstance;
729 * Getter for update instance
731 * @return $updateInstance Updateable criteria instance
733 public final function getUpdateInstance () {
734 return $this->updateInstance;
738 * Setter for resolver instance
740 * @param $resolverInstance Instance of a command resolver class
743 public final function setResolverInstance (Resolver $resolverInstance) {
744 $this->resolverInstance = $resolverInstance;
748 * Getter for resolver instance
750 * @return $resolverInstance Instance of a command resolver class
752 public final function getResolverInstance () {
753 return $this->resolverInstance;
757 * Setter for language instance
759 * @param $configInstance The configuration instance which shall
760 * be FrameworkConfiguration
763 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
764 Registry::getRegistry()->addInstance('config', $configInstance);
768 * Getter for configuration instance
770 * @return $configInstance Configuration instance
772 public final function getConfigInstance () {
773 $configInstance = Registry::getRegistry()->getInstance('config');
774 return $configInstance;
778 * Setter for debug instance
780 * @param $debugInstance The instance for debug output class
783 public final function setDebugInstance (DebugMiddleware $debugInstance) {
784 Registry::getRegistry()->addInstance('debug', $debugInstance);
788 * Getter for debug instance
790 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
792 public final function getDebugInstance () {
793 // Get debug instance
794 $debugInstance = Registry::getRegistry()->getInstance('debug');
797 return $debugInstance;
801 * Setter for web output instance
803 * @param $webInstance The instance for web output class
806 public final function setWebOutputInstance (OutputStreamer $webInstance) {
807 Registry::getRegistry()->addInstance('web_output', $webInstance);
811 * Getter for web output instance
813 * @return $webOutputInstance - Instance to class WebOutput
815 public final function getWebOutputInstance () {
816 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
817 return $webOutputInstance;
821 * Setter for database instance
823 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
826 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
827 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
831 * Getter for database layer
833 * @return $databaseInstance The database layer instance
835 public final function getDatabaseInstance () {
837 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
840 return $databaseInstance;
844 * Setter for compressor channel
846 * @param $compressorInstance An instance of CompressorChannel
849 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
850 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
854 * Getter for compressor channel
856 * @return $compressorInstance The compressor channel
858 public final function getCompressorChannel () {
859 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
860 return $compressorInstance;
864 * Protected getter for a manageable application helper class
866 * @return $applicationInstance An instance of a manageable application helper class
868 protected final function getApplicationInstance () {
869 $applicationInstance = Registry::getRegistry()->getInstance('application');
870 return $applicationInstance;
874 * Setter for a manageable application helper class
876 * @param $applicationInstance An instance of a manageable application helper class
879 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
880 Registry::getRegistry()->addInstance('application', $applicationInstance);
884 * Setter for request instance
886 * @param $requestInstance An instance of a Requestable class
889 public final function setRequestInstance (Requestable $requestInstance) {
890 $this->requestInstance = $requestInstance;
894 * Getter for request instance
896 * @return $requestInstance An instance of a Requestable class
898 public final function getRequestInstance () {
899 return $this->requestInstance;
903 * Setter for response instance
905 * @param $responseInstance An instance of a Responseable class
908 public final function setResponseInstance (Responseable $responseInstance) {
909 $this->responseInstance = $responseInstance;
913 * Getter for response instance
915 * @return $responseInstance An instance of a Responseable class
917 public final function getResponseInstance () {
918 return $this->responseInstance;
922 * Private getter for language instance
924 * @return $langInstance An instance to the language sub-system
926 protected final function getLanguageInstance () {
927 $langInstance = Registry::getRegistry()->getInstance('language');
928 return $langInstance;
932 * Setter for language instance
934 * @param $langInstance An instance to the language sub-system
936 * @see LanguageSystem
938 public final function setLanguageInstance (ManageableLanguage $langInstance) {
939 Registry::getRegistry()->addInstance('language', $langInstance);
943 * Private getter for file IO instance
945 * @return $fileIoInstance An instance to the file I/O sub-system
947 protected final function getFileIoInstance () {
948 return $this->fileIoInstance;
952 * Setter for file I/O instance
954 * @param $fileIoInstance An instance to the file I/O sub-system
957 public final function setFileIoInstance (IoHandler $fileIoInstance) {
958 $this->fileIoInstance = $fileIoInstance;
962 * Protected setter for user instance
964 * @param $userInstance An instance of a user class
967 protected final function setUserInstance (ManageableAccount $userInstance) {
968 $this->userInstance = $userInstance;
972 * Getter for user instance
974 * @return $userInstance An instance of a user class
976 public final function getUserInstance () {
977 return $this->userInstance;
981 * Setter for controller instance (this surely breaks a bit the MVC patterm)
983 * @param $controllerInstance An instance of the controller
986 public final function setControllerInstance (Controller $controllerInstance) {
987 $this->controllerInstance = $controllerInstance;
991 * Getter for controller instance (this surely breaks a bit the MVC patterm)
993 * @return $controllerInstance An instance of the controller
995 public final function getControllerInstance () {
996 return $this->controllerInstance;
1000 * Setter for RNG instance
1002 * @param $rngInstance An instance of a random number generator (RNG)
1005 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1006 $this->rngInstance = $rngInstance;
1010 * Getter for RNG instance
1012 * @return $rngInstance An instance of a random number generator (RNG)
1014 public final function getRngInstance () {
1015 return $this->rngInstance;
1019 * Setter for Cryptable instance
1021 * @param $cryptoInstance An instance of a Cryptable class
1024 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1025 $this->cryptoInstance = $cryptoInstance;
1029 * Getter for Cryptable instance
1031 * @return $cryptoInstance An instance of a Cryptable class
1033 public final function getCryptoInstance () {
1034 return $this->cryptoInstance;
1038 * Setter for the list instance
1040 * @param $listInstance A list of Listable
1043 protected final function setListInstance (Listable $listInstance) {
1044 $this->listInstance = $listInstance;
1048 * Getter for the list instance
1050 * @return $listInstance A list of Listable
1052 protected final function getListInstance () {
1053 return $this->listInstance;
1057 * Setter for the menu instance
1059 * @param $menuInstance A RenderableMenu instance
1062 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1063 $this->menuInstance = $menuInstance;
1067 * Getter for the menu instance
1069 * @return $menuInstance A RenderableMenu instance
1071 protected final function getMenuInstance () {
1072 return $this->menuInstance;
1076 * Setter for image instance
1078 * @param $imageInstance An instance of an image
1081 public final function setImageInstance (BaseImage $imageInstance) {
1082 $this->imageInstance = $imageInstance;
1086 * Getter for image instance
1088 * @return $imageInstance An instance of an image
1090 public final function getImageInstance () {
1091 return $this->imageInstance;
1095 * Setter for stacker instance
1097 * @param $stackInstance An instance of an stacker
1100 public final function setStackInstance (Stackable $stackInstance) {
1101 $this->stackInstance = $stackInstance;
1105 * Getter for stacker instance
1107 * @return $stackInstance An instance of an stacker
1109 public final function getStackInstance () {
1110 return $this->stackInstance;
1114 * Setter for compressor instance
1116 * @param $compressorInstance An instance of an compressor
1119 public final function setCompressorInstance (Compressor $compressorInstance) {
1120 $this->compressorInstance = $compressorInstance;
1124 * Getter for compressor instance
1126 * @return $compressorInstance An instance of an compressor
1128 public final function getCompressorInstance () {
1129 return $this->compressorInstance;
1133 * Setter for Parseable instance
1135 * @param $parserInstance An instance of an Parseable
1138 public final function setParserInstance (Parseable $parserInstance) {
1139 $this->parserInstance = $parserInstance;
1143 * Getter for Parseable instance
1145 * @return $parserInstance An instance of an Parseable
1147 public final function getParserInstance () {
1148 return $this->parserInstance;
1152 * Setter for HandleableProtocol instance
1154 * @param $protocolInstance An instance of an HandleableProtocol
1157 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1158 $this->protocolInstance = $protocolInstance;
1162 * Getter for HandleableProtocol instance
1164 * @return $protocolInstance An instance of an HandleableProtocol
1166 public final function getProtocolInstance () {
1167 return $this->protocolInstance;
1171 * Setter for DatabaseWrapper instance
1173 * @param $wrapperInstance An instance of an DatabaseWrapper
1176 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1177 $this->wrapperInstance = $wrapperInstance;
1181 * Getter for DatabaseWrapper instance
1183 * @return $wrapperInstance An instance of an DatabaseWrapper
1185 public final function getWrapperInstance () {
1186 return $this->wrapperInstance;
1190 * Setter for socket resource
1192 * @param $socketResource A valid socket resource
1195 public final function setSocketResource ($socketResource) {
1196 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1197 $this->socketResource = $socketResource;
1201 * Getter for socket resource
1203 * @return $socketResource A valid socket resource
1205 public final function getSocketResource () {
1206 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1207 return $this->socketResource;
1211 * Setter for regular expression
1213 * @param $regularExpression A valid regular expression
1216 public final function setRegularExpression ($regularExpression) {
1217 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1218 $this->regularExpression = $regularExpression;
1222 * Getter for regular expression
1224 * @return $regularExpression A valid regular expression
1226 public final function getRegularExpression () {
1227 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1228 return $this->regularExpression;
1232 * Setter for helper instance
1234 * @param $helperInstance An instance of a helper class
1237 protected final function setHelperInstance (Helper $helperInstance) {
1238 $this->helperInstance = $helperInstance;
1242 * Getter for helper instance
1244 * @return $helperInstance An instance of a helper class
1246 public final function getHelperInstance () {
1247 return $this->helperInstance;
1251 * Setter for a Source instance
1253 * @param $sourceInstance An instance of a Source class
1256 protected final function setSourceInstance (Source $sourceInstance) {
1257 $this->sourceInstance = $sourceInstance;
1261 * Getter for a Source instance
1263 * @return $sourceInstance An instance of a Source class
1265 protected final function getSourceInstance () {
1266 return $this->sourceInstance;
1270 * Setter for a UrlSource instance
1272 * @param $sourceInstance An instance of a UrlSource class
1275 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1276 $this->urlSourceInstance = $urlSourceInstance;
1280 * Getter for a UrlSource instance
1282 * @return $urlSourceInstance An instance of a UrlSource class
1284 protected final function getUrlSourceInstance () {
1285 return $this->urlSourceInstance;
1289 * Getter for a InputStream instance
1291 * @param $inputStreamInstance The InputStream instance
1293 protected final function getInputStreamInstance () {
1294 return $this->inputStreamInstance;
1298 * Setter for a InputStream instance
1300 * @param $inputStreamInstance The InputStream instance
1303 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1304 $this->inputStreamInstance = $inputStreamInstance;
1308 * Getter for a OutputStream instance
1310 * @param $outputStreamInstance The OutputStream instance
1312 protected final function getOutputStreamInstance () {
1313 return $this->outputStreamInstance;
1317 * Setter for a OutputStream instance
1319 * @param $outputStreamInstance The OutputStream instance
1322 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1323 $this->outputStreamInstance = $outputStreamInstance;
1327 * Setter for handler instance
1329 * @param $handlerInstance An instance of a Handleable class
1332 protected final function setHandlerInstance (Handleable $handlerInstance) {
1333 $this->handlerInstance = $handlerInstance;
1337 * Getter for handler instance
1339 * @return $handlerInstance A Networkable instance
1341 protected final function getHandlerInstance () {
1342 return $this->handlerInstance;
1346 * Setter for visitor instance
1348 * @param $visitorInstance A Visitor instance
1351 protected final function setVisitorInstance (Visitor $visitorInstance) {
1352 $this->visitorInstance = $visitorInstance;
1356 * Getter for visitor instance
1358 * @return $visitorInstance A Visitor instance
1360 protected final function getVisitorInstance () {
1361 return $this->visitorInstance;
1365 * Setter for DHT instance
1367 * @param $dhtInstance A Distributable instance
1370 protected final function setDhtInstance (Distributable $dhtInstance) {
1371 $this->dhtInstance = $dhtInstance;
1375 * Getter for DHT instance
1377 * @return $dhtInstance A Distributable instance
1379 protected final function getDhtInstance () {
1380 return $this->dhtInstance;
1384 * Setter for raw package Data
1386 * @param $packageData Raw package Data
1389 public final function setPackageData (array $packageData) {
1390 $this->packageData = $packageData;
1394 * Getter for raw package Data
1396 * @return $packageData Raw package Data
1398 public function getPackageData () {
1399 return $this->packageData;
1404 * Setter for Iterator instance
1406 * @param $iteratorInstance An instance of an Iterator
1409 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1410 $this->iteratorInstance = $iteratorInstance;
1414 * Getter for Iterator instance
1416 * @return $iteratorInstance An instance of an Iterator
1418 public final function getIteratorInstance () {
1419 return $this->iteratorInstance;
1423 * Setter for FilePointer instance
1425 * @param $pointerInstance An instance of an FilePointer class
1428 protected final function setPointerInstance (FilePointer $pointerInstance) {
1429 $this->pointerInstance = $pointerInstance;
1433 * Getter for FilePointer instance
1435 * @return $pointerInstance An instance of an FilePointer class
1437 public final function getPointerInstance () {
1438 return $this->pointerInstance;
1442 * Unsets pointer instance which triggers a call of __destruct() if the
1443 * instance is still there. This is surely not fatal on already "closed"
1444 * file pointer instances.
1446 * I don't want to mess around with above setter by giving it a default
1447 * value NULL as setter should always explicitly only set (existing) object
1448 * instances and NULL is NULL.
1452 protected final function unsetPointerInstance () {
1453 // Simply it to NULL
1454 $this->pointerInstance = NULL;
1458 * Setter for Indexable instance
1460 * @param $indexInstance An instance of an Indexable class
1463 protected final function setIndexInstance (Indexable $indexInstance) {
1464 $this->indexInstance = $indexInstance;
1468 * Getter for Indexable instance
1470 * @return $indexInstance An instance of an Indexable class
1472 public final function getIndexInstance () {
1473 return $this->indexInstance;
1477 * Setter for Block instance
1479 * @param $blockInstance An instance of an Block class
1482 protected final function setBlockInstance (Block $blockInstance) {
1483 $this->blockInstance = $blockInstance;
1487 * Getter for Block instance
1489 * @return $blockInstance An instance of an Block class
1491 public final function getBlockInstance () {
1492 return $this->blockInstance;
1496 * Setter for Minable instance
1498 * @param $minableInstance A Minable instance
1501 protected final function setMinableInstance (Minable $minableInstance) {
1502 $this->minableInstance = $minableInstance;
1506 * Getter for minable instance
1508 * @return $minableInstance A Minable instance
1510 protected final function getMinableInstance () {
1511 return $this->minableInstance;
1515 * Setter for FrameworkDirectory instance
1517 * @param $directoryInstance A FrameworkDirectoryPointer instance
1520 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1521 $this->directoryInstance = $directoryInstance;
1525 * Getter for FrameworkDirectory instance
1527 * @return $directoryInstance A FrameworkDirectory instance
1529 protected final function getDirectoryInstance () {
1530 return $this->directoryInstance;
1534 * Setter for listener instance
1536 * @param $listenerInstance A Listenable instance
1539 protected final function setListenerInstance (Listenable $listenerInstance) {
1540 $this->listenerInstance = $listenerInstance;
1544 * Getter for listener instance
1546 * @return $listenerInstance A Listenable instance
1548 protected final function getListenerInstance () {
1549 return $this->listenerInstance;
1553 * Getter for communicator instance
1555 * @return $communicatorInstance An instance of a Communicator class
1557 public final function getCommunicatorInstance () {
1558 return $this->communicatorInstance;
1562 * Setter for communicator instance
1564 * @param $communicatorInstance An instance of a Communicator class
1567 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1568 $this->communicatorInstance = $communicatorInstance;
1572 * Setter for state instance
1574 * @param $stateInstance A Stateable instance
1577 public final function setStateInstance (Stateable $stateInstance) {
1578 $this->stateInstance = $stateInstance;
1582 * Getter for state instance
1584 * @return $stateInstance A Stateable instance
1586 public final function getStateInstance () {
1587 return $this->stateInstance;
1591 * Setter for output instance
1593 * @param $outputInstance The debug output instance
1596 public final function setOutputInstance (OutputStreamer $outputInstance) {
1597 $this->outputInstance = $outputInstance;
1601 * Getter for output instance
1603 * @return $outputInstance The debug output instance
1605 public final function getOutputInstance () {
1606 return $this->outputInstance;
1610 * Setter for command name
1612 * @param $commandName Last validated command name
1615 protected final function setCommandName ($commandName) {
1616 $this->commandName = $commandName;
1620 * Getter for command name
1622 * @return $commandName Last validated command name
1624 protected final function getCommandName () {
1625 return $this->commandName;
1629 * Setter for controller name
1631 * @param $controllerName Last validated controller name
1634 protected final function setControllerName ($controllerName) {
1635 $this->controllerName = $controllerName;
1639 * Getter for controller name
1641 * @return $controllerName Last validated controller name
1643 protected final function getControllerName () {
1644 return $this->controllerName;
1648 * Getter for protocol name
1650 * @return $protocolName Name of used protocol
1652 public final function getProtocolName () {
1653 return $this->protocolName;
1657 * Setter for protocol name
1659 * @param $protocolName Name of used protocol
1662 protected final function setProtocolName ($protocolName) {
1663 $this->protocolName = $protocolName;
1667 * Checks whether an object equals this object. You should overwrite this
1668 * method to implement own equality checks
1670 * @param $objectInstance An instance of a FrameworkInterface object
1671 * @return $equals Whether both objects equals
1673 public function equals (FrameworkInterface $objectInstance) {
1676 $this->__toString() == $objectInstance->__toString()
1678 $this->hashCode() == $objectInstance->hashCode()
1681 // Return the result
1686 * Generates a generic hash code of this class. You should really overwrite
1687 * this method with your own hash code generator code. But keep KISS in mind.
1689 * @return $hashCode A generic hash code respresenting this whole class
1691 public function hashCode () {
1693 return crc32($this->__toString());
1697 * Formats computer generated price values into human-understandable formats
1698 * with thousand and decimal separators.
1700 * @param $value The in computer format value for a price
1701 * @param $currency The currency symbol (use HTML-valid characters!)
1702 * @param $decNum Number of decimals after commata
1703 * @return $price The for the current language formated price string
1704 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1705 * thousands separator
1708 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1709 // Are all required attriutes set?
1710 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1711 // Throw an exception
1712 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1716 $value = (float) $value;
1718 // Reformat the US number
1719 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1721 // Return as string...
1726 * Appends a trailing slash to a string
1728 * @param $str A string (maybe) without trailing slash
1729 * @return $str A string with an auto-appended trailing slash
1731 public final function addMissingTrailingSlash ($str) {
1732 // Is there a trailing slash?
1733 if (substr($str, -1, 1) != '/') {
1737 // Return string with trailing slash
1742 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1743 * application helper instance (ApplicationHelper by default).
1745 * @param $applicationInstance An application helper instance or
1746 * null if we shall use the default
1747 * @return $templateInstance The template engine instance
1748 * @throws NullPointerException If the discovered application
1749 * instance is still null
1751 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1752 // Is the application instance set?
1753 if (is_null($applicationInstance)) {
1754 // Get the current instance
1755 $applicationInstance = $this->getApplicationInstance();
1758 if (is_null($applicationInstance)) {
1759 // Thrown an exception
1760 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1764 // Initialize the template engine
1765 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1767 // Return the prepared instance
1768 return $templateInstance;
1772 * Debugs this instance by putting out it's full content
1774 * @param $message Optional message to show in debug output
1777 public final function debugInstance ($message = '') {
1778 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1779 restore_error_handler();
1784 // Is a message set?
1785 if (!empty($message)) {
1786 // Construct message
1787 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1790 // Generate the output
1791 $content .= sprintf('<pre>%s</pre>',
1794 print_r($this, TRUE)
1800 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>',
1801 $this->__toString(),
1803 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1808 * Replaces control characters with printable output
1810 * @param $str String with control characters
1811 * @return $str Replaced string
1813 protected function replaceControlCharacters ($str) {
1816 chr(13), '[r]', str_replace(
1817 chr(10), '[n]', str_replace(
1827 * Output a partial stub message for the caller method
1829 * @param $message An optional message to display
1832 protected function partialStub ($message = '') {
1833 // Get the backtrace
1834 $backtrace = debug_backtrace();
1836 // Generate the class::method string
1837 $methodName = 'UnknownClass->unknownMethod';
1838 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1839 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1842 // Construct the full message
1843 $stubMessage = sprintf('[%s:] Partial stub!',
1847 // Is the extra message given?
1848 if (!empty($message)) {
1849 // Then add it as well
1850 $stubMessage .= ' Message: ' . $message;
1853 // Debug instance is there?
1854 if (!is_null($this->getDebugInstance())) {
1855 // Output stub message
1856 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1859 trigger_error($stubMessage);
1865 * Outputs a debug backtrace and stops further script execution
1867 * @param $message An optional message to output
1868 * @param $doExit Whether exit the program (TRUE is default)
1871 public function debugBackTrace ($message = '', $doExit = TRUE) {
1872 // Sorry, there is no other way getting this nice backtrace
1873 if (!empty($message)) {
1875 printf('Message: %s<br />' . PHP_EOL, $message);
1879 debug_print_backtrace();
1883 if ($doExit === TRUE) {
1889 * Creates an instance of a debugger instance
1891 * @param $className Name of the class (currently unsupported)
1892 * @return $debugInstance An instance of a debugger class
1893 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1895 public final static function createDebugInstance ($className) {
1896 // Is the instance set?
1897 if (!Registry::getRegistry()->instanceExists('debug')) {
1898 // Init debug instance
1899 $debugInstance = NULL;
1903 // Get a debugger instance
1904 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1905 } catch (NullPointerException $e) {
1906 // Didn't work, no instance there
1907 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1910 // Empty string should be ignored and used for testing the middleware
1911 DebugMiddleware::getSelfInstance()->output('');
1913 // Set it in its own class. This will set it in the registry
1914 $debugInstance->setDebugInstance($debugInstance);
1916 // Get instance from registry
1917 $debugInstance = Registry::getRegistry()->getDebugInstance();
1921 return $debugInstance;
1925 * Simple output of a message with line-break
1927 * @param $message Message to output
1930 public function outputLine ($message) {
1932 print($message . PHP_EOL);
1936 * Outputs a debug message whether to debug instance (should be set!) or
1937 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1938 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1940 * @param $message Message we shall send out...
1941 * @param $doPrint Whether print or die here (default: print)
1942 * @paran $stripTags Whether to strip tags (default: FALSE)
1945 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1946 // Set debug instance to NULL
1947 $debugInstance = NULL;
1951 // Get debug instance
1952 $debugInstance = $this->getDebugInstance();
1953 } catch (NullPointerException $e) {
1954 // The debug instance is not set (yet)
1957 // Is the debug instance there?
1958 if (is_object($debugInstance)) {
1959 // Use debug output handler
1960 $debugInstance->output($message, $stripTags);
1962 if ($doPrint === FALSE) {
1963 // Die here if not printed
1967 // Are debug times enabled?
1968 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1970 $message = $this->getPrintableExecutionTime() . $message;
1974 if ($doPrint === TRUE) {
1976 $this->outputLine($message);
1985 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1987 * @param $str The string, what ever it is needs to be converted
1988 * @return $className Generated class name
1990 public static final function convertToClassName ($str) {
1994 // Convert all dashes in underscores
1995 $str = self::convertDashesToUnderscores($str);
1997 // Now use that underscores to get classname parts for hungarian style
1998 foreach (explode('_', $str) as $strPart) {
1999 // Make the class name part lower case and first upper case
2000 $className .= ucfirst(strtolower($strPart));
2003 // Return class name
2008 * Converts dashes to underscores, e.g. useable for configuration entries
2010 * @param $str The string with maybe dashes inside
2011 * @return $str The converted string with no dashed, but underscores
2013 public static final function convertDashesToUnderscores ($str) {
2015 $str = str_replace('-', '_', $str);
2017 // Return converted string
2022 * Marks up the code by adding e.g. line numbers
2024 * @param $phpCode Unmarked PHP code
2025 * @return $markedCode Marked PHP code
2027 public function markupCode ($phpCode) {
2032 $errorArray = error_get_last();
2034 // Init the code with error message
2035 if (is_array($errorArray)) {
2037 $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>',
2038 basename($errorArray['file']),
2039 $errorArray['line'],
2040 $errorArray['message'],
2045 // Add line number to the code
2046 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2048 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2050 htmlentities($code, ENT_QUOTES)
2059 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2060 * beatiful for web-based front-ends. If null is given a message id
2061 * null_timestamp will be resolved and returned.
2063 * @param $timestamp Timestamp to prepare (filter) for display
2064 * @return $readable A readable timestamp
2066 public function doFilterFormatTimestamp ($timestamp) {
2067 // Default value to return
2070 // Is the timestamp null?
2071 if (is_null($timestamp)) {
2072 // Get a message string
2073 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2075 switch ($this->getLanguageInstance()->getLanguageCode()) {
2076 case 'de': // German format is a bit different to default
2077 // Split the GMT stamp up
2078 $dateTime = explode(' ', $timestamp );
2079 $dateArray = explode('-', $dateTime[0]);
2080 $timeArray = explode(':', $dateTime[1]);
2082 // Construct the timestamp
2083 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2093 default: // Default is pass-through
2094 $readable = $timestamp;
2104 * Filter a given number into a localized number
2106 * @param $value The raw value from e.g. database
2107 * @return $localized Localized value
2109 public function doFilterFormatNumber ($value) {
2110 // Generate it from config and localize dependencies
2111 switch ($this->getLanguageInstance()->getLanguageCode()) {
2112 case 'de': // German format is a bit different to default
2113 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2116 default: // US, etc.
2117 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2126 * "Getter" for databse entry
2128 * @return $entry An array with database entries
2129 * @throws NullPointerException If the database result is not found
2130 * @throws InvalidDatabaseResultException If the database result is invalid
2132 protected final function getDatabaseEntry () {
2133 // Is there an instance?
2134 if (!$this->getResultInstance() instanceof SearchableResult) {
2135 // Throw an exception here
2136 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2140 $this->getResultInstance()->rewind();
2142 // Do we have an entry?
2143 if ($this->getResultInstance()->valid() === FALSE) {
2144 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2145 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2149 $this->getResultInstance()->next();
2152 $entry = $this->getResultInstance()->current();
2159 * Getter for field name
2161 * @param $fieldName Field name which we shall get
2162 * @return $fieldValue Field value from the user
2163 * @throws NullPointerException If the result instance is null
2165 public final function getField ($fieldName) {
2166 // Default field value
2169 // Get result instance
2170 $resultInstance = $this->getResultInstance();
2172 // Is this instance null?
2173 if (is_null($resultInstance)) {
2174 // Then the user instance is no longer valid (expired cookies?)
2175 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2178 // Get current array
2179 $fieldArray = $resultInstance->current();
2180 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2182 // Convert dashes to underscore
2183 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2185 // Does the field exist?
2186 if ($this->isFieldSet($fieldName)) {
2188 $fieldValue = $fieldArray[$fieldName2];
2189 } elseif (defined('DEVELOPER')) {
2190 // Missing field entry, may require debugging
2191 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2193 // Missing field entry, may require debugging
2194 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2202 * Checks if given field is set
2204 * @param $fieldName Field name to check
2205 * @return $isSet Whether the given field name is set
2206 * @throws NullPointerException If the result instance is null
2208 public function isFieldSet ($fieldName) {
2209 // Get result instance
2210 $resultInstance = $this->getResultInstance();
2212 // Is this instance null?
2213 if (is_null($resultInstance)) {
2214 // Then the user instance is no longer valid (expired cookies?)
2215 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2218 // Get current array
2219 $fieldArray = $resultInstance->current();
2220 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2222 // Convert dashes to underscore
2223 $fieldName = self::convertDashesToUnderscores($fieldName);
2226 $isSet = isset($fieldArray[$fieldName]);
2233 * Flushs all pending updates to the database layer
2237 public function flushPendingUpdates () {
2238 // Get result instance
2239 $resultInstance = $this->getResultInstance();
2241 // Do we have data to update?
2242 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2243 // Get wrapper class name config entry
2244 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2246 // Create object instance
2247 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2249 // Yes, then send the whole result to the database layer
2250 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2255 * Outputs a deprecation warning to the developer.
2257 * @param $message The message we shall output to the developer
2259 * @todo Write a logging mechanism for productive mode
2261 public function deprecationWarning ($message) {
2262 // Is developer mode active?
2263 if (defined('DEVELOPER')) {
2264 // Debug instance is there?
2265 if (!is_null($this->getDebugInstance())) {
2266 // Output stub message
2267 self::createDebugInstance(__CLASS__)->debugOutput($message);
2270 trigger_error($message . "<br />\n");
2274 // @TODO Finish this part!
2275 $this->partialStub('Developer mode inactive. Message:' . $message);
2280 * Checks whether the given PHP extension is loaded
2282 * @param $phpExtension The PHP extension we shall check
2283 * @return $isLoaded Whether the PHP extension is loaded
2285 public final function isPhpExtensionLoaded ($phpExtension) {
2287 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2294 * "Getter" as a time() replacement but with milliseconds. You should use this
2295 * method instead of the encapsulated getimeofday() function.
2297 * @return $milliTime Timestamp with milliseconds
2299 public function getMilliTime () {
2300 // Get the time of day as float
2301 $milliTime = gettimeofday(TRUE);
2308 * Idles (sleeps) for given milliseconds
2310 * @return $hasSlept Whether it goes fine
2312 public function idle ($milliSeconds) {
2313 // Sleep is fine by default
2316 // Idle so long with found function
2317 if (function_exists('time_sleep_until')) {
2318 // Get current time and add idle time
2319 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2321 // New PHP 5.1.0 function found, ignore errors
2322 $hasSlept = @time_sleep_until($sleepUntil);
2325 * My Sun station doesn't have that function even with latest PHP
2328 usleep($milliSeconds * 1000);
2335 * Converts a hexadecimal string, even with negative sign as first string to
2336 * a decimal number using BC functions.
2338 * This work is based on comment #86673 on php.net documentation page at:
2339 * <http://de.php.net/manual/en/function.dechex.php#86673>
2341 * @param $hex Hexadecimal string
2342 * @return $dec Decimal number
2344 protected function hex2dec ($hex) {
2345 // Convert to all lower-case
2346 $hex = strtolower($hex);
2348 // Detect sign (negative/positive numbers)
2350 if (substr($hex, 0, 1) == '-') {
2352 $hex = substr($hex, 1);
2355 // Decode the hexadecimal string into a decimal number
2357 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2358 $factor = self::$hexdec[substr($hex, $i, 1)];
2359 $dec = bcadd($dec, bcmul($factor, $e));
2362 // Return the decimal number
2363 return $sign . $dec;
2367 * Converts even very large decimal numbers, also signed, to a hexadecimal
2370 * This work is based on comment #97756 on php.net documentation page at:
2371 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2373 * @param $dec Decimal number, even with negative sign
2374 * @param $maxLength Optional maximum length of the string
2375 * @return $hex Hexadecimal string
2377 protected function dec2hex ($dec, $maxLength = 0) {
2378 // maxLength can be zero or devideable by 2
2379 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2381 // Detect sign (negative/positive numbers)
2388 // Encode the decimal number into a hexadecimal string
2391 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2393 } while ($dec >= 1);
2396 * Leading zeros are required for hex-decimal "numbers". In some
2397 * situations more leading zeros are wanted, so check for both
2400 if ($maxLength > 0) {
2401 // Prepend more zeros
2402 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2403 } elseif ((strlen($hex) % 2) != 0) {
2404 // Only make string's length dividable by 2
2408 // Return the hexadecimal string
2409 return $sign . $hex;
2413 * Converts a ASCII string (0 to 255) into a decimal number.
2415 * @param $asc The ASCII string to be converted
2416 * @return $dec Decimal number
2418 protected function asc2dec ($asc) {
2419 // Convert it into a hexadecimal number
2420 $hex = bin2hex($asc);
2422 // And back into a decimal number
2423 $dec = $this->hex2dec($hex);
2430 * Converts a decimal number into an ASCII string.
2432 * @param $dec Decimal number
2433 * @return $asc An ASCII string
2435 protected function dec2asc ($dec) {
2436 // First convert the number into a hexadecimal string
2437 $hex = $this->dec2hex($dec);
2439 // Then convert it into the ASCII string
2440 $asc = $this->hex2asc($hex);
2447 * Converts a hexadecimal number into an ASCII string. Negative numbers
2450 * @param $hex Hexadecimal string
2451 * @return $asc An ASCII string
2453 protected function hex2asc ($hex) {
2454 // Check for length, it must be devideable by 2
2455 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2456 assert((strlen($hex) % 2) == 0);
2460 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2461 // Get the decimal number of the chunk
2462 $part = hexdec(substr($hex, $idx, 2));
2464 // Add it to the final string
2468 // Return the final string
2473 * Checks whether the given encoded data was encoded with Base64
2475 * @param $encodedData Encoded data we shall check
2476 * @return $isBase64 Whether the encoded data is Base64
2478 protected function isBase64Encoded ($encodedData) {
2480 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2487 * "Getter" to get response/request type from analysis of the system.
2489 * @return $responseType Analyzed response type
2491 protected static function getResponseTypeFromSystem () {
2492 // Default is console
2493 $responseType = 'console';
2495 // Is 'HTTP_HOST' set?
2496 if (isset($_SERVER['HTTP_HOST'])) {
2498 * Then it is a HTML response/request as RSS and so on may be
2499 * transfered over HTTP as well.
2501 $responseType = 'html';
2505 return $responseType;
2509 * Gets a cache key from Criteria instance
2511 * @param $criteriaInstance An instance of a Criteria class
2512 * @param $onlyKeys Only use these keys for a cache key
2513 * @return $cacheKey A cache key suitable for lookup/storage purposes
2515 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2517 $cacheKey = sprintf('%s@%s',
2518 $this->__toString(),
2519 $criteriaInstance->getCacheKey($onlyKeys)
2523 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2528 * Getter for startup time in miliseconds
2530 * @return $startupTime Startup time in miliseconds
2532 protected function getStartupTime () {
2533 return self::$startupTime;
2537 * "Getter" for a printable currently execution time in nice braces
2539 * @return $executionTime Current execution time in nice braces
2541 protected function getPrintableExecutionTime () {
2542 // Caculate the execution time
2543 $executionTime = microtime(TRUE) - $this->getStartupTime();
2545 // Pack it in nice braces
2546 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2549 return $executionTime;
2553 * Hashes a given string with a simple but stronger hash function (no salt)
2554 * and hex-encode it.
2556 * @param $str The string to be hashed
2557 * @return $hash The hash from string $str
2559 public static final function hash ($str) {
2560 // Hash given string with (better secure) hasher
2561 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2568 * "Getter" for length of hash() output. This will be "cached" to speed up
2571 * @return $length Length of hash() output
2573 public static final function getHashLength () {
2575 if (is_null(self::$hashLength)) {
2576 // No, then hash a string and save its length.
2577 self::$hashLength = strlen(self::hash('abc123'));
2581 return self::$hashLength;
2585 * Checks whether the given number is really a number (only chars 0-9).
2587 * @param $num A string consisting only chars between 0 and 9
2588 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2589 * @param $assertMismatch Whether to assert mismatches
2590 * @return $ret The (hopefully) secured numbered value
2592 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2593 // Filter all numbers out
2594 $ret = preg_replace('/[^0123456789]/', '', $num);
2597 if ($castValue === TRUE) {
2598 // Cast to biggest numeric type
2599 $ret = (double) $ret;
2602 // Assert only if requested
2603 if ($assertMismatch === TRUE) {
2604 // Has the whole value changed?
2605 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2613 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2615 * @param $num A string consisting only chars between 0 and 9
2616 * @param $assertMismatch Whether to assert mismatches
2617 * @return $ret The (hopefully) secured hext-numbered value
2619 public function hexval ($num, $assertMismatch = FALSE) {
2620 // Filter all numbers out
2621 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2623 // Assert only if requested
2624 if ($assertMismatch === TRUE) {
2625 // Has the whole value changed?
2626 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2634 * Checks whether start/end marker are set
2636 * @param $data Data to be checked
2637 * @return $isset Whether start/end marker are set
2639 public final function ifStartEndMarkersSet ($data) {
2641 $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));
2643 // ... and return it
2648 * Determines if an element is set in the generic array
2650 * @param $keyGroup Main group for the key
2651 * @param $subGroup Sub group for the key
2652 * @param $key Key to check
2653 * @param $element Element to check
2654 * @return $isset Whether the given key is set
2656 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2658 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2661 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2667 * Determines if a key is set in the generic array
2669 * @param $keyGroup Main group for the key
2670 * @param $subGroup Sub group for the key
2671 * @param $key Key to check
2672 * @return $isset Whether the given key is set
2674 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2676 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2679 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2687 * Determines if a group is set in the generic array
2689 * @param $keyGroup Main group
2690 * @param $subGroup Sub group
2691 * @return $isset Whether the given group is set
2693 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2695 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2698 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2705 * Getter for sub key group
2707 * @param $keyGroup Main key group
2708 * @param $subGroup Sub key group
2709 * @return $array An array with all array elements
2711 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2713 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2714 // No, then abort here
2715 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2720 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2723 return $this->genericArray[$keyGroup][$subGroup];
2727 * Unsets a given key in generic array
2729 * @param $keyGroup Main group for the key
2730 * @param $subGroup Sub group for the key
2731 * @param $key Key to unset
2734 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2736 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2739 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2743 * Unsets a given element in generic array
2745 * @param $keyGroup Main group for the key
2746 * @param $subGroup Sub group for the key
2747 * @param $key Key to unset
2748 * @param $element Element to unset
2751 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2753 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2756 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2760 * Append a string to a given generic array key
2762 * @param $keyGroup Main group for the key
2763 * @param $subGroup Sub group for the key
2764 * @param $key Key to unset
2765 * @param $value Value to add/append
2768 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2770 //* 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);
2772 // Is it already there?
2773 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2775 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2778 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2783 * Append a string to a given generic array element
2785 * @param $keyGroup Main group for the key
2786 * @param $subGroup Sub group for the key
2787 * @param $key Key to unset
2788 * @param $element Element to check
2789 * @param $value Value to add/append
2792 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2794 //* 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);
2796 // Is it already there?
2797 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2799 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2802 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2807 * Sets a string in a given generic array element
2809 * @param $keyGroup Main group for the key
2810 * @param $subGroup Sub group for the key
2811 * @param $key Key to unset
2812 * @param $element Element to check
2813 * @param $value Value to add/append
2816 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2818 //* 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);
2821 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2825 * Initializes given generic array group
2827 * @param $keyGroup Main group for the key
2828 * @param $subGroup Sub group for the key
2829 * @param $key Key to use
2830 * @param $forceInit Optionally force initialization
2833 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2835 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2837 // Is it already set?
2838 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2839 // Already initialized
2840 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2845 $this->genericArray[$keyGroup][$subGroup] = array();
2849 * Initializes given generic array key
2851 * @param $keyGroup Main group for the key
2852 * @param $subGroup Sub group for the key
2853 * @param $key Key to use
2854 * @param $forceInit Optionally force initialization
2857 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2859 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2861 // Is it already set?
2862 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2863 // Already initialized
2864 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2869 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2873 * Initializes given generic array element
2875 * @param $keyGroup Main group for the key
2876 * @param $subGroup Sub group for the key
2877 * @param $key Key to use
2878 * @param $element Element to use
2879 * @param $forceInit Optionally force initialization
2882 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2884 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2886 // Is it already set?
2887 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2888 // Already initialized
2889 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2894 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2898 * Pushes an element to a generic key
2900 * @param $keyGroup Main group for the key
2901 * @param $subGroup Sub group for the key
2902 * @param $key Key to use
2903 * @param $value Value to add/append
2904 * @return $count Number of array elements
2906 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2908 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2911 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2913 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2917 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2920 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2921 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2926 * Pushes an element to a generic array element
2928 * @param $keyGroup Main group for the key
2929 * @param $subGroup Sub group for the key
2930 * @param $key Key to use
2931 * @param $element Element to check
2932 * @param $value Value to add/append
2933 * @return $count Number of array elements
2935 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2937 //* 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));
2940 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2942 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2946 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2949 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2950 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2955 * Pops an element from a generic group
2957 * @param $keyGroup Main group for the key
2958 * @param $subGroup Sub group for the key
2959 * @param $key Key to unset
2960 * @return $value Last "popped" value
2962 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2964 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2967 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2969 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2974 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2977 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2978 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2983 * Shifts an element from a generic group
2985 * @param $keyGroup Main group for the key
2986 * @param $subGroup Sub group for the key
2987 * @param $key Key to unset
2988 * @return $value Last "popped" value
2990 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2992 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2995 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2997 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3002 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3005 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3006 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3011 * Count generic array group
3013 * @param $keyGroup Main group for the key
3014 * @return $count Count of given group
3016 protected final function countGenericArray ($keyGroup) {
3018 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3021 if (!isset($this->genericArray[$keyGroup])) {
3023 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3028 $count = count($this->genericArray[$keyGroup]);
3031 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3038 * Count generic array sub group
3040 * @param $keyGroup Main group for the key
3041 * @param $subGroup Sub group for the key
3042 * @return $count Count of given group
3044 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3046 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3049 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3051 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3056 $count = count($this->genericArray[$keyGroup][$subGroup]);
3059 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3066 * Count generic array elements
3068 * @param $keyGroup Main group for the key
3069 * @param $subGroup Sub group for the key
3070 * @para $key Key to count
3071 * @return $count Count of given key
3073 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3075 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3078 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3080 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3082 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3084 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3089 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3092 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3099 * Getter for whole generic group array
3101 * @param $keyGroup Key group to get
3102 * @return $array Whole generic array group
3104 protected final function getGenericArray ($keyGroup) {
3106 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3109 if (!isset($this->genericArray[$keyGroup])) {
3111 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3116 return $this->genericArray[$keyGroup];
3120 * Setter for generic array key
3122 * @param $keyGroup Key group to get
3123 * @param $subGroup Sub group for the key
3124 * @param $key Key to unset
3125 * @param $value Mixed value from generic array element
3128 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3130 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3133 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3137 * Getter for generic array key
3139 * @param $keyGroup Key group to get
3140 * @param $subGroup Sub group for the key
3141 * @param $key Key to unset
3142 * @return $value Mixed value from generic array element
3144 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3146 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3149 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3151 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3156 return $this->genericArray[$keyGroup][$subGroup][$key];
3160 * Sets a value in given generic array key/element
3162 * @param $keyGroup Main group for the key
3163 * @param $subGroup Sub group for the key
3164 * @param $key Key to set
3165 * @param $element Element to set
3166 * @param $value Value to set
3169 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3171 //* 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));
3174 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3178 * Getter for generic array element
3180 * @param $keyGroup Key group to get
3181 * @param $subGroup Sub group for the key
3182 * @param $key Key to look for
3183 * @param $element Element to look for
3184 * @return $value Mixed value from generic array element
3186 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3188 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3191 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3193 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3198 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3202 * Checks if a given sub group is valid (array)
3204 * @param $keyGroup Key group to get
3205 * @param $subGroup Sub group for the key
3206 * @return $isValid Whether given sub group is valid
3208 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3210 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3213 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3220 * Checks if a given key is valid (array)
3222 * @param $keyGroup Key group to get
3223 * @param $subGroup Sub group for the key
3224 * @param $key Key to check
3225 * @return $isValid Whether given sub group is valid
3227 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3229 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3232 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3239 * Initializes the web output instance
3243 protected function initWebOutputInstance () {
3244 // Get application instance
3245 $applicationInstance = Registry::getRegistry()->getInstance('app');
3247 // Is this a response instance?
3248 if ($this instanceof Responseable) {
3249 // Then set it in application instance
3250 $applicationInstance->setResponseInstance($this);
3253 // Init web output instance
3254 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3257 $this->setWebOutputInstance($outputInstance);
3261 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3263 * @param $boolean Boolean value
3264 * @return $translated Translated boolean value
3266 public static final function translateBooleanToYesNo ($boolean) {
3267 // Make sure it is really boolean
3268 assert(is_bool($boolean));
3271 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3273 // ... and return it
3278 * Encodes raw data (almost any type) by "serializing" it and then pack it
3279 * into a "binary format".
3281 * @param $rawData Raw data (almost any type)
3282 * @return $encoded Encoded data
3284 protected function encodeData ($rawData) {
3285 // Make sure no objects or resources pass through
3286 assert(!is_object($rawData));
3287 assert(!is_resource($rawData));
3289 // First "serialize" it (json_encode() is faster than serialize())
3290 $encoded = $this->packString(json_encode($rawData));
3297 * Pack a string into a "binary format". Please execuse me that this is
3298 * widely undocumented. :-(
3300 * @param $str Unpacked string
3301 * @return $packed Packed string
3302 * @todo Improve documentation
3304 protected function packString ($str) {
3306 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3308 // First compress the string (gzcompress is okay)
3309 $str = gzcompress($str);
3314 // And start the "encoding" loop
3315 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3317 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3318 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3320 if (($idx + $i) <= strlen($str)) {
3321 $ord = ord(substr($str, ($idx + $i), 1));
3323 $add = $ord * pow(256, $factor);
3327 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3331 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3332 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3334 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3335 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3341 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');
3346 * Checks whether the given file/path is in open_basedir(). This does not
3347 * gurantee that the file is actually readable and/or writeable. If you need
3348 * such gurantee then please use isReadableFile() instead.
3350 * @param $filePathName Name of the file/path to be checked
3351 * @return $isReachable Whether it is within open_basedir()
3353 protected static function isReachableFilePath ($filePathName) {
3354 // Is not reachable by default
3355 $isReachable = FALSE;
3357 // Get open_basedir parameter
3358 $openBaseDir = ini_get('open_basedir');
3361 if (!empty($openBaseDir)) {
3362 // Check all entries
3363 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3364 // Check on existence
3365 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3367 $isReachable = TRUE;
3371 // If open_basedir is not set, all is allowed
3372 $isReachable = TRUE;
3376 return $isReachable;
3380 * Checks whether the give file is within open_basedir() (done by
3381 * isReachableFilePath()), is actually a file and is readable.
3383 * @param $fileName Name of the file to be checked
3384 * @return $isReadable Whether the file is readable (and therefor exists)
3386 public static function isReadableFile ($fileName) {
3387 // Default is not readable
3388 $isReadable = FALSE;
3390 // Is within parameters, so check if it is a file and readable
3391 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3398 * Creates a full-qualified file name (FQFN) for given file name by adding
3399 * a configured temporary file path to it.
3401 * @param $fileName Name for temporary file
3402 * @return $fqfn Full-qualified file name
3403 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3404 * @throws FileIoException If the file cannot be written
3406 protected static function createTempPathForFile ($fileName) {
3408 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3410 // Is the path writeable?
3411 if (!is_writable($basePath)) {
3412 // Path is write-protected
3413 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3417 $fqfn = $basePath . '/' . $fileName;
3420 if (!self::isReachableFilePath($fqfn)) {
3422 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3430 * "Getter" for a printable state name
3432 * @return $stateName Name of the node's state in a printable format
3434 public final function getPrintableState () {
3435 // Default is 'null'
3436 $stateName = 'null';
3438 // Get the state instance
3439 $stateInstance = $this->getStateInstance();
3441 // Is it an instance of Stateable?
3442 if ($stateInstance instanceof Stateable) {
3443 // Then use that state name
3444 $stateName = $stateInstance->getStateName();
3452 * Handles socket error for given socket resource and peer data. This method
3453 * validates $socketResource if it is a valid resource (see is_resource())
3454 * but assumes valid data in array $recipientData, except that
3455 * count($recipientData) is always 2.
3457 * @param $method Value of __METHOD__ from calling method
3458 * @param $line Value of __LINE__ from calling method
3459 * @param $socketResource A valid socket resource
3460 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3462 * @throws InvalidSocketException If $socketResource is no socket resource
3463 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3464 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3466 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3467 // This method handles only socket resources
3468 if (!is_resource($socketResource)) {
3469 // No resource, abort here
3470 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3473 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3474 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3475 assert(isset($socketData[0]));
3476 assert(isset($socketData[1]));
3478 // Get error code for first validation (0 is not an error)
3479 $errorCode = socket_last_error($socketResource);
3481 // If the error code is zero, someone called this method without an error
3482 if ($errorCode == 0) {
3483 // No error detected (or previously cleared outside this method)
3484 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3487 // Get handler (method) name
3488 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3490 // Call-back the error handler method
3491 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3493 // Finally clear the error because it has been handled
3494 socket_clear_error($socketResource);