3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Generic\FrameworkInterface;
8 use CoreFramework\Manager\ManageableApplication;
9 use CoreFramework\Template\CompileableTemplate;
15 * The simulator system class is the super class of all other classes. This
16 * class handles saving of games etc.
18 * @author Roland Haeder <webmaster@shipsimu.org>
20 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
21 * @license GNU GPL 3.0 or any newer version
22 * @link http://www.shipsimu.org
24 * This program is free software: you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License as published by
26 * the Free Software Foundation, either version 3 of the License, or
27 * (at your option) any later version.
29 * This program is distributed in the hope that it will be useful,
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 * GNU General Public License for more details.
34 * You should have received a copy of the GNU General Public License
35 * along with this program. If not, see <http://www.gnu.org/licenses/>.
37 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
39 * Length of output from hash()
41 private static $hashLength = NULL;
46 private $realClass = 'BaseFrameworkSystem';
49 * Instance of a request class
51 private $requestInstance = NULL;
54 * Instance of a response class
56 private $responseInstance = NULL;
59 * Search criteria instance
61 private $searchInstance = NULL;
64 * Update criteria instance
66 private $updateInstance = NULL;
69 * The file I/O instance for the template loader
71 private $fileIoInstance = NULL;
76 private $resolverInstance = NULL;
79 * Template engine instance
81 private $templateInstance = NULL;
84 * Database result instance
86 private $resultInstance = NULL;
89 * Instance for user class
91 private $userInstance = NULL;
94 * A controller instance
96 private $controllerInstance = NULL;
101 private $rngInstance = NULL;
104 * Instance of a crypto helper
106 private $cryptoInstance = NULL;
109 * Instance of an Iterator class
111 private $iteratorInstance = NULL;
114 * Instance of the list
116 private $listInstance = NULL;
121 private $menuInstance = NULL;
124 * Instance of the image
126 private $imageInstance = NULL;
129 * Instance of the stacker
131 private $stackInstance = NULL;
134 * A Compressor instance
136 private $compressorInstance = NULL;
139 * A Parseable instance
141 private $parserInstance = NULL;
144 * A HandleableProtocol instance
146 private $protocolInstance = NULL;
149 * A database wrapper instance
151 private $databaseInstance = NULL;
154 * A helper instance for the form
156 private $helperInstance = NULL;
159 * An instance of a Source class
161 private $sourceInstance = NULL;
164 * An instance of a UrlSource class
166 private $urlSourceInstance = NULL;
169 * An instance of a InputStream class
171 private $inputStreamInstance = NULL;
174 * An instance of a OutputStream class
176 private $outputStreamInstance = NULL;
179 * Networkable handler instance
181 private $handlerInstance = NULL;
184 * Visitor handler instance
186 private $visitorInstance = NULL;
191 private $dhtInstance = NULL;
194 * An instance of a database wrapper class
196 private $wrapperInstance = NULL;
199 * An instance of a file I/O pointer class (not handler)
201 private $pointerInstance = NULL;
204 * An instance of an Indexable class
206 private $indexInstance = NULL;
209 * An instance of a Block class
211 private $blockInstance = NULL;
216 private $minableInstance = NULL;
219 * A FrameworkDirectory instance
221 private $directoryInstance = NULL;
226 private $listenerInstance = NULL;
229 * An instance of a communicator
231 private $communicatorInstance = NULL;
234 * The concrete output instance
236 private $outputInstance = NULL;
241 private $stateInstance = NULL;
244 * Thousands separator
246 private $thousands = '.'; // German
251 private $decimals = ','; // German
256 private $socketResource = FALSE;
259 * Regular expression to use for validation
261 private $regularExpression = '';
266 private $packageData = array();
271 private $genericArray = array();
276 private $commandName = '';
281 private $controllerName = '';
284 * Name of used protocol
286 private $protocolName = 'invalid';
289 * Array with bitmasks and such for pack/unpack methods to support both
290 * 32-bit and 64-bit systems
292 private $packingData = array(
295 'left' => 0xffff0000,
296 'right' => 0x0000ffff,
302 'left' => 0xffffffff00000000,
303 'right' => 0x00000000ffffffff,
310 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
312 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
314 private $archArrayElement = FALSE;
316 /***********************
317 * Exception codes.... *
318 ***********************/
320 // @todo Try to clean these constants up
321 const EXCEPTION_IS_NULL_POINTER = 0x001;
322 const EXCEPTION_IS_NO_OBJECT = 0x002;
323 const EXCEPTION_IS_NO_ARRAY = 0x003;
324 const EXCEPTION_MISSING_METHOD = 0x004;
325 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
326 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
327 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
328 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
329 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
330 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
331 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
332 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
333 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
334 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
335 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
336 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
337 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
338 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
339 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
340 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
341 const EXCEPTION_PATH_NOT_FOUND = 0x015;
342 const EXCEPTION_INVALID_PATH_NAME = 0x016;
343 const EXCEPTION_READ_PROTECED_PATH = 0x017;
344 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
345 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
346 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
347 const EXCEPTION_INVALID_RESOURCE = 0x01b;
348 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
349 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
350 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
351 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
352 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
353 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
354 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
355 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
356 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
357 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
358 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
359 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
360 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
361 const EXCEPTION_INVALID_STRING = 0x029;
362 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
363 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
364 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
365 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
366 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
367 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
368 const EXCEPTION_MISSING_ELEMENT = 0x030;
369 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
370 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
371 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
372 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
373 const EXCEPTION_FATAL_ERROR = 0x035;
374 const EXCEPTION_FILE_NOT_FOUND = 0x036;
375 const EXCEPTION_ASSERTION_FAILED = 0x037;
376 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
377 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
378 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
379 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
380 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
381 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
384 * Hexadecimal->Decimal translation array
386 private static $hexdec = array(
406 * Decimal->hexadecimal translation array
408 private static $dechex = array(
428 * Startup time in miliseconds
430 private static $startupTime = 0;
433 * Protected super constructor
435 * @param $className Name of the class
438 protected function __construct ($className) {
440 $this->setRealClass($className);
442 // Set configuration instance if no registry ...
443 if (!$this instanceof Register) {
444 // ... because registries doesn't need to be configured
445 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
448 // Is the startup time set? (0 cannot be TRUE anymore)
449 if (self::$startupTime == 0) {
451 self::$startupTime = microtime(TRUE);
455 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
459 * Destructor for all classes. You should not call this method on your own.
463 public function __destruct () {
464 // Flush any updated entries to the database
465 $this->flushPendingUpdates();
467 // Is this object already destroyed?
468 if ($this->__toString() != 'DestructedObject') {
469 // Destroy all informations about this class but keep some text about it alive
470 $this->setRealClass('DestructedObject');
471 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
472 // Already destructed object
473 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
478 // Do not call this twice
479 trigger_error(__METHOD__ . ': Called twice.');
485 * The __call() method where all non-implemented methods end up
487 * @param $methodName Name of the missing method
488 * @args $args Arguments passed to the method
491 public final function __call ($methodName, $args) {
492 return self::__callStatic($methodName, $args);
496 * The __callStatic() method where all non-implemented static methods end up
498 * @param $methodName Name of the missing method
499 * @args $args Arguments passed to the method
502 public static final function __callStatic ($methodName, $args) {
503 // Init argument string
506 // Is it NULL, empty or an array?
507 if (is_null($args)) {
509 $argsString = 'NULL';
510 } elseif (is_array($args)) {
514 // Some arguments are there
515 foreach ($args as $arg) {
516 // Add data about the argument
517 $argsString .= gettype($arg) . ':';
520 // Found a NULL argument
521 $argsString .= 'NULL';
522 } elseif (is_string($arg)) {
523 // Add length for strings
524 $argsString .= strlen($arg);
525 } elseif ((is_int($arg)) || (is_float($arg))) {
528 } elseif (is_array($arg)) {
529 // .. or size if array
530 $argsString .= count($arg);
531 } elseif (is_object($arg)) {
533 $reflection = new ReflectionClass($arg);
535 // Is an other object, maybe no __toString() available
536 $argsString .= $reflection->getName();
537 } elseif ($arg === TRUE) {
538 // ... is boolean 'TRUE'
539 $argsString .= 'TRUE';
540 } elseif ($arg === FALSE) {
541 // ... is boolean 'FALSE'
542 $argsString .= 'FALSE';
545 // Comma for next one
550 if (substr($argsString, -2, 1) == ',') {
551 $argsString = substr($argsString, 0, -2);
557 // Invalid arguments!
558 $argsString = '!INVALID:' . gettype($args) . '!';
561 // Output stub message
562 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
563 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
573 * Getter for $realClass
575 * @return $realClass The name of the real class (not BaseFrameworkSystem)
577 public function __toString () {
578 return $this->realClass;
582 * Magic method to catch setting of missing but set class fields/attributes
584 * @param $name Name of the field/attribute
585 * @param $value Value to store
588 public final function __set ($name, $value) {
589 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
592 print_r($value, TRUE)
597 * Magic method to catch getting of missing fields/attributes
599 * @param $name Name of the field/attribute
602 public final function __get ($name) {
603 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
609 * Magic method to catch unsetting of missing fields/attributes
611 * @param $name Name of the field/attribute
614 public final function __unset ($name) {
615 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
621 * Magic method to catch object serialization
623 * @return $unsupported Unsupported method
624 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
626 public final function __sleep () {
627 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
631 * Magic method to catch object deserialization
633 * @return $unsupported Unsupported method
634 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
636 public final function __wakeup () {
637 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
641 * Magic method to catch calls when an object instance is called
643 * @return $unsupported Unsupported method
644 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
646 public final function __invoke () {
647 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
651 * Setter for the real class name
653 * @param $realClass Class name (string)
656 public final function setRealClass ($realClass) {
658 $this->realClass = (string) $realClass;
662 * Setter for database result instance
664 * @param $resultInstance An instance of a database result class
666 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
668 protected final function setResultInstance (SearchableResult $resultInstance) {
669 $this->resultInstance = $resultInstance;
673 * Getter for database result instance
675 * @return $resultInstance An instance of a database result class
677 public final function getResultInstance () {
678 return $this->resultInstance;
682 * Setter for template engine instances
684 * @param $templateInstance An instance of a template engine class
687 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
688 $this->templateInstance = $templateInstance;
692 * Getter for template engine instances
694 * @return $templateInstance An instance of a template engine class
696 protected final function getTemplateInstance () {
697 return $this->templateInstance;
701 * Setter for search instance
703 * @param $searchInstance Searchable criteria instance
706 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
707 $this->searchInstance = $searchInstance;
711 * Getter for search instance
713 * @return $searchInstance Searchable criteria instance
715 public final function getSearchInstance () {
716 return $this->searchInstance;
720 * Setter for update instance
722 * @param $updateInstance Searchable criteria instance
725 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
726 $this->updateInstance = $updateInstance;
730 * Getter for update instance
732 * @return $updateInstance Updateable criteria instance
734 public final function getUpdateInstance () {
735 return $this->updateInstance;
739 * Setter for resolver instance
741 * @param $resolverInstance Instance of a command resolver class
744 public final function setResolverInstance (Resolver $resolverInstance) {
745 $this->resolverInstance = $resolverInstance;
749 * Getter for resolver instance
751 * @return $resolverInstance Instance of a command resolver class
753 public final function getResolverInstance () {
754 return $this->resolverInstance;
758 * Setter for language instance
760 * @param $configInstance The configuration instance which shall
761 * be FrameworkConfiguration
764 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
765 Registry::getRegistry()->addInstance('config', $configInstance);
769 * Getter for configuration instance
771 * @return $configInstance Configuration instance
773 public final function getConfigInstance () {
774 $configInstance = Registry::getRegistry()->getInstance('config');
775 return $configInstance;
779 * Setter for debug instance
781 * @param $debugInstance The instance for debug output class
784 public final function setDebugInstance (DebugMiddleware $debugInstance) {
785 Registry::getRegistry()->addInstance('debug', $debugInstance);
789 * Getter for debug instance
791 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
793 public final function getDebugInstance () {
794 // Get debug instance
795 $debugInstance = Registry::getRegistry()->getInstance('debug');
798 return $debugInstance;
802 * Setter for web output instance
804 * @param $webInstance The instance for web output class
807 public final function setWebOutputInstance (OutputStreamer $webInstance) {
808 Registry::getRegistry()->addInstance('web_output', $webInstance);
812 * Getter for web output instance
814 * @return $webOutputInstance - Instance to class WebOutput
816 public final function getWebOutputInstance () {
817 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
818 return $webOutputInstance;
822 * Setter for database instance
824 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
827 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
828 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
832 * Getter for database layer
834 * @return $databaseInstance The database layer instance
836 public final function getDatabaseInstance () {
838 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
841 return $databaseInstance;
845 * Setter for compressor channel
847 * @param $compressorInstance An instance of CompressorChannel
850 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
851 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
855 * Getter for compressor channel
857 * @return $compressorInstance The compressor channel
859 public final function getCompressorChannel () {
860 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
861 return $compressorInstance;
865 * Protected getter for a manageable application helper class
867 * @return $applicationInstance An instance of a manageable application helper class
869 protected final function getApplicationInstance () {
870 $applicationInstance = Registry::getRegistry()->getInstance('application');
871 return $applicationInstance;
875 * Setter for a manageable application helper class
877 * @param $applicationInstance An instance of a manageable application helper class
880 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
881 Registry::getRegistry()->addInstance('application', $applicationInstance);
885 * Setter for request instance
887 * @param $requestInstance An instance of a Requestable class
890 public final function setRequestInstance (Requestable $requestInstance) {
891 $this->requestInstance = $requestInstance;
895 * Getter for request instance
897 * @return $requestInstance An instance of a Requestable class
899 public final function getRequestInstance () {
900 return $this->requestInstance;
904 * Setter for response instance
906 * @param $responseInstance An instance of a Responseable class
909 public final function setResponseInstance (Responseable $responseInstance) {
910 $this->responseInstance = $responseInstance;
914 * Getter for response instance
916 * @return $responseInstance An instance of a Responseable class
918 public final function getResponseInstance () {
919 return $this->responseInstance;
923 * Private getter for language instance
925 * @return $langInstance An instance to the language sub-system
927 protected final function getLanguageInstance () {
928 $langInstance = Registry::getRegistry()->getInstance('language');
929 return $langInstance;
933 * Setter for language instance
935 * @param $langInstance An instance to the language sub-system
937 * @see LanguageSystem
939 public final function setLanguageInstance (ManageableLanguage $langInstance) {
940 Registry::getRegistry()->addInstance('language', $langInstance);
944 * Private getter for file IO instance
946 * @return $fileIoInstance An instance to the file I/O sub-system
948 protected final function getFileIoInstance () {
949 return $this->fileIoInstance;
953 * Setter for file I/O instance
955 * @param $fileIoInstance An instance to the file I/O sub-system
958 public final function setFileIoInstance (IoHandler $fileIoInstance) {
959 $this->fileIoInstance = $fileIoInstance;
963 * Protected setter for user instance
965 * @param $userInstance An instance of a user class
968 protected final function setUserInstance (ManageableAccount $userInstance) {
969 $this->userInstance = $userInstance;
973 * Getter for user instance
975 * @return $userInstance An instance of a user class
977 public final function getUserInstance () {
978 return $this->userInstance;
982 * Setter for controller instance (this surely breaks a bit the MVC patterm)
984 * @param $controllerInstance An instance of the controller
987 public final function setControllerInstance (Controller $controllerInstance) {
988 $this->controllerInstance = $controllerInstance;
992 * Getter for controller instance (this surely breaks a bit the MVC patterm)
994 * @return $controllerInstance An instance of the controller
996 public final function getControllerInstance () {
997 return $this->controllerInstance;
1001 * Setter for RNG instance
1003 * @param $rngInstance An instance of a random number generator (RNG)
1006 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1007 $this->rngInstance = $rngInstance;
1011 * Getter for RNG instance
1013 * @return $rngInstance An instance of a random number generator (RNG)
1015 public final function getRngInstance () {
1016 return $this->rngInstance;
1020 * Setter for Cryptable instance
1022 * @param $cryptoInstance An instance of a Cryptable class
1025 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1026 $this->cryptoInstance = $cryptoInstance;
1030 * Getter for Cryptable instance
1032 * @return $cryptoInstance An instance of a Cryptable class
1034 public final function getCryptoInstance () {
1035 return $this->cryptoInstance;
1039 * Setter for the list instance
1041 * @param $listInstance A list of Listable
1044 protected final function setListInstance (Listable $listInstance) {
1045 $this->listInstance = $listInstance;
1049 * Getter for the list instance
1051 * @return $listInstance A list of Listable
1053 protected final function getListInstance () {
1054 return $this->listInstance;
1058 * Setter for the menu instance
1060 * @param $menuInstance A RenderableMenu instance
1063 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1064 $this->menuInstance = $menuInstance;
1068 * Getter for the menu instance
1070 * @return $menuInstance A RenderableMenu instance
1072 protected final function getMenuInstance () {
1073 return $this->menuInstance;
1077 * Setter for image instance
1079 * @param $imageInstance An instance of an image
1082 public final function setImageInstance (BaseImage $imageInstance) {
1083 $this->imageInstance = $imageInstance;
1087 * Getter for image instance
1089 * @return $imageInstance An instance of an image
1091 public final function getImageInstance () {
1092 return $this->imageInstance;
1096 * Setter for stacker instance
1098 * @param $stackInstance An instance of an stacker
1101 public final function setStackInstance (Stackable $stackInstance) {
1102 $this->stackInstance = $stackInstance;
1106 * Getter for stacker instance
1108 * @return $stackInstance An instance of an stacker
1110 public final function getStackInstance () {
1111 return $this->stackInstance;
1115 * Setter for compressor instance
1117 * @param $compressorInstance An instance of an compressor
1120 public final function setCompressorInstance (Compressor $compressorInstance) {
1121 $this->compressorInstance = $compressorInstance;
1125 * Getter for compressor instance
1127 * @return $compressorInstance An instance of an compressor
1129 public final function getCompressorInstance () {
1130 return $this->compressorInstance;
1134 * Setter for Parseable instance
1136 * @param $parserInstance An instance of an Parseable
1139 public final function setParserInstance (Parseable $parserInstance) {
1140 $this->parserInstance = $parserInstance;
1144 * Getter for Parseable instance
1146 * @return $parserInstance An instance of an Parseable
1148 public final function getParserInstance () {
1149 return $this->parserInstance;
1153 * Setter for HandleableProtocol instance
1155 * @param $protocolInstance An instance of an HandleableProtocol
1158 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1159 $this->protocolInstance = $protocolInstance;
1163 * Getter for HandleableProtocol instance
1165 * @return $protocolInstance An instance of an HandleableProtocol
1167 public final function getProtocolInstance () {
1168 return $this->protocolInstance;
1172 * Setter for DatabaseWrapper instance
1174 * @param $wrapperInstance An instance of an DatabaseWrapper
1177 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1178 $this->wrapperInstance = $wrapperInstance;
1182 * Getter for DatabaseWrapper instance
1184 * @return $wrapperInstance An instance of an DatabaseWrapper
1186 public final function getWrapperInstance () {
1187 return $this->wrapperInstance;
1191 * Setter for socket resource
1193 * @param $socketResource A valid socket resource
1196 public final function setSocketResource ($socketResource) {
1197 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1198 $this->socketResource = $socketResource;
1202 * Getter for socket resource
1204 * @return $socketResource A valid socket resource
1206 public final function getSocketResource () {
1207 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1208 return $this->socketResource;
1212 * Setter for regular expression
1214 * @param $regularExpression A valid regular expression
1217 public final function setRegularExpression ($regularExpression) {
1218 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1219 $this->regularExpression = $regularExpression;
1223 * Getter for regular expression
1225 * @return $regularExpression A valid regular expression
1227 public final function getRegularExpression () {
1228 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1229 return $this->regularExpression;
1233 * Setter for helper instance
1235 * @param $helperInstance An instance of a helper class
1238 protected final function setHelperInstance (Helper $helperInstance) {
1239 $this->helperInstance = $helperInstance;
1243 * Getter for helper instance
1245 * @return $helperInstance An instance of a helper class
1247 public final function getHelperInstance () {
1248 return $this->helperInstance;
1252 * Setter for a Source instance
1254 * @param $sourceInstance An instance of a Source class
1257 protected final function setSourceInstance (Source $sourceInstance) {
1258 $this->sourceInstance = $sourceInstance;
1262 * Getter for a Source instance
1264 * @return $sourceInstance An instance of a Source class
1266 protected final function getSourceInstance () {
1267 return $this->sourceInstance;
1271 * Setter for a UrlSource instance
1273 * @param $sourceInstance An instance of a UrlSource class
1276 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1277 $this->urlSourceInstance = $urlSourceInstance;
1281 * Getter for a UrlSource instance
1283 * @return $urlSourceInstance An instance of a UrlSource class
1285 protected final function getUrlSourceInstance () {
1286 return $this->urlSourceInstance;
1290 * Getter for a InputStream instance
1292 * @param $inputStreamInstance The InputStream instance
1294 protected final function getInputStreamInstance () {
1295 return $this->inputStreamInstance;
1299 * Setter for a InputStream instance
1301 * @param $inputStreamInstance The InputStream instance
1304 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1305 $this->inputStreamInstance = $inputStreamInstance;
1309 * Getter for a OutputStream instance
1311 * @param $outputStreamInstance The OutputStream instance
1313 protected final function getOutputStreamInstance () {
1314 return $this->outputStreamInstance;
1318 * Setter for a OutputStream instance
1320 * @param $outputStreamInstance The OutputStream instance
1323 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1324 $this->outputStreamInstance = $outputStreamInstance;
1328 * Setter for handler instance
1330 * @param $handlerInstance An instance of a Handleable class
1333 protected final function setHandlerInstance (Handleable $handlerInstance) {
1334 $this->handlerInstance = $handlerInstance;
1338 * Getter for handler instance
1340 * @return $handlerInstance A Networkable instance
1342 protected final function getHandlerInstance () {
1343 return $this->handlerInstance;
1347 * Setter for visitor instance
1349 * @param $visitorInstance A Visitor instance
1352 protected final function setVisitorInstance (Visitor $visitorInstance) {
1353 $this->visitorInstance = $visitorInstance;
1357 * Getter for visitor instance
1359 * @return $visitorInstance A Visitor instance
1361 protected final function getVisitorInstance () {
1362 return $this->visitorInstance;
1366 * Setter for DHT instance
1368 * @param $dhtInstance A Distributable instance
1371 protected final function setDhtInstance (Distributable $dhtInstance) {
1372 $this->dhtInstance = $dhtInstance;
1376 * Getter for DHT instance
1378 * @return $dhtInstance A Distributable instance
1380 protected final function getDhtInstance () {
1381 return $this->dhtInstance;
1385 * Setter for raw package Data
1387 * @param $packageData Raw package Data
1390 public final function setPackageData (array $packageData) {
1391 $this->packageData = $packageData;
1395 * Getter for raw package Data
1397 * @return $packageData Raw package Data
1399 public function getPackageData () {
1400 return $this->packageData;
1405 * Setter for Iterator instance
1407 * @param $iteratorInstance An instance of an Iterator
1410 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1411 $this->iteratorInstance = $iteratorInstance;
1415 * Getter for Iterator instance
1417 * @return $iteratorInstance An instance of an Iterator
1419 public final function getIteratorInstance () {
1420 return $this->iteratorInstance;
1424 * Setter for FilePointer instance
1426 * @param $pointerInstance An instance of an FilePointer class
1429 protected final function setPointerInstance (FilePointer $pointerInstance) {
1430 $this->pointerInstance = $pointerInstance;
1434 * Getter for FilePointer instance
1436 * @return $pointerInstance An instance of an FilePointer class
1438 public final function getPointerInstance () {
1439 return $this->pointerInstance;
1443 * Unsets pointer instance which triggers a call of __destruct() if the
1444 * instance is still there. This is surely not fatal on already "closed"
1445 * file pointer instances.
1447 * I don't want to mess around with above setter by giving it a default
1448 * value NULL as setter should always explicitly only set (existing) object
1449 * instances and NULL is NULL.
1453 protected final function unsetPointerInstance () {
1454 // Simply it to NULL
1455 $this->pointerInstance = NULL;
1459 * Setter for Indexable instance
1461 * @param $indexInstance An instance of an Indexable class
1464 protected final function setIndexInstance (Indexable $indexInstance) {
1465 $this->indexInstance = $indexInstance;
1469 * Getter for Indexable instance
1471 * @return $indexInstance An instance of an Indexable class
1473 public final function getIndexInstance () {
1474 return $this->indexInstance;
1478 * Setter for Block instance
1480 * @param $blockInstance An instance of an Block class
1483 protected final function setBlockInstance (Block $blockInstance) {
1484 $this->blockInstance = $blockInstance;
1488 * Getter for Block instance
1490 * @return $blockInstance An instance of an Block class
1492 public final function getBlockInstance () {
1493 return $this->blockInstance;
1497 * Setter for Minable instance
1499 * @param $minableInstance A Minable instance
1502 protected final function setMinableInstance (Minable $minableInstance) {
1503 $this->minableInstance = $minableInstance;
1507 * Getter for minable instance
1509 * @return $minableInstance A Minable instance
1511 protected final function getMinableInstance () {
1512 return $this->minableInstance;
1516 * Setter for FrameworkDirectory instance
1518 * @param $directoryInstance A FrameworkDirectoryPointer instance
1521 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1522 $this->directoryInstance = $directoryInstance;
1526 * Getter for FrameworkDirectory instance
1528 * @return $directoryInstance A FrameworkDirectory instance
1530 protected final function getDirectoryInstance () {
1531 return $this->directoryInstance;
1535 * Setter for listener instance
1537 * @param $listenerInstance A Listenable instance
1540 protected final function setListenerInstance (Listenable $listenerInstance) {
1541 $this->listenerInstance = $listenerInstance;
1545 * Getter for listener instance
1547 * @return $listenerInstance A Listenable instance
1549 protected final function getListenerInstance () {
1550 return $this->listenerInstance;
1554 * Getter for communicator instance
1556 * @return $communicatorInstance An instance of a Communicator class
1558 public final function getCommunicatorInstance () {
1559 return $this->communicatorInstance;
1563 * Setter for communicator instance
1565 * @param $communicatorInstance An instance of a Communicator class
1568 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1569 $this->communicatorInstance = $communicatorInstance;
1573 * Setter for state instance
1575 * @param $stateInstance A Stateable instance
1578 public final function setStateInstance (Stateable $stateInstance) {
1579 $this->stateInstance = $stateInstance;
1583 * Getter for state instance
1585 * @return $stateInstance A Stateable instance
1587 public final function getStateInstance () {
1588 return $this->stateInstance;
1592 * Setter for output instance
1594 * @param $outputInstance The debug output instance
1597 public final function setOutputInstance (OutputStreamer $outputInstance) {
1598 $this->outputInstance = $outputInstance;
1602 * Getter for output instance
1604 * @return $outputInstance The debug output instance
1606 public final function getOutputInstance () {
1607 return $this->outputInstance;
1611 * Setter for command name
1613 * @param $commandName Last validated command name
1616 protected final function setCommandName ($commandName) {
1617 $this->commandName = $commandName;
1621 * Getter for command name
1623 * @return $commandName Last validated command name
1625 protected final function getCommandName () {
1626 return $this->commandName;
1630 * Setter for controller name
1632 * @param $controllerName Last validated controller name
1635 protected final function setControllerName ($controllerName) {
1636 $this->controllerName = $controllerName;
1640 * Getter for controller name
1642 * @return $controllerName Last validated controller name
1644 protected final function getControllerName () {
1645 return $this->controllerName;
1649 * Getter for protocol name
1651 * @return $protocolName Name of used protocol
1653 public final function getProtocolName () {
1654 return $this->protocolName;
1658 * Setter for protocol name
1660 * @param $protocolName Name of used protocol
1663 protected final function setProtocolName ($protocolName) {
1664 $this->protocolName = $protocolName;
1668 * Checks whether an object equals this object. You should overwrite this
1669 * method to implement own equality checks
1671 * @param $objectInstance An instance of a FrameworkInterface object
1672 * @return $equals Whether both objects equals
1674 public function equals (FrameworkInterface $objectInstance) {
1677 $this->__toString() == $objectInstance->__toString()
1679 $this->hashCode() == $objectInstance->hashCode()
1682 // Return the result
1687 * Generates a generic hash code of this class. You should really overwrite
1688 * this method with your own hash code generator code. But keep KISS in mind.
1690 * @return $hashCode A generic hash code respresenting this whole class
1692 public function hashCode () {
1694 return crc32($this->__toString());
1698 * Formats computer generated price values into human-understandable formats
1699 * with thousand and decimal separators.
1701 * @param $value The in computer format value for a price
1702 * @param $currency The currency symbol (use HTML-valid characters!)
1703 * @param $decNum Number of decimals after commata
1704 * @return $price The for the current language formated price string
1705 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1706 * thousands separator
1709 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1710 // Are all required attriutes set?
1711 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1712 // Throw an exception
1713 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1717 $value = (float) $value;
1719 // Reformat the US number
1720 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1722 // Return as string...
1727 * Appends a trailing slash to a string
1729 * @param $str A string (maybe) without trailing slash
1730 * @return $str A string with an auto-appended trailing slash
1732 public final function addMissingTrailingSlash ($str) {
1733 // Is there a trailing slash?
1734 if (substr($str, -1, 1) != '/') {
1738 // Return string with trailing slash
1743 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1744 * application helper instance (ApplicationHelper by default).
1746 * @param $applicationInstance An application helper instance or
1747 * null if we shall use the default
1748 * @return $templateInstance The template engine instance
1749 * @throws NullPointerException If the discovered application
1750 * instance is still null
1752 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1753 // Is the application instance set?
1754 if (is_null($applicationInstance)) {
1755 // Get the current instance
1756 $applicationInstance = $this->getApplicationInstance();
1759 if (is_null($applicationInstance)) {
1760 // Thrown an exception
1761 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1765 // Initialize the template engine
1766 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1768 // Return the prepared instance
1769 return $templateInstance;
1773 * Debugs this instance by putting out it's full content
1775 * @param $message Optional message to show in debug output
1778 public final function debugInstance ($message = '') {
1779 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1780 restore_error_handler();
1785 // Is a message set?
1786 if (!empty($message)) {
1787 // Construct message
1788 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1791 // Generate the output
1792 $content .= sprintf('<pre>%s</pre>',
1795 print_r($this, TRUE)
1801 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>',
1802 $this->__toString(),
1804 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1809 * Replaces control characters with printable output
1811 * @param $str String with control characters
1812 * @return $str Replaced string
1814 protected function replaceControlCharacters ($str) {
1817 chr(13), '[r]', str_replace(
1818 chr(10), '[n]', str_replace(
1828 * Output a partial stub message for the caller method
1830 * @param $message An optional message to display
1833 protected function partialStub ($message = '') {
1834 // Get the backtrace
1835 $backtrace = debug_backtrace();
1837 // Generate the class::method string
1838 $methodName = 'UnknownClass->unknownMethod';
1839 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1840 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1843 // Construct the full message
1844 $stubMessage = sprintf('[%s:] Partial stub!',
1848 // Is the extra message given?
1849 if (!empty($message)) {
1850 // Then add it as well
1851 $stubMessage .= ' Message: ' . $message;
1854 // Debug instance is there?
1855 if (!is_null($this->getDebugInstance())) {
1856 // Output stub message
1857 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1860 trigger_error($stubMessage);
1866 * Outputs a debug backtrace and stops further script execution
1868 * @param $message An optional message to output
1869 * @param $doExit Whether exit the program (TRUE is default)
1872 public function debugBackTrace ($message = '', $doExit = TRUE) {
1873 // Sorry, there is no other way getting this nice backtrace
1874 if (!empty($message)) {
1876 printf('Message: %s<br />' . PHP_EOL, $message);
1880 debug_print_backtrace();
1884 if ($doExit === TRUE) {
1890 * Creates an instance of a debugger instance
1892 * @param $className Name of the class (currently unsupported)
1893 * @return $debugInstance An instance of a debugger class
1894 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1896 public final static function createDebugInstance ($className) {
1897 // Is the instance set?
1898 if (!Registry::getRegistry()->instanceExists('debug')) {
1899 // Init debug instance
1900 $debugInstance = NULL;
1904 // Get a debugger instance
1905 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1906 } catch (NullPointerException $e) {
1907 // Didn't work, no instance there
1908 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1911 // Empty string should be ignored and used for testing the middleware
1912 DebugMiddleware::getSelfInstance()->output('');
1914 // Set it in its own class. This will set it in the registry
1915 $debugInstance->setDebugInstance($debugInstance);
1917 // Get instance from registry
1918 $debugInstance = Registry::getRegistry()->getDebugInstance();
1922 return $debugInstance;
1926 * Simple output of a message with line-break
1928 * @param $message Message to output
1931 public function outputLine ($message) {
1933 print($message . PHP_EOL);
1937 * Outputs a debug message whether to debug instance (should be set!) or
1938 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1939 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1941 * @param $message Message we shall send out...
1942 * @param $doPrint Whether print or die here (default: print)
1943 * @paran $stripTags Whether to strip tags (default: FALSE)
1946 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1947 // Set debug instance to NULL
1948 $debugInstance = NULL;
1952 // Get debug instance
1953 $debugInstance = $this->getDebugInstance();
1954 } catch (NullPointerException $e) {
1955 // The debug instance is not set (yet)
1958 // Is the debug instance there?
1959 if (is_object($debugInstance)) {
1960 // Use debug output handler
1961 $debugInstance->output($message, $stripTags);
1963 if ($doPrint === FALSE) {
1964 // Die here if not printed
1968 // Are debug times enabled?
1969 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1971 $message = $this->getPrintableExecutionTime() . $message;
1975 if ($doPrint === TRUE) {
1977 $this->outputLine($message);
1986 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1988 * @param $str The string, what ever it is needs to be converted
1989 * @return $className Generated class name
1991 public static final function convertToClassName ($str) {
1995 // Convert all dashes in underscores
1996 $str = self::convertDashesToUnderscores($str);
1998 // Now use that underscores to get classname parts for hungarian style
1999 foreach (explode('_', $str) as $strPart) {
2000 // Make the class name part lower case and first upper case
2001 $className .= ucfirst(strtolower($strPart));
2004 // Return class name
2009 * Converts dashes to underscores, e.g. useable for configuration entries
2011 * @param $str The string with maybe dashes inside
2012 * @return $str The converted string with no dashed, but underscores
2014 public static final function convertDashesToUnderscores ($str) {
2016 $str = str_replace('-', '_', $str);
2018 // Return converted string
2023 * Marks up the code by adding e.g. line numbers
2025 * @param $phpCode Unmarked PHP code
2026 * @return $markedCode Marked PHP code
2028 public function markupCode ($phpCode) {
2033 $errorArray = error_get_last();
2035 // Init the code with error message
2036 if (is_array($errorArray)) {
2038 $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>',
2039 basename($errorArray['file']),
2040 $errorArray['line'],
2041 $errorArray['message'],
2046 // Add line number to the code
2047 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2049 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2051 htmlentities($code, ENT_QUOTES)
2060 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2061 * beatiful for web-based front-ends. If null is given a message id
2062 * null_timestamp will be resolved and returned.
2064 * @param $timestamp Timestamp to prepare (filter) for display
2065 * @return $readable A readable timestamp
2067 public function doFilterFormatTimestamp ($timestamp) {
2068 // Default value to return
2071 // Is the timestamp null?
2072 if (is_null($timestamp)) {
2073 // Get a message string
2074 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2076 switch ($this->getLanguageInstance()->getLanguageCode()) {
2077 case 'de': // German format is a bit different to default
2078 // Split the GMT stamp up
2079 $dateTime = explode(' ', $timestamp );
2080 $dateArray = explode('-', $dateTime[0]);
2081 $timeArray = explode(':', $dateTime[1]);
2083 // Construct the timestamp
2084 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2094 default: // Default is pass-through
2095 $readable = $timestamp;
2105 * Filter a given number into a localized number
2107 * @param $value The raw value from e.g. database
2108 * @return $localized Localized value
2110 public function doFilterFormatNumber ($value) {
2111 // Generate it from config and localize dependencies
2112 switch ($this->getLanguageInstance()->getLanguageCode()) {
2113 case 'de': // German format is a bit different to default
2114 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2117 default: // US, etc.
2118 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2127 * "Getter" for databse entry
2129 * @return $entry An array with database entries
2130 * @throws NullPointerException If the database result is not found
2131 * @throws InvalidDatabaseResultException If the database result is invalid
2133 protected final function getDatabaseEntry () {
2134 // Is there an instance?
2135 if (!$this->getResultInstance() instanceof SearchableResult) {
2136 // Throw an exception here
2137 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2141 $this->getResultInstance()->rewind();
2143 // Do we have an entry?
2144 if ($this->getResultInstance()->valid() === FALSE) {
2145 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2146 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2150 $this->getResultInstance()->next();
2153 $entry = $this->getResultInstance()->current();
2160 * Getter for field name
2162 * @param $fieldName Field name which we shall get
2163 * @return $fieldValue Field value from the user
2164 * @throws NullPointerException If the result instance is null
2166 public final function getField ($fieldName) {
2167 // Default field value
2170 // Get result instance
2171 $resultInstance = $this->getResultInstance();
2173 // Is this instance null?
2174 if (is_null($resultInstance)) {
2175 // Then the user instance is no longer valid (expired cookies?)
2176 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2179 // Get current array
2180 $fieldArray = $resultInstance->current();
2181 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2183 // Convert dashes to underscore
2184 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2186 // Does the field exist?
2187 if ($this->isFieldSet($fieldName)) {
2189 $fieldValue = $fieldArray[$fieldName2];
2190 } elseif (defined('DEVELOPER')) {
2191 // Missing field entry, may require debugging
2192 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2194 // Missing field entry, may require debugging
2195 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2203 * Checks if given field is set
2205 * @param $fieldName Field name to check
2206 * @return $isSet Whether the given field name is set
2207 * @throws NullPointerException If the result instance is null
2209 public function isFieldSet ($fieldName) {
2210 // Get result instance
2211 $resultInstance = $this->getResultInstance();
2213 // Is this instance null?
2214 if (is_null($resultInstance)) {
2215 // Then the user instance is no longer valid (expired cookies?)
2216 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2219 // Get current array
2220 $fieldArray = $resultInstance->current();
2221 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2223 // Convert dashes to underscore
2224 $fieldName = self::convertDashesToUnderscores($fieldName);
2227 $isSet = isset($fieldArray[$fieldName]);
2234 * Flushs all pending updates to the database layer
2238 public function flushPendingUpdates () {
2239 // Get result instance
2240 $resultInstance = $this->getResultInstance();
2242 // Do we have data to update?
2243 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2244 // Get wrapper class name config entry
2245 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2247 // Create object instance
2248 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2250 // Yes, then send the whole result to the database layer
2251 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2256 * Outputs a deprecation warning to the developer.
2258 * @param $message The message we shall output to the developer
2260 * @todo Write a logging mechanism for productive mode
2262 public function deprecationWarning ($message) {
2263 // Is developer mode active?
2264 if (defined('DEVELOPER')) {
2265 // Debug instance is there?
2266 if (!is_null($this->getDebugInstance())) {
2267 // Output stub message
2268 self::createDebugInstance(__CLASS__)->debugOutput($message);
2271 trigger_error($message . "<br />\n");
2275 // @TODO Finish this part!
2276 $this->partialStub('Developer mode inactive. Message:' . $message);
2281 * Checks whether the given PHP extension is loaded
2283 * @param $phpExtension The PHP extension we shall check
2284 * @return $isLoaded Whether the PHP extension is loaded
2286 public final function isPhpExtensionLoaded ($phpExtension) {
2288 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2295 * "Getter" as a time() replacement but with milliseconds. You should use this
2296 * method instead of the encapsulated getimeofday() function.
2298 * @return $milliTime Timestamp with milliseconds
2300 public function getMilliTime () {
2301 // Get the time of day as float
2302 $milliTime = gettimeofday(TRUE);
2309 * Idles (sleeps) for given milliseconds
2311 * @return $hasSlept Whether it goes fine
2313 public function idle ($milliSeconds) {
2314 // Sleep is fine by default
2317 // Idle so long with found function
2318 if (function_exists('time_sleep_until')) {
2319 // Get current time and add idle time
2320 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2322 // New PHP 5.1.0 function found, ignore errors
2323 $hasSlept = @time_sleep_until($sleepUntil);
2326 * My Sun station doesn't have that function even with latest PHP
2329 usleep($milliSeconds * 1000);
2336 * Converts a hexadecimal string, even with negative sign as first string to
2337 * a decimal number using BC functions.
2339 * This work is based on comment #86673 on php.net documentation page at:
2340 * <http://de.php.net/manual/en/function.dechex.php#86673>
2342 * @param $hex Hexadecimal string
2343 * @return $dec Decimal number
2345 protected function hex2dec ($hex) {
2346 // Convert to all lower-case
2347 $hex = strtolower($hex);
2349 // Detect sign (negative/positive numbers)
2351 if (substr($hex, 0, 1) == '-') {
2353 $hex = substr($hex, 1);
2356 // Decode the hexadecimal string into a decimal number
2358 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2359 $factor = self::$hexdec[substr($hex, $i, 1)];
2360 $dec = bcadd($dec, bcmul($factor, $e));
2363 // Return the decimal number
2364 return $sign . $dec;
2368 * Converts even very large decimal numbers, also signed, to a hexadecimal
2371 * This work is based on comment #97756 on php.net documentation page at:
2372 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2374 * @param $dec Decimal number, even with negative sign
2375 * @param $maxLength Optional maximum length of the string
2376 * @return $hex Hexadecimal string
2378 protected function dec2hex ($dec, $maxLength = 0) {
2379 // maxLength can be zero or devideable by 2
2380 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2382 // Detect sign (negative/positive numbers)
2389 // Encode the decimal number into a hexadecimal string
2392 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2394 } while ($dec >= 1);
2397 * Leading zeros are required for hex-decimal "numbers". In some
2398 * situations more leading zeros are wanted, so check for both
2401 if ($maxLength > 0) {
2402 // Prepend more zeros
2403 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2404 } elseif ((strlen($hex) % 2) != 0) {
2405 // Only make string's length dividable by 2
2409 // Return the hexadecimal string
2410 return $sign . $hex;
2414 * Converts a ASCII string (0 to 255) into a decimal number.
2416 * @param $asc The ASCII string to be converted
2417 * @return $dec Decimal number
2419 protected function asc2dec ($asc) {
2420 // Convert it into a hexadecimal number
2421 $hex = bin2hex($asc);
2423 // And back into a decimal number
2424 $dec = $this->hex2dec($hex);
2431 * Converts a decimal number into an ASCII string.
2433 * @param $dec Decimal number
2434 * @return $asc An ASCII string
2436 protected function dec2asc ($dec) {
2437 // First convert the number into a hexadecimal string
2438 $hex = $this->dec2hex($dec);
2440 // Then convert it into the ASCII string
2441 $asc = $this->hex2asc($hex);
2448 * Converts a hexadecimal number into an ASCII string. Negative numbers
2451 * @param $hex Hexadecimal string
2452 * @return $asc An ASCII string
2454 protected function hex2asc ($hex) {
2455 // Check for length, it must be devideable by 2
2456 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2457 assert((strlen($hex) % 2) == 0);
2461 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2462 // Get the decimal number of the chunk
2463 $part = hexdec(substr($hex, $idx, 2));
2465 // Add it to the final string
2469 // Return the final string
2474 * Checks whether the given encoded data was encoded with Base64
2476 * @param $encodedData Encoded data we shall check
2477 * @return $isBase64 Whether the encoded data is Base64
2479 protected function isBase64Encoded ($encodedData) {
2481 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2488 * "Getter" to get response/request type from analysis of the system.
2490 * @return $responseType Analyzed response type
2492 protected static function getResponseTypeFromSystem () {
2493 // Default is console
2494 $responseType = 'console';
2496 // Is 'HTTP_HOST' set?
2497 if (isset($_SERVER['HTTP_HOST'])) {
2499 * Then it is a HTML response/request as RSS and so on may be
2500 * transfered over HTTP as well.
2502 $responseType = 'html';
2506 return $responseType;
2510 * Gets a cache key from Criteria instance
2512 * @param $criteriaInstance An instance of a Criteria class
2513 * @param $onlyKeys Only use these keys for a cache key
2514 * @return $cacheKey A cache key suitable for lookup/storage purposes
2516 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2518 $cacheKey = sprintf('%s@%s',
2519 $this->__toString(),
2520 $criteriaInstance->getCacheKey($onlyKeys)
2524 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2529 * Getter for startup time in miliseconds
2531 * @return $startupTime Startup time in miliseconds
2533 protected function getStartupTime () {
2534 return self::$startupTime;
2538 * "Getter" for a printable currently execution time in nice braces
2540 * @return $executionTime Current execution time in nice braces
2542 protected function getPrintableExecutionTime () {
2543 // Caculate the execution time
2544 $executionTime = microtime(TRUE) - $this->getStartupTime();
2546 // Pack it in nice braces
2547 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2550 return $executionTime;
2554 * Hashes a given string with a simple but stronger hash function (no salt)
2555 * and hex-encode it.
2557 * @param $str The string to be hashed
2558 * @return $hash The hash from string $str
2560 public static final function hash ($str) {
2561 // Hash given string with (better secure) hasher
2562 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2569 * "Getter" for length of hash() output. This will be "cached" to speed up
2572 * @return $length Length of hash() output
2574 public static final function getHashLength () {
2576 if (is_null(self::$hashLength)) {
2577 // No, then hash a string and save its length.
2578 self::$hashLength = strlen(self::hash('abc123'));
2582 return self::$hashLength;
2586 * Checks whether the given number is really a number (only chars 0-9).
2588 * @param $num A string consisting only chars between 0 and 9
2589 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2590 * @param $assertMismatch Whether to assert mismatches
2591 * @return $ret The (hopefully) secured numbered value
2593 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2594 // Filter all numbers out
2595 $ret = preg_replace('/[^0123456789]/', '', $num);
2598 if ($castValue === TRUE) {
2599 // Cast to biggest numeric type
2600 $ret = (double) $ret;
2603 // Assert only if requested
2604 if ($assertMismatch === TRUE) {
2605 // Has the whole value changed?
2606 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2614 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2616 * @param $num A string consisting only chars between 0 and 9
2617 * @param $assertMismatch Whether to assert mismatches
2618 * @return $ret The (hopefully) secured hext-numbered value
2620 public function hexval ($num, $assertMismatch = FALSE) {
2621 // Filter all numbers out
2622 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2624 // Assert only if requested
2625 if ($assertMismatch === TRUE) {
2626 // Has the whole value changed?
2627 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2635 * Checks whether start/end marker are set
2637 * @param $data Data to be checked
2638 * @return $isset Whether start/end marker are set
2640 public final function ifStartEndMarkersSet ($data) {
2642 $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));
2644 // ... and return it
2649 * Determines if an element is set in the generic array
2651 * @param $keyGroup Main group for the key
2652 * @param $subGroup Sub group for the key
2653 * @param $key Key to check
2654 * @param $element Element to check
2655 * @return $isset Whether the given key is set
2657 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2659 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2662 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2668 * Determines if a key is set in the generic array
2670 * @param $keyGroup Main group for the key
2671 * @param $subGroup Sub group for the key
2672 * @param $key Key to check
2673 * @return $isset Whether the given key is set
2675 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2677 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2680 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2688 * Determines if a group is set in the generic array
2690 * @param $keyGroup Main group
2691 * @param $subGroup Sub group
2692 * @return $isset Whether the given group is set
2694 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2696 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2699 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2706 * Getter for sub key group
2708 * @param $keyGroup Main key group
2709 * @param $subGroup Sub key group
2710 * @return $array An array with all array elements
2712 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2714 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2715 // No, then abort here
2716 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2721 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2724 return $this->genericArray[$keyGroup][$subGroup];
2728 * Unsets a given key in generic array
2730 * @param $keyGroup Main group for the key
2731 * @param $subGroup Sub group for the key
2732 * @param $key Key to unset
2735 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2737 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2740 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2744 * Unsets a given element in generic array
2746 * @param $keyGroup Main group for the key
2747 * @param $subGroup Sub group for the key
2748 * @param $key Key to unset
2749 * @param $element Element to unset
2752 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2754 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2757 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2761 * Append a string to a given generic array key
2763 * @param $keyGroup Main group for the key
2764 * @param $subGroup Sub group for the key
2765 * @param $key Key to unset
2766 * @param $value Value to add/append
2769 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2771 //* 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);
2773 // Is it already there?
2774 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2776 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2779 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2784 * Append a string to a given generic array element
2786 * @param $keyGroup Main group for the key
2787 * @param $subGroup Sub group for the key
2788 * @param $key Key to unset
2789 * @param $element Element to check
2790 * @param $value Value to add/append
2793 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2795 //* 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);
2797 // Is it already there?
2798 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2800 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2803 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2808 * Sets a string in a given generic array element
2810 * @param $keyGroup Main group for the key
2811 * @param $subGroup Sub group for the key
2812 * @param $key Key to unset
2813 * @param $element Element to check
2814 * @param $value Value to add/append
2817 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2819 //* 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);
2822 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2826 * Initializes given generic array group
2828 * @param $keyGroup Main group for the key
2829 * @param $subGroup Sub group for the key
2830 * @param $key Key to use
2831 * @param $forceInit Optionally force initialization
2834 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2836 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2838 // Is it already set?
2839 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2840 // Already initialized
2841 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2846 $this->genericArray[$keyGroup][$subGroup] = array();
2850 * Initializes given generic array key
2852 * @param $keyGroup Main group for the key
2853 * @param $subGroup Sub group for the key
2854 * @param $key Key to use
2855 * @param $forceInit Optionally force initialization
2858 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2860 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2862 // Is it already set?
2863 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2864 // Already initialized
2865 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2870 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2874 * Initializes given generic array element
2876 * @param $keyGroup Main group for the key
2877 * @param $subGroup Sub group for the key
2878 * @param $key Key to use
2879 * @param $element Element to use
2880 * @param $forceInit Optionally force initialization
2883 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2885 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2887 // Is it already set?
2888 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2889 // Already initialized
2890 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2895 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2899 * Pushes an element to a generic key
2901 * @param $keyGroup Main group for the key
2902 * @param $subGroup Sub group for the key
2903 * @param $key Key to use
2904 * @param $value Value to add/append
2905 * @return $count Number of array elements
2907 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2909 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2912 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2914 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2918 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2921 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2922 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2927 * Pushes an element to a generic array element
2929 * @param $keyGroup Main group for the key
2930 * @param $subGroup Sub group for the key
2931 * @param $key Key to use
2932 * @param $element Element to check
2933 * @param $value Value to add/append
2934 * @return $count Number of array elements
2936 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2938 //* 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));
2941 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2943 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2947 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2950 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2951 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2956 * Pops an element from a generic group
2958 * @param $keyGroup Main group for the key
2959 * @param $subGroup Sub group for the key
2960 * @param $key Key to unset
2961 * @return $value Last "popped" value
2963 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2965 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2968 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2970 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2975 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2978 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2979 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2984 * Shifts an element from a generic group
2986 * @param $keyGroup Main group for the key
2987 * @param $subGroup Sub group for the key
2988 * @param $key Key to unset
2989 * @return $value Last "popped" value
2991 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2993 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2996 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2998 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3003 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3006 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3007 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3012 * Count generic array group
3014 * @param $keyGroup Main group for the key
3015 * @return $count Count of given group
3017 protected final function countGenericArray ($keyGroup) {
3019 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3022 if (!isset($this->genericArray[$keyGroup])) {
3024 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3029 $count = count($this->genericArray[$keyGroup]);
3032 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3039 * Count generic array sub group
3041 * @param $keyGroup Main group for the key
3042 * @param $subGroup Sub group for the key
3043 * @return $count Count of given group
3045 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3047 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3050 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3052 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3057 $count = count($this->genericArray[$keyGroup][$subGroup]);
3060 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3067 * Count generic array elements
3069 * @param $keyGroup Main group for the key
3070 * @param $subGroup Sub group for the key
3071 * @para $key Key to count
3072 * @return $count Count of given key
3074 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3076 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3079 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3081 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3083 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3085 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3090 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3093 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3100 * Getter for whole generic group array
3102 * @param $keyGroup Key group to get
3103 * @return $array Whole generic array group
3105 protected final function getGenericArray ($keyGroup) {
3107 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3110 if (!isset($this->genericArray[$keyGroup])) {
3112 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3117 return $this->genericArray[$keyGroup];
3121 * Setter for generic array key
3123 * @param $keyGroup Key group to get
3124 * @param $subGroup Sub group for the key
3125 * @param $key Key to unset
3126 * @param $value Mixed value from generic array element
3129 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3131 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3134 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3138 * Getter for generic array key
3140 * @param $keyGroup Key group to get
3141 * @param $subGroup Sub group for the key
3142 * @param $key Key to unset
3143 * @return $value Mixed value from generic array element
3145 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3147 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3150 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3152 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3157 return $this->genericArray[$keyGroup][$subGroup][$key];
3161 * Sets a value in given generic array key/element
3163 * @param $keyGroup Main group for the key
3164 * @param $subGroup Sub group for the key
3165 * @param $key Key to set
3166 * @param $element Element to set
3167 * @param $value Value to set
3170 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3172 //* 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));
3175 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3179 * Getter for generic array element
3181 * @param $keyGroup Key group to get
3182 * @param $subGroup Sub group for the key
3183 * @param $key Key to look for
3184 * @param $element Element to look for
3185 * @return $value Mixed value from generic array element
3187 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3189 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3192 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3194 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3199 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3203 * Checks if a given sub group is valid (array)
3205 * @param $keyGroup Key group to get
3206 * @param $subGroup Sub group for the key
3207 * @return $isValid Whether given sub group is valid
3209 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3211 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3214 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3221 * Checks if a given key is valid (array)
3223 * @param $keyGroup Key group to get
3224 * @param $subGroup Sub group for the key
3225 * @param $key Key to check
3226 * @return $isValid Whether given sub group is valid
3228 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3230 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3233 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3240 * Initializes the web output instance
3244 protected function initWebOutputInstance () {
3245 // Get application instance
3246 $applicationInstance = Registry::getRegistry()->getInstance('app');
3248 // Is this a response instance?
3249 if ($this instanceof Responseable) {
3250 // Then set it in application instance
3251 $applicationInstance->setResponseInstance($this);
3254 // Init web output instance
3255 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3258 $this->setWebOutputInstance($outputInstance);
3262 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3264 * @param $boolean Boolean value
3265 * @return $translated Translated boolean value
3267 public static final function translateBooleanToYesNo ($boolean) {
3268 // Make sure it is really boolean
3269 assert(is_bool($boolean));
3272 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3274 // ... and return it
3279 * Encodes raw data (almost any type) by "serializing" it and then pack it
3280 * into a "binary format".
3282 * @param $rawData Raw data (almost any type)
3283 * @return $encoded Encoded data
3285 protected function encodeData ($rawData) {
3286 // Make sure no objects or resources pass through
3287 assert(!is_object($rawData));
3288 assert(!is_resource($rawData));
3290 // First "serialize" it (json_encode() is faster than serialize())
3291 $encoded = $this->packString(json_encode($rawData));
3298 * Pack a string into a "binary format". Please execuse me that this is
3299 * widely undocumented. :-(
3301 * @param $str Unpacked string
3302 * @return $packed Packed string
3303 * @todo Improve documentation
3305 protected function packString ($str) {
3307 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3309 // First compress the string (gzcompress is okay)
3310 $str = gzcompress($str);
3315 // And start the "encoding" loop
3316 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3318 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3319 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3321 if (($idx + $i) <= strlen($str)) {
3322 $ord = ord(substr($str, ($idx + $i), 1));
3324 $add = $ord * pow(256, $factor);
3328 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3332 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3333 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3335 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3336 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3342 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');
3347 * Checks whether the given file/path is in open_basedir(). This does not
3348 * gurantee that the file is actually readable and/or writeable. If you need
3349 * such gurantee then please use isReadableFile() instead.
3351 * @param $filePathName Name of the file/path to be checked
3352 * @return $isReachable Whether it is within open_basedir()
3354 protected static function isReachableFilePath ($filePathName) {
3355 // Is not reachable by default
3356 $isReachable = FALSE;
3358 // Get open_basedir parameter
3359 $openBaseDir = ini_get('open_basedir');
3362 if (!empty($openBaseDir)) {
3363 // Check all entries
3364 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3365 // Check on existence
3366 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3368 $isReachable = TRUE;
3372 // If open_basedir is not set, all is allowed
3373 $isReachable = TRUE;
3377 return $isReachable;
3381 * Checks whether the give file is within open_basedir() (done by
3382 * isReachableFilePath()), is actually a file and is readable.
3384 * @param $fileName Name of the file to be checked
3385 * @return $isReadable Whether the file is readable (and therefor exists)
3387 public static function isReadableFile ($fileName) {
3388 // Default is not readable
3389 $isReadable = FALSE;
3391 // Is within parameters, so check if it is a file and readable
3392 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3399 * Creates a full-qualified file name (FQFN) for given file name by adding
3400 * a configured temporary file path to it.
3402 * @param $fileName Name for temporary file
3403 * @return $fqfn Full-qualified file name
3404 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3405 * @throws FileIoException If the file cannot be written
3407 protected static function createTempPathForFile ($fileName) {
3409 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3411 // Is the path writeable?
3412 if (!is_writable($basePath)) {
3413 // Path is write-protected
3414 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3418 $fqfn = $basePath . '/' . $fileName;
3421 if (!self::isReachableFilePath($fqfn)) {
3423 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3431 * "Getter" for a printable state name
3433 * @return $stateName Name of the node's state in a printable format
3435 public final function getPrintableState () {
3436 // Default is 'null'
3437 $stateName = 'null';
3439 // Get the state instance
3440 $stateInstance = $this->getStateInstance();
3442 // Is it an instance of Stateable?
3443 if ($stateInstance instanceof Stateable) {
3444 // Then use that state name
3445 $stateName = $stateInstance->getStateName();
3453 * Handles socket error for given socket resource and peer data. This method
3454 * validates $socketResource if it is a valid resource (see is_resource())
3455 * but assumes valid data in array $recipientData, except that
3456 * count($recipientData) is always 2.
3458 * @param $method Value of __METHOD__ from calling method
3459 * @param $line Value of __LINE__ from calling method
3460 * @param $socketResource A valid socket resource
3461 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3463 * @throws InvalidSocketException If $socketResource is no socket resource
3464 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3465 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3467 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3468 // This method handles only socket resources
3469 if (!is_resource($socketResource)) {
3470 // No resource, abort here
3471 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3474 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3475 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3476 assert(isset($socketData[0]));
3477 assert(isset($socketData[1]));
3479 // Get error code for first validation (0 is not an error)
3480 $errorCode = socket_last_error($socketResource);
3482 // If the error code is zero, someone called this method without an error
3483 if ($errorCode == 0) {
3484 // No error detected (or previously cleared outside this method)
3485 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3488 // Get handler (method) name
3489 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3491 // Call-back the error handler method
3492 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3494 // Finally clear the error because it has been handled
3495 socket_clear_error($socketResource);