3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Factory\ObjectFactory;
8 use CoreFramework\Generic\FrameworkInterface;
9 use CoreFramework\Generic\NullPointerException;
10 use CoreFramework\Loader\ClassLoader;
11 use CoreFramework\Manager\ManageableApplication;
12 use CoreFramework\Middleware\Debug\DebugMiddleware;
13 use CoreFramework\Registry\Register;
14 use CoreFramework\Registry\Generic\Registry;
15 use CoreFramework\Stream\Output\OutputStreamer;
16 use CoreFramework\Template\CompileableTemplate;
22 * The simulator system class is the super class of all other classes. This
23 * class handles saving of games etc.
25 * @author Roland Haeder <webmaster@shipsimu.org>
27 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
28 * @license GNU GPL 3.0 or any newer version
29 * @link http://www.shipsimu.org
31 * This program is free software: you can redistribute it and/or modify
32 * it under the terms of the GNU General Public License as published by
33 * the Free Software Foundation, either version 3 of the License, or
34 * (at your option) any later version.
36 * This program is distributed in the hope that it will be useful,
37 * but WITHOUT ANY WARRANTY; without even the implied warranty of
38 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
39 * GNU General Public License for more details.
41 * You should have received a copy of the GNU General Public License
42 * along with this program. If not, see <http://www.gnu.org/licenses/>.
44 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
46 * Length of output from hash()
48 private static $hashLength = NULL;
53 private $realClass = 'BaseFrameworkSystem';
56 * Instance of a request class
58 private $requestInstance = NULL;
61 * Instance of a response class
63 private $responseInstance = NULL;
66 * Search criteria instance
68 private $searchInstance = NULL;
71 * Update criteria instance
73 private $updateInstance = NULL;
76 * The file I/O instance for the template loader
78 private $fileIoInstance = NULL;
83 private $resolverInstance = NULL;
86 * Template engine instance
88 private $templateInstance = NULL;
91 * Database result instance
93 private $resultInstance = NULL;
96 * Instance for user class
98 private $userInstance = NULL;
101 * A controller instance
103 private $controllerInstance = NULL;
108 private $rngInstance = NULL;
111 * Instance of a crypto helper
113 private $cryptoInstance = NULL;
116 * Instance of an Iterator class
118 private $iteratorInstance = NULL;
121 * Instance of the list
123 private $listInstance = NULL;
128 private $menuInstance = NULL;
131 * Instance of the image
133 private $imageInstance = NULL;
136 * Instance of the stacker
138 private $stackInstance = NULL;
141 * A Compressor instance
143 private $compressorInstance = NULL;
146 * A Parseable instance
148 private $parserInstance = NULL;
151 * A HandleableProtocol instance
153 private $protocolInstance = NULL;
156 * A database wrapper instance
158 private $databaseInstance = NULL;
161 * A helper instance for the form
163 private $helperInstance = NULL;
166 * An instance of a Source class
168 private $sourceInstance = NULL;
171 * An instance of a UrlSource class
173 private $urlSourceInstance = NULL;
176 * An instance of a InputStream class
178 private $inputStreamInstance = NULL;
181 * An instance of a OutputStream class
183 private $outputStreamInstance = NULL;
186 * Networkable handler instance
188 private $handlerInstance = NULL;
191 * Visitor handler instance
193 private $visitorInstance = NULL;
198 private $dhtInstance = NULL;
201 * An instance of a database wrapper class
203 private $wrapperInstance = NULL;
206 * An instance of a file I/O pointer class (not handler)
208 private $pointerInstance = NULL;
211 * An instance of an Indexable class
213 private $indexInstance = NULL;
216 * An instance of a Block class
218 private $blockInstance = NULL;
223 private $minableInstance = NULL;
226 * A FrameworkDirectory instance
228 private $directoryInstance = NULL;
233 private $listenerInstance = NULL;
236 * An instance of a communicator
238 private $communicatorInstance = NULL;
241 * The concrete output instance
243 private $outputInstance = NULL;
248 private $stateInstance = NULL;
251 * Thousands separator
253 private $thousands = '.'; // German
258 private $decimals = ','; // German
263 private $socketResource = FALSE;
266 * Regular expression to use for validation
268 private $regularExpression = '';
273 private $packageData = array();
278 private $genericArray = array();
283 private $commandName = '';
288 private $controllerName = '';
291 * Name of used protocol
293 private $protocolName = 'invalid';
296 * Array with bitmasks and such for pack/unpack methods to support both
297 * 32-bit and 64-bit systems
299 private $packingData = array(
302 'left' => 0xffff0000,
303 'right' => 0x0000ffff,
309 'left' => 0xffffffff00000000,
310 'right' => 0x00000000ffffffff,
317 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
319 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
321 private $archArrayElement = FALSE;
323 /***********************
324 * Exception codes.... *
325 ***********************/
327 // @todo Try to clean these constants up
328 const EXCEPTION_IS_NULL_POINTER = 0x001;
329 const EXCEPTION_IS_NO_OBJECT = 0x002;
330 const EXCEPTION_IS_NO_ARRAY = 0x003;
331 const EXCEPTION_MISSING_METHOD = 0x004;
332 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
333 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
334 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
335 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
336 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
337 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
338 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
339 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
340 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
341 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
342 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
343 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
344 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
345 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
346 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
347 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
348 const EXCEPTION_PATH_NOT_FOUND = 0x015;
349 const EXCEPTION_INVALID_PATH_NAME = 0x016;
350 const EXCEPTION_READ_PROTECED_PATH = 0x017;
351 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
352 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
353 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
354 const EXCEPTION_INVALID_RESOURCE = 0x01b;
355 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
356 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
357 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
358 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
359 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
360 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
361 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
362 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
363 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
364 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
365 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
366 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
367 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
368 const EXCEPTION_INVALID_STRING = 0x029;
369 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
370 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
371 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
372 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
373 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
374 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
375 const EXCEPTION_MISSING_ELEMENT = 0x030;
376 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
377 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
378 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
379 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
380 const EXCEPTION_FATAL_ERROR = 0x035;
381 const EXCEPTION_FILE_NOT_FOUND = 0x036;
382 const EXCEPTION_ASSERTION_FAILED = 0x037;
383 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
384 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
385 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
386 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
387 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
388 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
391 * Hexadecimal->Decimal translation array
393 private static $hexdec = array(
413 * Decimal->hexadecimal translation array
415 private static $dechex = array(
435 * Startup time in miliseconds
437 private static $startupTime = 0;
440 * Protected super constructor
442 * @param $className Name of the class
445 protected function __construct ($className) {
447 $this->setRealClass($className);
449 // Set configuration instance if no registry ...
450 if (!$this instanceof Register) {
451 // ... because registries doesn't need to be configured
452 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
455 // Is the startup time set? (0 cannot be TRUE anymore)
456 if (self::$startupTime == 0) {
458 self::$startupTime = microtime(TRUE);
462 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
466 * Destructor for all classes. You should not call this method on your own.
470 public function __destruct () {
471 // Flush any updated entries to the database
472 $this->flushPendingUpdates();
474 // Is this object already destroyed?
475 if ($this->__toString() != 'DestructedObject') {
476 // Destroy all informations about this class but keep some text about it alive
477 $this->setRealClass('DestructedObject');
478 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
479 // Already destructed object
480 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
485 // Do not call this twice
486 trigger_error(__METHOD__ . ': Called twice.');
492 * The __call() method where all non-implemented methods end up
494 * @param $methodName Name of the missing method
495 * @args $args Arguments passed to the method
498 public final function __call ($methodName, $args) {
499 return self::__callStatic($methodName, $args);
503 * The __callStatic() method where all non-implemented static methods end up
505 * @param $methodName Name of the missing method
506 * @args $args Arguments passed to the method
509 public static final function __callStatic ($methodName, $args) {
511 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
513 // Init argument string
516 // Is it NULL, empty or an array?
517 if (is_null($args)) {
519 $argsString = 'NULL';
520 } elseif (is_array($args)) {
524 // Some arguments are there
525 foreach ($args as $arg) {
526 // Add data about the argument
527 $argsString .= gettype($arg) . ':';
530 // Found a NULL argument
531 $argsString .= 'NULL';
532 } elseif (is_string($arg)) {
533 // Add length for strings
534 $argsString .= strlen($arg);
535 } elseif ((is_int($arg)) || (is_float($arg))) {
538 } elseif (is_array($arg)) {
539 // .. or size if array
540 $argsString .= count($arg);
541 } elseif (is_object($arg)) {
543 $reflection = new ReflectionClass($arg);
545 // Is an other object, maybe no __toString() available
546 $argsString .= $reflection->getName();
547 } elseif ($arg === TRUE) {
548 // ... is boolean 'TRUE'
549 $argsString .= 'TRUE';
550 } elseif ($arg === FALSE) {
551 // ... is boolean 'FALSE'
552 $argsString .= 'FALSE';
555 // Comma for next one
560 if (substr($argsString, -2, 1) == ',') {
561 $argsString = substr($argsString, 0, -2);
567 // Invalid arguments!
568 $argsString = '!INVALID:' . gettype($args) . '!';
571 // Output stub message
572 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
573 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
583 * Getter for $realClass
585 * @return $realClass The name of the real class (not BaseFrameworkSystem)
587 public function __toString () {
588 return $this->realClass;
592 * Magic method to catch setting of missing but set class fields/attributes
594 * @param $name Name of the field/attribute
595 * @param $value Value to store
598 public final function __set ($name, $value) {
599 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
602 print_r($value, TRUE)
607 * Magic method to catch getting of missing fields/attributes
609 * @param $name Name of the field/attribute
612 public final function __get ($name) {
613 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
619 * Magic method to catch unsetting of missing fields/attributes
621 * @param $name Name of the field/attribute
624 public final function __unset ($name) {
625 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
631 * Magic method to catch object serialization
633 * @return $unsupported Unsupported method
634 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
636 public final function __sleep () {
637 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
641 * Magic method to catch object deserialization
643 * @return $unsupported Unsupported method
644 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
646 public final function __wakeup () {
647 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
651 * Magic method to catch calls when an object instance is called
653 * @return $unsupported Unsupported method
654 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
656 public final function __invoke () {
657 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
661 * Setter for the real class name
663 * @param $realClass Class name (string)
666 public final function setRealClass ($realClass) {
668 $this->realClass = (string) $realClass;
672 * Setter for database result instance
674 * @param $resultInstance An instance of a database result class
676 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
678 protected final function setResultInstance (SearchableResult $resultInstance) {
679 $this->resultInstance = $resultInstance;
683 * Getter for database result instance
685 * @return $resultInstance An instance of a database result class
687 public final function getResultInstance () {
688 return $this->resultInstance;
692 * Setter for template engine instances
694 * @param $templateInstance An instance of a template engine class
697 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
698 $this->templateInstance = $templateInstance;
702 * Getter for template engine instances
704 * @return $templateInstance An instance of a template engine class
706 protected final function getTemplateInstance () {
707 return $this->templateInstance;
711 * Setter for search instance
713 * @param $searchInstance Searchable criteria instance
716 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
717 $this->searchInstance = $searchInstance;
721 * Getter for search instance
723 * @return $searchInstance Searchable criteria instance
725 public final function getSearchInstance () {
726 return $this->searchInstance;
730 * Setter for update instance
732 * @param $updateInstance Searchable criteria instance
735 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
736 $this->updateInstance = $updateInstance;
740 * Getter for update instance
742 * @return $updateInstance Updateable criteria instance
744 public final function getUpdateInstance () {
745 return $this->updateInstance;
749 * Setter for resolver instance
751 * @param $resolverInstance Instance of a command resolver class
754 public final function setResolverInstance (Resolver $resolverInstance) {
755 $this->resolverInstance = $resolverInstance;
759 * Getter for resolver instance
761 * @return $resolverInstance Instance of a command resolver class
763 public final function getResolverInstance () {
764 return $this->resolverInstance;
768 * Setter for language instance
770 * @param $configInstance The configuration instance which shall
771 * be FrameworkConfiguration
774 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
775 Registry::getRegistry()->addInstance('config', $configInstance);
779 * Getter for configuration instance
781 * @return $configInstance Configuration instance
783 public final function getConfigInstance () {
784 $configInstance = Registry::getRegistry()->getInstance('config');
785 return $configInstance;
789 * Setter for debug instance
791 * @param $debugInstance The instance for debug output class
794 public final function setDebugInstance (DebugMiddleware $debugInstance) {
795 Registry::getRegistry()->addInstance('debug', $debugInstance);
799 * Getter for debug instance
801 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
803 public final function getDebugInstance () {
804 // Get debug instance
805 $debugInstance = Registry::getRegistry()->getInstance('debug');
808 return $debugInstance;
812 * Setter for web output instance
814 * @param $webInstance The instance for web output class
817 public final function setWebOutputInstance (OutputStreamer $webInstance) {
818 Registry::getRegistry()->addInstance('web_output', $webInstance);
822 * Getter for web output instance
824 * @return $webOutputInstance - Instance to class WebOutput
826 public final function getWebOutputInstance () {
827 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
828 return $webOutputInstance;
832 * Setter for database instance
834 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
837 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
838 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
842 * Getter for database layer
844 * @return $databaseInstance The database layer instance
846 public final function getDatabaseInstance () {
848 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
851 return $databaseInstance;
855 * Setter for compressor channel
857 * @param $compressorInstance An instance of CompressorChannel
860 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
861 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
865 * Getter for compressor channel
867 * @return $compressorInstance The compressor channel
869 public final function getCompressorChannel () {
870 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
871 return $compressorInstance;
875 * Protected getter for a manageable application helper class
877 * @return $applicationInstance An instance of a manageable application helper class
879 protected final function getApplicationInstance () {
880 $applicationInstance = Registry::getRegistry()->getInstance('application');
881 return $applicationInstance;
885 * Setter for a manageable application helper class
887 * @param $applicationInstance An instance of a manageable application helper class
890 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
891 Registry::getRegistry()->addInstance('application', $applicationInstance);
895 * Setter for request instance
897 * @param $requestInstance An instance of a Requestable class
900 public final function setRequestInstance (Requestable $requestInstance) {
901 $this->requestInstance = $requestInstance;
905 * Getter for request instance
907 * @return $requestInstance An instance of a Requestable class
909 public final function getRequestInstance () {
910 return $this->requestInstance;
914 * Setter for response instance
916 * @param $responseInstance An instance of a Responseable class
919 public final function setResponseInstance (Responseable $responseInstance) {
920 $this->responseInstance = $responseInstance;
924 * Getter for response instance
926 * @return $responseInstance An instance of a Responseable class
928 public final function getResponseInstance () {
929 return $this->responseInstance;
933 * Private getter for language instance
935 * @return $langInstance An instance to the language sub-system
937 protected final function getLanguageInstance () {
938 $langInstance = Registry::getRegistry()->getInstance('language');
939 return $langInstance;
943 * Setter for language instance
945 * @param $langInstance An instance to the language sub-system
947 * @see LanguageSystem
949 public final function setLanguageInstance (ManageableLanguage $langInstance) {
950 Registry::getRegistry()->addInstance('language', $langInstance);
954 * Private getter for file IO instance
956 * @return $fileIoInstance An instance to the file I/O sub-system
958 protected final function getFileIoInstance () {
959 return $this->fileIoInstance;
963 * Setter for file I/O instance
965 * @param $fileIoInstance An instance to the file I/O sub-system
968 public final function setFileIoInstance (IoHandler $fileIoInstance) {
969 $this->fileIoInstance = $fileIoInstance;
973 * Protected setter for user instance
975 * @param $userInstance An instance of a user class
978 protected final function setUserInstance (ManageableAccount $userInstance) {
979 $this->userInstance = $userInstance;
983 * Getter for user instance
985 * @return $userInstance An instance of a user class
987 public final function getUserInstance () {
988 return $this->userInstance;
992 * Setter for controller instance (this surely breaks a bit the MVC patterm)
994 * @param $controllerInstance An instance of the controller
997 public final function setControllerInstance (Controller $controllerInstance) {
998 $this->controllerInstance = $controllerInstance;
1002 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1004 * @return $controllerInstance An instance of the controller
1006 public final function getControllerInstance () {
1007 return $this->controllerInstance;
1011 * Setter for RNG instance
1013 * @param $rngInstance An instance of a random number generator (RNG)
1016 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1017 $this->rngInstance = $rngInstance;
1021 * Getter for RNG instance
1023 * @return $rngInstance An instance of a random number generator (RNG)
1025 public final function getRngInstance () {
1026 return $this->rngInstance;
1030 * Setter for Cryptable instance
1032 * @param $cryptoInstance An instance of a Cryptable class
1035 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1036 $this->cryptoInstance = $cryptoInstance;
1040 * Getter for Cryptable instance
1042 * @return $cryptoInstance An instance of a Cryptable class
1044 public final function getCryptoInstance () {
1045 return $this->cryptoInstance;
1049 * Setter for the list instance
1051 * @param $listInstance A list of Listable
1054 protected final function setListInstance (Listable $listInstance) {
1055 $this->listInstance = $listInstance;
1059 * Getter for the list instance
1061 * @return $listInstance A list of Listable
1063 protected final function getListInstance () {
1064 return $this->listInstance;
1068 * Setter for the menu instance
1070 * @param $menuInstance A RenderableMenu instance
1073 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1074 $this->menuInstance = $menuInstance;
1078 * Getter for the menu instance
1080 * @return $menuInstance A RenderableMenu instance
1082 protected final function getMenuInstance () {
1083 return $this->menuInstance;
1087 * Setter for image instance
1089 * @param $imageInstance An instance of an image
1092 public final function setImageInstance (BaseImage $imageInstance) {
1093 $this->imageInstance = $imageInstance;
1097 * Getter for image instance
1099 * @return $imageInstance An instance of an image
1101 public final function getImageInstance () {
1102 return $this->imageInstance;
1106 * Setter for stacker instance
1108 * @param $stackInstance An instance of an stacker
1111 public final function setStackInstance (Stackable $stackInstance) {
1112 $this->stackInstance = $stackInstance;
1116 * Getter for stacker instance
1118 * @return $stackInstance An instance of an stacker
1120 public final function getStackInstance () {
1121 return $this->stackInstance;
1125 * Setter for compressor instance
1127 * @param $compressorInstance An instance of an compressor
1130 public final function setCompressorInstance (Compressor $compressorInstance) {
1131 $this->compressorInstance = $compressorInstance;
1135 * Getter for compressor instance
1137 * @return $compressorInstance An instance of an compressor
1139 public final function getCompressorInstance () {
1140 return $this->compressorInstance;
1144 * Setter for Parseable instance
1146 * @param $parserInstance An instance of an Parseable
1149 public final function setParserInstance (Parseable $parserInstance) {
1150 $this->parserInstance = $parserInstance;
1154 * Getter for Parseable instance
1156 * @return $parserInstance An instance of an Parseable
1158 public final function getParserInstance () {
1159 return $this->parserInstance;
1163 * Setter for HandleableProtocol instance
1165 * @param $protocolInstance An instance of an HandleableProtocol
1168 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1169 $this->protocolInstance = $protocolInstance;
1173 * Getter for HandleableProtocol instance
1175 * @return $protocolInstance An instance of an HandleableProtocol
1177 public final function getProtocolInstance () {
1178 return $this->protocolInstance;
1182 * Setter for DatabaseWrapper instance
1184 * @param $wrapperInstance An instance of an DatabaseWrapper
1187 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1188 $this->wrapperInstance = $wrapperInstance;
1192 * Getter for DatabaseWrapper instance
1194 * @return $wrapperInstance An instance of an DatabaseWrapper
1196 public final function getWrapperInstance () {
1197 return $this->wrapperInstance;
1201 * Setter for socket resource
1203 * @param $socketResource A valid socket resource
1206 public final function setSocketResource ($socketResource) {
1207 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1208 $this->socketResource = $socketResource;
1212 * Getter for socket resource
1214 * @return $socketResource A valid socket resource
1216 public final function getSocketResource () {
1217 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1218 return $this->socketResource;
1222 * Setter for regular expression
1224 * @param $regularExpression A valid regular expression
1227 public final function setRegularExpression ($regularExpression) {
1228 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1229 $this->regularExpression = $regularExpression;
1233 * Getter for regular expression
1235 * @return $regularExpression A valid regular expression
1237 public final function getRegularExpression () {
1238 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1239 return $this->regularExpression;
1243 * Setter for helper instance
1245 * @param $helperInstance An instance of a helper class
1248 protected final function setHelperInstance (Helper $helperInstance) {
1249 $this->helperInstance = $helperInstance;
1253 * Getter for helper instance
1255 * @return $helperInstance An instance of a helper class
1257 public final function getHelperInstance () {
1258 return $this->helperInstance;
1262 * Setter for a Source instance
1264 * @param $sourceInstance An instance of a Source class
1267 protected final function setSourceInstance (Source $sourceInstance) {
1268 $this->sourceInstance = $sourceInstance;
1272 * Getter for a Source instance
1274 * @return $sourceInstance An instance of a Source class
1276 protected final function getSourceInstance () {
1277 return $this->sourceInstance;
1281 * Setter for a UrlSource instance
1283 * @param $sourceInstance An instance of a UrlSource class
1286 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1287 $this->urlSourceInstance = $urlSourceInstance;
1291 * Getter for a UrlSource instance
1293 * @return $urlSourceInstance An instance of a UrlSource class
1295 protected final function getUrlSourceInstance () {
1296 return $this->urlSourceInstance;
1300 * Getter for a InputStream instance
1302 * @param $inputStreamInstance The InputStream instance
1304 protected final function getInputStreamInstance () {
1305 return $this->inputStreamInstance;
1309 * Setter for a InputStream instance
1311 * @param $inputStreamInstance The InputStream instance
1314 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1315 $this->inputStreamInstance = $inputStreamInstance;
1319 * Getter for a OutputStream instance
1321 * @param $outputStreamInstance The OutputStream instance
1323 protected final function getOutputStreamInstance () {
1324 return $this->outputStreamInstance;
1328 * Setter for a OutputStream instance
1330 * @param $outputStreamInstance The OutputStream instance
1333 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1334 $this->outputStreamInstance = $outputStreamInstance;
1338 * Setter for handler instance
1340 * @param $handlerInstance An instance of a Handleable class
1343 protected final function setHandlerInstance (Handleable $handlerInstance) {
1344 $this->handlerInstance = $handlerInstance;
1348 * Getter for handler instance
1350 * @return $handlerInstance A Networkable instance
1352 protected final function getHandlerInstance () {
1353 return $this->handlerInstance;
1357 * Setter for visitor instance
1359 * @param $visitorInstance A Visitor instance
1362 protected final function setVisitorInstance (Visitor $visitorInstance) {
1363 $this->visitorInstance = $visitorInstance;
1367 * Getter for visitor instance
1369 * @return $visitorInstance A Visitor instance
1371 protected final function getVisitorInstance () {
1372 return $this->visitorInstance;
1376 * Setter for DHT instance
1378 * @param $dhtInstance A Distributable instance
1381 protected final function setDhtInstance (Distributable $dhtInstance) {
1382 $this->dhtInstance = $dhtInstance;
1386 * Getter for DHT instance
1388 * @return $dhtInstance A Distributable instance
1390 protected final function getDhtInstance () {
1391 return $this->dhtInstance;
1395 * Setter for raw package Data
1397 * @param $packageData Raw package Data
1400 public final function setPackageData (array $packageData) {
1401 $this->packageData = $packageData;
1405 * Getter for raw package Data
1407 * @return $packageData Raw package Data
1409 public function getPackageData () {
1410 return $this->packageData;
1415 * Setter for Iterator instance
1417 * @param $iteratorInstance An instance of an Iterator
1420 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1421 $this->iteratorInstance = $iteratorInstance;
1425 * Getter for Iterator instance
1427 * @return $iteratorInstance An instance of an Iterator
1429 public final function getIteratorInstance () {
1430 return $this->iteratorInstance;
1434 * Setter for FilePointer instance
1436 * @param $pointerInstance An instance of an FilePointer class
1439 protected final function setPointerInstance (FilePointer $pointerInstance) {
1440 $this->pointerInstance = $pointerInstance;
1444 * Getter for FilePointer instance
1446 * @return $pointerInstance An instance of an FilePointer class
1448 public final function getPointerInstance () {
1449 return $this->pointerInstance;
1453 * Unsets pointer instance which triggers a call of __destruct() if the
1454 * instance is still there. This is surely not fatal on already "closed"
1455 * file pointer instances.
1457 * I don't want to mess around with above setter by giving it a default
1458 * value NULL as setter should always explicitly only set (existing) object
1459 * instances and NULL is NULL.
1463 protected final function unsetPointerInstance () {
1464 // Simply it to NULL
1465 $this->pointerInstance = NULL;
1469 * Setter for Indexable instance
1471 * @param $indexInstance An instance of an Indexable class
1474 protected final function setIndexInstance (Indexable $indexInstance) {
1475 $this->indexInstance = $indexInstance;
1479 * Getter for Indexable instance
1481 * @return $indexInstance An instance of an Indexable class
1483 public final function getIndexInstance () {
1484 return $this->indexInstance;
1488 * Setter for Block instance
1490 * @param $blockInstance An instance of an Block class
1493 protected final function setBlockInstance (Block $blockInstance) {
1494 $this->blockInstance = $blockInstance;
1498 * Getter for Block instance
1500 * @return $blockInstance An instance of an Block class
1502 public final function getBlockInstance () {
1503 return $this->blockInstance;
1507 * Setter for Minable instance
1509 * @param $minableInstance A Minable instance
1512 protected final function setMinableInstance (Minable $minableInstance) {
1513 $this->minableInstance = $minableInstance;
1517 * Getter for minable instance
1519 * @return $minableInstance A Minable instance
1521 protected final function getMinableInstance () {
1522 return $this->minableInstance;
1526 * Setter for FrameworkDirectory instance
1528 * @param $directoryInstance A FrameworkDirectoryPointer instance
1531 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1532 $this->directoryInstance = $directoryInstance;
1536 * Getter for FrameworkDirectory instance
1538 * @return $directoryInstance A FrameworkDirectory instance
1540 protected final function getDirectoryInstance () {
1541 return $this->directoryInstance;
1545 * Setter for listener instance
1547 * @param $listenerInstance A Listenable instance
1550 protected final function setListenerInstance (Listenable $listenerInstance) {
1551 $this->listenerInstance = $listenerInstance;
1555 * Getter for listener instance
1557 * @return $listenerInstance A Listenable instance
1559 protected final function getListenerInstance () {
1560 return $this->listenerInstance;
1564 * Getter for communicator instance
1566 * @return $communicatorInstance An instance of a Communicator class
1568 public final function getCommunicatorInstance () {
1569 return $this->communicatorInstance;
1573 * Setter for communicator instance
1575 * @param $communicatorInstance An instance of a Communicator class
1578 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1579 $this->communicatorInstance = $communicatorInstance;
1583 * Setter for state instance
1585 * @param $stateInstance A Stateable instance
1588 public final function setStateInstance (Stateable $stateInstance) {
1589 $this->stateInstance = $stateInstance;
1593 * Getter for state instance
1595 * @return $stateInstance A Stateable instance
1597 public final function getStateInstance () {
1598 return $this->stateInstance;
1602 * Setter for output instance
1604 * @param $outputInstance The debug output instance
1607 public final function setOutputInstance (OutputStreamer $outputInstance) {
1608 $this->outputInstance = $outputInstance;
1612 * Getter for output instance
1614 * @return $outputInstance The debug output instance
1616 public final function getOutputInstance () {
1617 return $this->outputInstance;
1621 * Setter for command name
1623 * @param $commandName Last validated command name
1626 protected final function setCommandName ($commandName) {
1627 $this->commandName = $commandName;
1631 * Getter for command name
1633 * @return $commandName Last validated command name
1635 protected final function getCommandName () {
1636 return $this->commandName;
1640 * Setter for controller name
1642 * @param $controllerName Last validated controller name
1645 protected final function setControllerName ($controllerName) {
1646 $this->controllerName = $controllerName;
1650 * Getter for controller name
1652 * @return $controllerName Last validated controller name
1654 protected final function getControllerName () {
1655 return $this->controllerName;
1659 * Getter for protocol name
1661 * @return $protocolName Name of used protocol
1663 public final function getProtocolName () {
1664 return $this->protocolName;
1668 * Setter for protocol name
1670 * @param $protocolName Name of used protocol
1673 protected final function setProtocolName ($protocolName) {
1674 $this->protocolName = $protocolName;
1678 * Checks whether an object equals this object. You should overwrite this
1679 * method to implement own equality checks
1681 * @param $objectInstance An instance of a FrameworkInterface object
1682 * @return $equals Whether both objects equals
1684 public function equals (FrameworkInterface $objectInstance) {
1687 $this->__toString() == $objectInstance->__toString()
1689 $this->hashCode() == $objectInstance->hashCode()
1692 // Return the result
1697 * Generates a generic hash code of this class. You should really overwrite
1698 * this method with your own hash code generator code. But keep KISS in mind.
1700 * @return $hashCode A generic hash code respresenting this whole class
1702 public function hashCode () {
1704 return crc32($this->__toString());
1708 * Formats computer generated price values into human-understandable formats
1709 * with thousand and decimal separators.
1711 * @param $value The in computer format value for a price
1712 * @param $currency The currency symbol (use HTML-valid characters!)
1713 * @param $decNum Number of decimals after commata
1714 * @return $price The for the current language formated price string
1715 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1716 * thousands separator
1719 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1720 // Are all required attriutes set?
1721 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1722 // Throw an exception
1723 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1727 $value = (float) $value;
1729 // Reformat the US number
1730 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1732 // Return as string...
1737 * Appends a trailing slash to a string
1739 * @param $str A string (maybe) without trailing slash
1740 * @return $str A string with an auto-appended trailing slash
1742 public final function addMissingTrailingSlash ($str) {
1743 // Is there a trailing slash?
1744 if (substr($str, -1, 1) != '/') {
1748 // Return string with trailing slash
1753 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1754 * application helper instance (ApplicationHelper by default).
1756 * @param $applicationInstance An application helper instance or
1757 * null if we shall use the default
1758 * @return $templateInstance The template engine instance
1759 * @throws NullPointerException If the discovered application
1760 * instance is still null
1762 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1763 // Is the application instance set?
1764 if (is_null($applicationInstance)) {
1765 // Get the current instance
1766 $applicationInstance = $this->getApplicationInstance();
1769 if (is_null($applicationInstance)) {
1770 // Thrown an exception
1771 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1775 // Initialize the template engine
1776 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1778 // Return the prepared instance
1779 return $templateInstance;
1783 * Debugs this instance by putting out it's full content
1785 * @param $message Optional message to show in debug output
1788 public final function debugInstance ($message = '') {
1789 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1790 restore_error_handler();
1795 // Is a message set?
1796 if (!empty($message)) {
1797 // Construct message
1798 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1801 // Generate the output
1802 $content .= sprintf('<pre>%s</pre>',
1805 print_r($this, TRUE)
1811 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>',
1812 $this->__toString(),
1814 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1819 * Replaces control characters with printable output
1821 * @param $str String with control characters
1822 * @return $str Replaced string
1824 protected function replaceControlCharacters ($str) {
1827 chr(13), '[r]', str_replace(
1828 chr(10), '[n]', str_replace(
1838 * Output a partial stub message for the caller method
1840 * @param $message An optional message to display
1843 protected function partialStub ($message = '') {
1844 // Get the backtrace
1845 $backtrace = debug_backtrace();
1847 // Generate the class::method string
1848 $methodName = 'UnknownClass->unknownMethod';
1849 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1850 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1853 // Construct the full message
1854 $stubMessage = sprintf('[%s:] Partial stub!',
1858 // Is the extra message given?
1859 if (!empty($message)) {
1860 // Then add it as well
1861 $stubMessage .= ' Message: ' . $message;
1864 // Debug instance is there?
1865 if (!is_null($this->getDebugInstance())) {
1866 // Output stub message
1867 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1870 trigger_error($stubMessage);
1876 * Outputs a debug backtrace and stops further script execution
1878 * @param $message An optional message to output
1879 * @param $doExit Whether exit the program (TRUE is default)
1882 public function debugBackTrace ($message = '', $doExit = TRUE) {
1883 // Sorry, there is no other way getting this nice backtrace
1884 if (!empty($message)) {
1886 printf('Message: %s<br />' . PHP_EOL, $message);
1890 debug_print_backtrace();
1894 if ($doExit === TRUE) {
1900 * Creates an instance of a debugger instance
1902 * @param $className Name of the class (currently unsupported)
1903 * @param $lineNumber Line number where the call was made
1904 * @return $debugInstance An instance of a debugger class
1905 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1907 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1908 // Is the instance set?
1909 if (!Registry::getRegistry()->instanceExists('debug')) {
1910 // Init debug instance
1911 $debugInstance = NULL;
1915 // Get a debugger instance
1916 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1917 } catch (NullPointerException $e) {
1918 // Didn't work, no instance there
1919 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1922 // Empty string should be ignored and used for testing the middleware
1923 DebugMiddleware::getSelfInstance()->output('');
1925 // Set it in its own class. This will set it in the registry
1926 $debugInstance->setDebugInstance($debugInstance);
1928 // Get instance from registry
1929 $debugInstance = Registry::getRegistry()->getDebugInstance();
1933 return $debugInstance;
1937 * Simple output of a message with line-break
1939 * @param $message Message to output
1942 public function outputLine ($message) {
1944 print($message . PHP_EOL);
1948 * Outputs a debug message whether to debug instance (should be set!) or
1949 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1950 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1952 * @param $message Message we shall send out...
1953 * @param $doPrint Whether print or die here (default: print)
1954 * @paran $stripTags Whether to strip tags (default: FALSE)
1957 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1958 // Set debug instance to NULL
1959 $debugInstance = NULL;
1963 // Get debug instance
1964 $debugInstance = $this->getDebugInstance();
1965 } catch (NullPointerException $e) {
1966 // The debug instance is not set (yet)
1969 // Is the debug instance there?
1970 if (is_object($debugInstance)) {
1971 // Use debug output handler
1972 $debugInstance->output($message, $stripTags);
1974 if ($doPrint === FALSE) {
1975 // Die here if not printed
1979 // Are debug times enabled?
1980 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1982 $message = $this->getPrintableExecutionTime() . $message;
1986 if ($doPrint === TRUE) {
1988 $this->outputLine($message);
1997 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1999 * @param $str The string, what ever it is needs to be converted
2000 * @return $className Generated class name
2002 public static final function convertToClassName ($str) {
2006 // Convert all dashes in underscores
2007 $str = self::convertDashesToUnderscores($str);
2009 // Now use that underscores to get classname parts for hungarian style
2010 foreach (explode('_', $str) as $strPart) {
2011 // Make the class name part lower case and first upper case
2012 $className .= ucfirst(strtolower($strPart));
2015 // Return class name
2020 * Converts dashes to underscores, e.g. useable for configuration entries
2022 * @param $str The string with maybe dashes inside
2023 * @return $str The converted string with no dashed, but underscores
2025 public static final function convertDashesToUnderscores ($str) {
2027 $str = str_replace('-', '_', $str);
2029 // Return converted string
2034 * Marks up the code by adding e.g. line numbers
2036 * @param $phpCode Unmarked PHP code
2037 * @return $markedCode Marked PHP code
2039 public function markupCode ($phpCode) {
2044 $errorArray = error_get_last();
2046 // Init the code with error message
2047 if (is_array($errorArray)) {
2049 $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>',
2050 basename($errorArray['file']),
2051 $errorArray['line'],
2052 $errorArray['message'],
2057 // Add line number to the code
2058 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2060 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2062 htmlentities($code, ENT_QUOTES)
2071 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2072 * beatiful for web-based front-ends. If null is given a message id
2073 * null_timestamp will be resolved and returned.
2075 * @param $timestamp Timestamp to prepare (filter) for display
2076 * @return $readable A readable timestamp
2078 public function doFilterFormatTimestamp ($timestamp) {
2079 // Default value to return
2082 // Is the timestamp null?
2083 if (is_null($timestamp)) {
2084 // Get a message string
2085 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2087 switch ($this->getLanguageInstance()->getLanguageCode()) {
2088 case 'de': // German format is a bit different to default
2089 // Split the GMT stamp up
2090 $dateTime = explode(' ', $timestamp );
2091 $dateArray = explode('-', $dateTime[0]);
2092 $timeArray = explode(':', $dateTime[1]);
2094 // Construct the timestamp
2095 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2105 default: // Default is pass-through
2106 $readable = $timestamp;
2116 * Filter a given number into a localized number
2118 * @param $value The raw value from e.g. database
2119 * @return $localized Localized value
2121 public function doFilterFormatNumber ($value) {
2122 // Generate it from config and localize dependencies
2123 switch ($this->getLanguageInstance()->getLanguageCode()) {
2124 case 'de': // German format is a bit different to default
2125 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2128 default: // US, etc.
2129 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2138 * "Getter" for databse entry
2140 * @return $entry An array with database entries
2141 * @throws NullPointerException If the database result is not found
2142 * @throws InvalidDatabaseResultException If the database result is invalid
2144 protected final function getDatabaseEntry () {
2145 // Is there an instance?
2146 if (!$this->getResultInstance() instanceof SearchableResult) {
2147 // Throw an exception here
2148 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2152 $this->getResultInstance()->rewind();
2154 // Do we have an entry?
2155 if ($this->getResultInstance()->valid() === FALSE) {
2156 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2157 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2161 $this->getResultInstance()->next();
2164 $entry = $this->getResultInstance()->current();
2171 * Getter for field name
2173 * @param $fieldName Field name which we shall get
2174 * @return $fieldValue Field value from the user
2175 * @throws NullPointerException If the result instance is null
2177 public final function getField ($fieldName) {
2178 // Default field value
2181 // Get result instance
2182 $resultInstance = $this->getResultInstance();
2184 // Is this instance null?
2185 if (is_null($resultInstance)) {
2186 // Then the user instance is no longer valid (expired cookies?)
2187 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2190 // Get current array
2191 $fieldArray = $resultInstance->current();
2192 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2194 // Convert dashes to underscore
2195 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2197 // Does the field exist?
2198 if ($this->isFieldSet($fieldName)) {
2200 $fieldValue = $fieldArray[$fieldName2];
2201 } elseif (defined('DEVELOPER')) {
2202 // Missing field entry, may require debugging
2203 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2205 // Missing field entry, may require debugging
2206 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2214 * Checks if given field is set
2216 * @param $fieldName Field name to check
2217 * @return $isSet Whether the given field name is set
2218 * @throws NullPointerException If the result instance is null
2220 public function isFieldSet ($fieldName) {
2221 // Get result instance
2222 $resultInstance = $this->getResultInstance();
2224 // Is this instance null?
2225 if (is_null($resultInstance)) {
2226 // Then the user instance is no longer valid (expired cookies?)
2227 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2230 // Get current array
2231 $fieldArray = $resultInstance->current();
2232 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2234 // Convert dashes to underscore
2235 $fieldName = self::convertDashesToUnderscores($fieldName);
2238 $isSet = isset($fieldArray[$fieldName]);
2245 * Flushs all pending updates to the database layer
2249 public function flushPendingUpdates () {
2250 // Get result instance
2251 $resultInstance = $this->getResultInstance();
2253 // Do we have data to update?
2254 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2255 // Get wrapper class name config entry
2256 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2258 // Create object instance
2259 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2261 // Yes, then send the whole result to the database layer
2262 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2267 * Outputs a deprecation warning to the developer.
2269 * @param $message The message we shall output to the developer
2271 * @todo Write a logging mechanism for productive mode
2273 public function deprecationWarning ($message) {
2274 // Is developer mode active?
2275 if (defined('DEVELOPER')) {
2276 // Debug instance is there?
2277 if (!is_null($this->getDebugInstance())) {
2278 // Output stub message
2279 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2282 trigger_error($message . "<br />\n");
2286 // @TODO Finish this part!
2287 $this->partialStub('Developer mode inactive. Message:' . $message);
2292 * Checks whether the given PHP extension is loaded
2294 * @param $phpExtension The PHP extension we shall check
2295 * @return $isLoaded Whether the PHP extension is loaded
2297 public final function isPhpExtensionLoaded ($phpExtension) {
2299 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2306 * "Getter" as a time() replacement but with milliseconds. You should use this
2307 * method instead of the encapsulated getimeofday() function.
2309 * @return $milliTime Timestamp with milliseconds
2311 public function getMilliTime () {
2312 // Get the time of day as float
2313 $milliTime = gettimeofday(TRUE);
2320 * Idles (sleeps) for given milliseconds
2322 * @return $hasSlept Whether it goes fine
2324 public function idle ($milliSeconds) {
2325 // Sleep is fine by default
2328 // Idle so long with found function
2329 if (function_exists('time_sleep_until')) {
2330 // Get current time and add idle time
2331 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2333 // New PHP 5.1.0 function found, ignore errors
2334 $hasSlept = @time_sleep_until($sleepUntil);
2337 * My Sun station doesn't have that function even with latest PHP
2340 usleep($milliSeconds * 1000);
2347 * Converts a hexadecimal string, even with negative sign as first string to
2348 * a decimal number using BC functions.
2350 * This work is based on comment #86673 on php.net documentation page at:
2351 * <http://de.php.net/manual/en/function.dechex.php#86673>
2353 * @param $hex Hexadecimal string
2354 * @return $dec Decimal number
2356 protected function hex2dec ($hex) {
2357 // Convert to all lower-case
2358 $hex = strtolower($hex);
2360 // Detect sign (negative/positive numbers)
2362 if (substr($hex, 0, 1) == '-') {
2364 $hex = substr($hex, 1);
2367 // Decode the hexadecimal string into a decimal number
2369 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2370 $factor = self::$hexdec[substr($hex, $i, 1)];
2371 $dec = bcadd($dec, bcmul($factor, $e));
2374 // Return the decimal number
2375 return $sign . $dec;
2379 * Converts even very large decimal numbers, also signed, to a hexadecimal
2382 * This work is based on comment #97756 on php.net documentation page at:
2383 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2385 * @param $dec Decimal number, even with negative sign
2386 * @param $maxLength Optional maximum length of the string
2387 * @return $hex Hexadecimal string
2389 protected function dec2hex ($dec, $maxLength = 0) {
2390 // maxLength can be zero or devideable by 2
2391 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2393 // Detect sign (negative/positive numbers)
2400 // Encode the decimal number into a hexadecimal string
2403 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2405 } while ($dec >= 1);
2408 * Leading zeros are required for hex-decimal "numbers". In some
2409 * situations more leading zeros are wanted, so check for both
2412 if ($maxLength > 0) {
2413 // Prepend more zeros
2414 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2415 } elseif ((strlen($hex) % 2) != 0) {
2416 // Only make string's length dividable by 2
2420 // Return the hexadecimal string
2421 return $sign . $hex;
2425 * Converts a ASCII string (0 to 255) into a decimal number.
2427 * @param $asc The ASCII string to be converted
2428 * @return $dec Decimal number
2430 protected function asc2dec ($asc) {
2431 // Convert it into a hexadecimal number
2432 $hex = bin2hex($asc);
2434 // And back into a decimal number
2435 $dec = $this->hex2dec($hex);
2442 * Converts a decimal number into an ASCII string.
2444 * @param $dec Decimal number
2445 * @return $asc An ASCII string
2447 protected function dec2asc ($dec) {
2448 // First convert the number into a hexadecimal string
2449 $hex = $this->dec2hex($dec);
2451 // Then convert it into the ASCII string
2452 $asc = $this->hex2asc($hex);
2459 * Converts a hexadecimal number into an ASCII string. Negative numbers
2462 * @param $hex Hexadecimal string
2463 * @return $asc An ASCII string
2465 protected function hex2asc ($hex) {
2466 // Check for length, it must be devideable by 2
2467 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2468 assert((strlen($hex) % 2) == 0);
2472 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2473 // Get the decimal number of the chunk
2474 $part = hexdec(substr($hex, $idx, 2));
2476 // Add it to the final string
2480 // Return the final string
2485 * Checks whether the given encoded data was encoded with Base64
2487 * @param $encodedData Encoded data we shall check
2488 * @return $isBase64 Whether the encoded data is Base64
2490 protected function isBase64Encoded ($encodedData) {
2492 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2499 * "Getter" to get response/request type from analysis of the system.
2501 * @return $responseType Analyzed response type
2503 protected static function getResponseTypeFromSystem () {
2504 // Default is console
2505 $responseType = 'console';
2507 // Is 'HTTP_HOST' set?
2508 if (isset($_SERVER['HTTP_HOST'])) {
2510 * Then it is a HTML response/request as RSS and so on may be
2511 * transfered over HTTP as well.
2513 $responseType = 'html';
2517 return $responseType;
2521 * Gets a cache key from Criteria instance
2523 * @param $criteriaInstance An instance of a Criteria class
2524 * @param $onlyKeys Only use these keys for a cache key
2525 * @return $cacheKey A cache key suitable for lookup/storage purposes
2527 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2529 $cacheKey = sprintf('%s@%s',
2530 $this->__toString(),
2531 $criteriaInstance->getCacheKey($onlyKeys)
2535 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2540 * Getter for startup time in miliseconds
2542 * @return $startupTime Startup time in miliseconds
2544 protected function getStartupTime () {
2545 return self::$startupTime;
2549 * "Getter" for a printable currently execution time in nice braces
2551 * @return $executionTime Current execution time in nice braces
2553 protected function getPrintableExecutionTime () {
2554 // Caculate the execution time
2555 $executionTime = microtime(TRUE) - $this->getStartupTime();
2557 // Pack it in nice braces
2558 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2561 return $executionTime;
2565 * Hashes a given string with a simple but stronger hash function (no salt)
2566 * and hex-encode it.
2568 * @param $str The string to be hashed
2569 * @return $hash The hash from string $str
2571 public static final function hash ($str) {
2572 // Hash given string with (better secure) hasher
2573 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2580 * "Getter" for length of hash() output. This will be "cached" to speed up
2583 * @return $length Length of hash() output
2585 public static final function getHashLength () {
2587 if (is_null(self::$hashLength)) {
2588 // No, then hash a string and save its length.
2589 self::$hashLength = strlen(self::hash('abc123'));
2593 return self::$hashLength;
2597 * Checks whether the given number is really a number (only chars 0-9).
2599 * @param $num A string consisting only chars between 0 and 9
2600 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2601 * @param $assertMismatch Whether to assert mismatches
2602 * @return $ret The (hopefully) secured numbered value
2604 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2605 // Filter all numbers out
2606 $ret = preg_replace('/[^0123456789]/', '', $num);
2609 if ($castValue === TRUE) {
2610 // Cast to biggest numeric type
2611 $ret = (double) $ret;
2614 // Assert only if requested
2615 if ($assertMismatch === TRUE) {
2616 // Has the whole value changed?
2617 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2625 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2627 * @param $num A string consisting only chars between 0 and 9
2628 * @param $assertMismatch Whether to assert mismatches
2629 * @return $ret The (hopefully) secured hext-numbered value
2631 public function hexval ($num, $assertMismatch = FALSE) {
2632 // Filter all numbers out
2633 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2635 // Assert only if requested
2636 if ($assertMismatch === TRUE) {
2637 // Has the whole value changed?
2638 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2646 * Checks whether start/end marker are set
2648 * @param $data Data to be checked
2649 * @return $isset Whether start/end marker are set
2651 public final function ifStartEndMarkersSet ($data) {
2653 $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));
2655 // ... and return it
2660 * Determines if an element is set in the generic array
2662 * @param $keyGroup Main group for the key
2663 * @param $subGroup Sub group for the key
2664 * @param $key Key to check
2665 * @param $element Element to check
2666 * @return $isset Whether the given key is set
2668 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2670 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2673 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2679 * Determines if a key is set in the generic array
2681 * @param $keyGroup Main group for the key
2682 * @param $subGroup Sub group for the key
2683 * @param $key Key to check
2684 * @return $isset Whether the given key is set
2686 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2688 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2691 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2699 * Determines if a group is set in the generic array
2701 * @param $keyGroup Main group
2702 * @param $subGroup Sub group
2703 * @return $isset Whether the given group is set
2705 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2707 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2710 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2717 * Getter for sub key group
2719 * @param $keyGroup Main key group
2720 * @param $subGroup Sub key group
2721 * @return $array An array with all array elements
2723 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2725 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2726 // No, then abort here
2727 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2732 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2735 return $this->genericArray[$keyGroup][$subGroup];
2739 * Unsets a given key in generic array
2741 * @param $keyGroup Main group for the key
2742 * @param $subGroup Sub group for the key
2743 * @param $key Key to unset
2746 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2748 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2751 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2755 * Unsets a given element in generic array
2757 * @param $keyGroup Main group for the key
2758 * @param $subGroup Sub group for the key
2759 * @param $key Key to unset
2760 * @param $element Element to unset
2763 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2765 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2768 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2772 * Append a string to a given generic array key
2774 * @param $keyGroup Main group for the key
2775 * @param $subGroup Sub group for the key
2776 * @param $key Key to unset
2777 * @param $value Value to add/append
2780 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2782 //* 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);
2784 // Is it already there?
2785 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2787 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2790 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2795 * Append a string to a given generic array element
2797 * @param $keyGroup Main group for the key
2798 * @param $subGroup Sub group for the key
2799 * @param $key Key to unset
2800 * @param $element Element to check
2801 * @param $value Value to add/append
2804 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2806 //* 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);
2808 // Is it already there?
2809 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2811 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2814 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2819 * Sets a string in a given generic array element
2821 * @param $keyGroup Main group for the key
2822 * @param $subGroup Sub group for the key
2823 * @param $key Key to unset
2824 * @param $element Element to check
2825 * @param $value Value to add/append
2828 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2830 //* 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);
2833 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2837 * Initializes given generic array group
2839 * @param $keyGroup Main group for the key
2840 * @param $subGroup Sub group for the key
2841 * @param $key Key to use
2842 * @param $forceInit Optionally force initialization
2845 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2847 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2849 // Is it already set?
2850 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2851 // Already initialized
2852 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2857 $this->genericArray[$keyGroup][$subGroup] = array();
2861 * Initializes given generic array key
2863 * @param $keyGroup Main group for the key
2864 * @param $subGroup Sub group for the key
2865 * @param $key Key to use
2866 * @param $forceInit Optionally force initialization
2869 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2871 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2873 // Is it already set?
2874 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2875 // Already initialized
2876 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2881 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2885 * Initializes given generic array element
2887 * @param $keyGroup Main group for the key
2888 * @param $subGroup Sub group for the key
2889 * @param $key Key to use
2890 * @param $element Element to use
2891 * @param $forceInit Optionally force initialization
2894 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2896 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2898 // Is it already set?
2899 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2900 // Already initialized
2901 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2906 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2910 * Pushes an element to a generic key
2912 * @param $keyGroup Main group for the key
2913 * @param $subGroup Sub group for the key
2914 * @param $key Key to use
2915 * @param $value Value to add/append
2916 * @return $count Number of array elements
2918 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2920 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2923 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2925 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2929 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2932 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2933 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2938 * Pushes an element to a generic array element
2940 * @param $keyGroup Main group for the key
2941 * @param $subGroup Sub group for the key
2942 * @param $key Key to use
2943 * @param $element Element to check
2944 * @param $value Value to add/append
2945 * @return $count Number of array elements
2947 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2949 //* 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));
2952 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2954 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2958 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2961 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2962 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2967 * Pops an element from a generic group
2969 * @param $keyGroup Main group for the key
2970 * @param $subGroup Sub group for the key
2971 * @param $key Key to unset
2972 * @return $value Last "popped" value
2974 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2976 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2979 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2981 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2986 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2989 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2990 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2995 * Shifts an element from a generic group
2997 * @param $keyGroup Main group for the key
2998 * @param $subGroup Sub group for the key
2999 * @param $key Key to unset
3000 * @return $value Last "popped" value
3002 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3004 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3007 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3009 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3014 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3017 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3018 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3023 * Count generic array group
3025 * @param $keyGroup Main group for the key
3026 * @return $count Count of given group
3028 protected final function countGenericArray ($keyGroup) {
3030 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3033 if (!isset($this->genericArray[$keyGroup])) {
3035 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3040 $count = count($this->genericArray[$keyGroup]);
3043 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3050 * Count generic array sub group
3052 * @param $keyGroup Main group for the key
3053 * @param $subGroup Sub group for the key
3054 * @return $count Count of given group
3056 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3058 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3061 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3063 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3068 $count = count($this->genericArray[$keyGroup][$subGroup]);
3071 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3078 * Count generic array elements
3080 * @param $keyGroup Main group for the key
3081 * @param $subGroup Sub group for the key
3082 * @para $key Key to count
3083 * @return $count Count of given key
3085 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3087 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3090 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3092 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3094 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3096 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3101 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3104 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3111 * Getter for whole generic group array
3113 * @param $keyGroup Key group to get
3114 * @return $array Whole generic array group
3116 protected final function getGenericArray ($keyGroup) {
3118 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3121 if (!isset($this->genericArray[$keyGroup])) {
3123 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3128 return $this->genericArray[$keyGroup];
3132 * Setter for generic array key
3134 * @param $keyGroup Key group to get
3135 * @param $subGroup Sub group for the key
3136 * @param $key Key to unset
3137 * @param $value Mixed value from generic array element
3140 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3142 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3145 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3149 * Getter for generic array key
3151 * @param $keyGroup Key group to get
3152 * @param $subGroup Sub group for the key
3153 * @param $key Key to unset
3154 * @return $value Mixed value from generic array element
3156 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3158 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3161 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3163 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3168 return $this->genericArray[$keyGroup][$subGroup][$key];
3172 * Sets a value in given generic array key/element
3174 * @param $keyGroup Main group for the key
3175 * @param $subGroup Sub group for the key
3176 * @param $key Key to set
3177 * @param $element Element to set
3178 * @param $value Value to set
3181 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3183 //* 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));
3186 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3190 * Getter for generic array element
3192 * @param $keyGroup Key group to get
3193 * @param $subGroup Sub group for the key
3194 * @param $key Key to look for
3195 * @param $element Element to look for
3196 * @return $value Mixed value from generic array element
3198 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3200 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3203 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3205 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3210 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3214 * Checks if a given sub group is valid (array)
3216 * @param $keyGroup Key group to get
3217 * @param $subGroup Sub group for the key
3218 * @return $isValid Whether given sub group is valid
3220 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3222 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3225 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3232 * Checks if a given key is valid (array)
3234 * @param $keyGroup Key group to get
3235 * @param $subGroup Sub group for the key
3236 * @param $key Key to check
3237 * @return $isValid Whether given sub group is valid
3239 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3241 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3244 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3251 * Initializes the web output instance
3255 protected function initWebOutputInstance () {
3256 // Get application instance
3257 $applicationInstance = Registry::getRegistry()->getInstance('app');
3259 // Is this a response instance?
3260 if ($this instanceof Responseable) {
3261 // Then set it in application instance
3262 $applicationInstance->setResponseInstance($this);
3265 // Init web output instance
3266 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3269 $this->setWebOutputInstance($outputInstance);
3273 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3275 * @param $boolean Boolean value
3276 * @return $translated Translated boolean value
3278 public static final function translateBooleanToYesNo ($boolean) {
3279 // Make sure it is really boolean
3280 assert(is_bool($boolean));
3283 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3285 // ... and return it
3290 * Encodes raw data (almost any type) by "serializing" it and then pack it
3291 * into a "binary format".
3293 * @param $rawData Raw data (almost any type)
3294 * @return $encoded Encoded data
3296 protected function encodeData ($rawData) {
3297 // Make sure no objects or resources pass through
3298 assert(!is_object($rawData));
3299 assert(!is_resource($rawData));
3301 // First "serialize" it (json_encode() is faster than serialize())
3302 $encoded = $this->packString(json_encode($rawData));
3309 * Pack a string into a "binary format". Please execuse me that this is
3310 * widely undocumented. :-(
3312 * @param $str Unpacked string
3313 * @return $packed Packed string
3314 * @todo Improve documentation
3316 protected function packString ($str) {
3318 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3320 // First compress the string (gzcompress is okay)
3321 $str = gzcompress($str);
3326 // And start the "encoding" loop
3327 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3329 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3330 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3332 if (($idx + $i) <= strlen($str)) {
3333 $ord = ord(substr($str, ($idx + $i), 1));
3335 $add = $ord * pow(256, $factor);
3339 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3343 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3344 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3346 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3347 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3353 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3358 * Checks whether the given file/path is in open_basedir(). This does not
3359 * gurantee that the file is actually readable and/or writeable. If you need
3360 * such gurantee then please use isReadableFile() instead.
3362 * @param $filePathName Name of the file/path to be checked
3363 * @return $isReachable Whether it is within open_basedir()
3365 protected static function isReachableFilePath ($filePathName) {
3366 // Is not reachable by default
3367 $isReachable = FALSE;
3369 // Get open_basedir parameter
3370 $openBaseDir = ini_get('open_basedir');
3373 if (!empty($openBaseDir)) {
3374 // Check all entries
3375 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3376 // Check on existence
3377 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3379 $isReachable = TRUE;
3383 // If open_basedir is not set, all is allowed
3384 $isReachable = TRUE;
3388 return $isReachable;
3392 * Checks whether the give file is within open_basedir() (done by
3393 * isReachableFilePath()), is actually a file and is readable.
3395 * @param $fileName Name of the file to be checked
3396 * @return $isReadable Whether the file is readable (and therefor exists)
3398 public static function isReadableFile ($fileName) {
3399 // Default is not readable
3400 $isReadable = FALSE;
3402 // Is within parameters, so check if it is a file and readable
3403 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3410 * Creates a full-qualified file name (FQFN) for given file name by adding
3411 * a configured temporary file path to it.
3413 * @param $fileName Name for temporary file
3414 * @return $fqfn Full-qualified file name
3415 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3416 * @throws FileIoException If the file cannot be written
3418 protected static function createTempPathForFile ($fileName) {
3420 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3422 // Is the path writeable?
3423 if (!is_writable($basePath)) {
3424 // Path is write-protected
3425 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3429 $fqfn = $basePath . '/' . $fileName;
3432 if (!self::isReachableFilePath($fqfn)) {
3434 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3442 * "Getter" for a printable state name
3444 * @return $stateName Name of the node's state in a printable format
3446 public final function getPrintableState () {
3447 // Default is 'null'
3448 $stateName = 'null';
3450 // Get the state instance
3451 $stateInstance = $this->getStateInstance();
3453 // Is it an instance of Stateable?
3454 if ($stateInstance instanceof Stateable) {
3455 // Then use that state name
3456 $stateName = $stateInstance->getStateName();
3464 * Handles socket error for given socket resource and peer data. This method
3465 * validates $socketResource if it is a valid resource (see is_resource())
3466 * but assumes valid data in array $recipientData, except that
3467 * count($recipientData) is always 2.
3469 * @param $method Value of __METHOD__ from calling method
3470 * @param $line Value of __LINE__ from calling method
3471 * @param $socketResource A valid socket resource
3472 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3474 * @throws InvalidSocketException If $socketResource is no socket resource
3475 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3476 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3478 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3479 // This method handles only socket resources
3480 if (!is_resource($socketResource)) {
3481 // No resource, abort here
3482 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3485 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3486 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3487 assert(isset($socketData[0]));
3488 assert(isset($socketData[1]));
3490 // Get error code for first validation (0 is not an error)
3491 $errorCode = socket_last_error($socketResource);
3493 // If the error code is zero, someone called this method without an error
3494 if ($errorCode == 0) {
3495 // No error detected (or previously cleared outside this method)
3496 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3499 // Get handler (method) name
3500 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3502 // Call-back the error handler method
3503 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3505 // Finally clear the error because it has been handled
3506 socket_clear_error($socketResource);