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\Request\Requestable;
16 use CoreFramework\Response\Responseable;
17 use CoreFramework\Stream\Output\OutputStreamer;
18 use CoreFramework\Template\CompileableTemplate;
24 * The simulator system class is the super class of all other classes. This
25 * class handles saving of games etc.
27 * @author Roland Haeder <webmaster@shipsimu.org>
29 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
30 * @license GNU GPL 3.0 or any newer version
31 * @link http://www.shipsimu.org
33 * This program is free software: you can redistribute it and/or modify
34 * it under the terms of the GNU General Public License as published by
35 * the Free Software Foundation, either version 3 of the License, or
36 * (at your option) any later version.
38 * This program is distributed in the hope that it will be useful,
39 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 * GNU General Public License for more details.
43 * You should have received a copy of the GNU General Public License
44 * along with this program. If not, see <http://www.gnu.org/licenses/>.
46 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
48 * Length of output from hash()
50 private static $hashLength = NULL;
55 private $realClass = 'BaseFrameworkSystem';
58 * Instance of a Requestable class
60 private $requestInstance = NULL;
63 * Instance of a Responseable class
65 private $responseInstance = NULL;
68 * Search criteria instance
70 private $searchInstance = NULL;
73 * Update criteria instance
75 private $updateInstance = NULL;
78 * The file I/O instance for the template loader
80 private $fileIoInstance = NULL;
85 private $resolverInstance = NULL;
88 * Template engine instance
90 private $templateInstance = NULL;
93 * Database result instance
95 private $resultInstance = NULL;
98 * Instance for user class
100 private $userInstance = NULL;
103 * A controller instance
105 private $controllerInstance = NULL;
110 private $rngInstance = NULL;
113 * Instance of a crypto helper
115 private $cryptoInstance = NULL;
118 * Instance of an Iterator class
120 private $iteratorInstance = NULL;
123 * Instance of the list
125 private $listInstance = NULL;
130 private $menuInstance = NULL;
133 * Instance of the image
135 private $imageInstance = NULL;
138 * Instance of the stacker
140 private $stackInstance = NULL;
143 * A Compressor instance
145 private $compressorInstance = NULL;
148 * A Parseable instance
150 private $parserInstance = NULL;
153 * A HandleableProtocol instance
155 private $protocolInstance = NULL;
158 * A database wrapper instance
160 private $databaseInstance = NULL;
163 * A helper instance for the form
165 private $helperInstance = NULL;
168 * An instance of a Source class
170 private $sourceInstance = NULL;
173 * An instance of a UrlSource class
175 private $urlSourceInstance = NULL;
178 * An instance of a InputStream class
180 private $inputStreamInstance = NULL;
183 * An instance of a OutputStream class
185 private $outputStreamInstance = NULL;
188 * Networkable handler instance
190 private $handlerInstance = NULL;
193 * Visitor handler instance
195 private $visitorInstance = NULL;
200 private $dhtInstance = NULL;
203 * An instance of a database wrapper class
205 private $wrapperInstance = NULL;
208 * An instance of a file I/O pointer class (not handler)
210 private $pointerInstance = NULL;
213 * An instance of an Indexable class
215 private $indexInstance = NULL;
218 * An instance of a Block class
220 private $blockInstance = NULL;
225 private $minableInstance = NULL;
228 * A FrameworkDirectory instance
230 private $directoryInstance = NULL;
235 private $listenerInstance = NULL;
238 * An instance of a communicator
240 private $communicatorInstance = NULL;
243 * The concrete output instance
245 private $outputInstance = NULL;
250 private $stateInstance = NULL;
253 * Thousands separator
255 private $thousands = '.'; // German
260 private $decimals = ','; // German
265 private $socketResource = FALSE;
268 * Regular expression to use for validation
270 private $regularExpression = '';
275 private $packageData = array();
280 private $genericArray = array();
285 private $commandName = '';
290 private $controllerName = '';
293 * Name of used protocol
295 private $protocolName = 'invalid';
298 * Array with bitmasks and such for pack/unpack methods to support both
299 * 32-bit and 64-bit systems
301 private $packingData = array(
304 'left' => 0xffff0000,
305 'right' => 0x0000ffff,
311 'left' => 0xffffffff00000000,
312 'right' => 0x00000000ffffffff,
319 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
321 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
323 private $archArrayElement = FALSE;
325 /***********************
326 * Exception codes.... *
327 ***********************/
329 // @todo Try to clean these constants up
330 const EXCEPTION_IS_NULL_POINTER = 0x001;
331 const EXCEPTION_IS_NO_OBJECT = 0x002;
332 const EXCEPTION_IS_NO_ARRAY = 0x003;
333 const EXCEPTION_MISSING_METHOD = 0x004;
334 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
335 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
336 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
337 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
338 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
339 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
340 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
341 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
342 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
343 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
344 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
345 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
346 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
347 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
348 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
349 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
350 const EXCEPTION_PATH_NOT_FOUND = 0x015;
351 const EXCEPTION_INVALID_PATH_NAME = 0x016;
352 const EXCEPTION_READ_PROTECED_PATH = 0x017;
353 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
354 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
355 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
356 const EXCEPTION_INVALID_RESOURCE = 0x01b;
357 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
358 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
359 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
360 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
361 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
362 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
363 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
364 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
365 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
366 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
367 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
368 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
369 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
370 const EXCEPTION_INVALID_STRING = 0x029;
371 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
372 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
373 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
374 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
375 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
376 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
377 const EXCEPTION_MISSING_ELEMENT = 0x030;
378 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
379 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
380 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
381 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
382 const EXCEPTION_FATAL_ERROR = 0x035;
383 const EXCEPTION_FILE_NOT_FOUND = 0x036;
384 const EXCEPTION_ASSERTION_FAILED = 0x037;
385 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
386 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
387 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
388 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
389 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
390 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
393 * Hexadecimal->Decimal translation array
395 private static $hexdec = array(
415 * Decimal->hexadecimal translation array
417 private static $dechex = array(
437 * Startup time in miliseconds
439 private static $startupTime = 0;
442 * Protected super constructor
444 * @param $className Name of the class
447 protected function __construct ($className) {
449 $this->setRealClass($className);
451 // Set configuration instance if no registry ...
452 if (!$this instanceof Register) {
453 // ... because registries doesn't need to be configured
454 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
457 // Is the startup time set? (0 cannot be TRUE anymore)
458 if (self::$startupTime == 0) {
460 self::$startupTime = microtime(TRUE);
464 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
468 * Destructor for all classes. You should not call this method on your own.
472 public function __destruct () {
473 // Flush any updated entries to the database
474 $this->flushPendingUpdates();
476 // Is this object already destroyed?
477 if ($this->__toString() != 'DestructedObject') {
478 // Destroy all informations about this class but keep some text about it alive
479 $this->setRealClass('DestructedObject');
480 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
481 // Already destructed object
482 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
487 // Do not call this twice
488 trigger_error(__METHOD__ . ': Called twice.');
494 * The __call() method where all non-implemented methods end up
496 * @param $methodName Name of the missing method
497 * @args $args Arguments passed to the method
500 public final function __call ($methodName, $args) {
501 return self::__callStatic($methodName, $args);
505 * The __callStatic() method where all non-implemented static methods end up
507 * @param $methodName Name of the missing method
508 * @args $args Arguments passed to the method
511 public static final function __callStatic ($methodName, $args) {
513 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
515 // Init argument string
518 // Is it NULL, empty or an array?
519 if (is_null($args)) {
521 $argsString = 'NULL';
522 } elseif (is_array($args)) {
526 // Some arguments are there
527 foreach ($args as $arg) {
528 // Add data about the argument
529 $argsString .= gettype($arg) . ':';
532 // Found a NULL argument
533 $argsString .= 'NULL';
534 } elseif (is_string($arg)) {
535 // Add length for strings
536 $argsString .= strlen($arg);
537 } elseif ((is_int($arg)) || (is_float($arg))) {
540 } elseif (is_array($arg)) {
541 // .. or size if array
542 $argsString .= count($arg);
543 } elseif (is_object($arg)) {
545 $reflection = new ReflectionClass($arg);
547 // Is an other object, maybe no __toString() available
548 $argsString .= $reflection->getName();
549 } elseif ($arg === TRUE) {
550 // ... is boolean 'TRUE'
551 $argsString .= 'TRUE';
552 } elseif ($arg === FALSE) {
553 // ... is boolean 'FALSE'
554 $argsString .= 'FALSE';
557 // Comma for next one
562 if (substr($argsString, -2, 1) == ',') {
563 $argsString = substr($argsString, 0, -2);
569 // Invalid arguments!
570 $argsString = '!INVALID:' . gettype($args) . '!';
573 // Output stub message
574 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
575 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
585 * Getter for $realClass
587 * @return $realClass The name of the real class (not BaseFrameworkSystem)
589 public function __toString () {
590 return $this->realClass;
594 * Magic method to catch setting of missing but set class fields/attributes
596 * @param $name Name of the field/attribute
597 * @param $value Value to store
600 public final function __set ($name, $value) {
601 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
604 print_r($value, TRUE)
609 * Magic method to catch getting of missing fields/attributes
611 * @param $name Name of the field/attribute
614 public final function __get ($name) {
615 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
621 * Magic method to catch unsetting of missing fields/attributes
623 * @param $name Name of the field/attribute
626 public final function __unset ($name) {
627 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
633 * Magic method to catch object serialization
635 * @return $unsupported Unsupported method
636 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
638 public final function __sleep () {
639 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
643 * Magic method to catch object deserialization
645 * @return $unsupported Unsupported method
646 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
648 public final function __wakeup () {
649 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
653 * Magic method to catch calls when an object instance is called
655 * @return $unsupported Unsupported method
656 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
658 public final function __invoke () {
659 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
663 * Setter for the real class name
665 * @param $realClass Class name (string)
668 public final function setRealClass ($realClass) {
670 $this->realClass = (string) $realClass;
674 * Setter for database result instance
676 * @param $resultInstance An instance of a database result class
678 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
680 protected final function setResultInstance (SearchableResult $resultInstance) {
681 $this->resultInstance = $resultInstance;
685 * Getter for database result instance
687 * @return $resultInstance An instance of a database result class
689 public final function getResultInstance () {
690 return $this->resultInstance;
694 * Setter for template engine instances
696 * @param $templateInstance An instance of a template engine class
699 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
700 $this->templateInstance = $templateInstance;
704 * Getter for template engine instances
706 * @return $templateInstance An instance of a template engine class
708 protected final function getTemplateInstance () {
709 return $this->templateInstance;
713 * Setter for search instance
715 * @param $searchInstance Searchable criteria instance
718 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
719 $this->searchInstance = $searchInstance;
723 * Getter for search instance
725 * @return $searchInstance Searchable criteria instance
727 public final function getSearchInstance () {
728 return $this->searchInstance;
732 * Setter for update instance
734 * @param $updateInstance Searchable criteria instance
737 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
738 $this->updateInstance = $updateInstance;
742 * Getter for update instance
744 * @return $updateInstance Updateable criteria instance
746 public final function getUpdateInstance () {
747 return $this->updateInstance;
751 * Setter for resolver instance
753 * @param $resolverInstance Instance of a command resolver class
756 public final function setResolverInstance (Resolver $resolverInstance) {
757 $this->resolverInstance = $resolverInstance;
761 * Getter for resolver instance
763 * @return $resolverInstance Instance of a command resolver class
765 public final function getResolverInstance () {
766 return $this->resolverInstance;
770 * Setter for language instance
772 * @param $configInstance The configuration instance which shall
773 * be FrameworkConfiguration
776 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
777 Registry::getRegistry()->addInstance('config', $configInstance);
781 * Getter for configuration instance
783 * @return $configInstance Configuration instance
785 public final function getConfigInstance () {
786 $configInstance = Registry::getRegistry()->getInstance('config');
787 return $configInstance;
791 * Setter for debug instance
793 * @param $debugInstance The instance for debug output class
796 public final function setDebugInstance (DebugMiddleware $debugInstance) {
797 Registry::getRegistry()->addInstance('debug', $debugInstance);
801 * Getter for debug instance
803 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
805 public final function getDebugInstance () {
806 // Get debug instance
807 $debugInstance = Registry::getRegistry()->getInstance('debug');
810 return $debugInstance;
814 * Setter for web output instance
816 * @param $webInstance The instance for web output class
819 public final function setWebOutputInstance (OutputStreamer $webInstance) {
820 Registry::getRegistry()->addInstance('web_output', $webInstance);
824 * Getter for web output instance
826 * @return $webOutputInstance - Instance to class WebOutput
828 public final function getWebOutputInstance () {
829 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
830 return $webOutputInstance;
834 * Setter for database instance
836 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
839 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
840 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
844 * Getter for database layer
846 * @return $databaseInstance The database layer instance
848 public final function getDatabaseInstance () {
850 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
853 return $databaseInstance;
857 * Setter for compressor channel
859 * @param $compressorInstance An instance of CompressorChannel
862 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
863 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
867 * Getter for compressor channel
869 * @return $compressorInstance The compressor channel
871 public final function getCompressorChannel () {
872 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
873 return $compressorInstance;
877 * Protected getter for a manageable application helper class
879 * @return $applicationInstance An instance of a manageable application helper class
881 protected final function getApplicationInstance () {
882 $applicationInstance = Registry::getRegistry()->getInstance('application');
883 return $applicationInstance;
887 * Setter for a manageable application helper class
889 * @param $applicationInstance An instance of a manageable application helper class
892 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
893 Registry::getRegistry()->addInstance('application', $applicationInstance);
897 * Setter for request instance
899 * @param $requestInstance An instance of a Requestable class
902 public final function setRequestInstance (Requestable $requestInstance) {
903 $this->requestInstance = $requestInstance;
907 * Getter for request instance
909 * @return $requestInstance An instance of a Requestable class
911 public final function getRequestInstance () {
912 return $this->requestInstance;
916 * Setter for response instance
918 * @param $responseInstance An instance of a Responseable class
921 public final function setResponseInstance (Responseable $responseInstance) {
922 $this->responseInstance = $responseInstance;
926 * Getter for response instance
928 * @return $responseInstance An instance of a Responseable class
930 public final function getResponseInstance () {
931 return $this->responseInstance;
935 * Private getter for language instance
937 * @return $langInstance An instance to the language sub-system
939 protected final function getLanguageInstance () {
940 $langInstance = Registry::getRegistry()->getInstance('language');
941 return $langInstance;
945 * Setter for language instance
947 * @param $langInstance An instance to the language sub-system
949 * @see LanguageSystem
951 public final function setLanguageInstance (ManageableLanguage $langInstance) {
952 Registry::getRegistry()->addInstance('language', $langInstance);
956 * Private getter for file IO instance
958 * @return $fileIoInstance An instance to the file I/O sub-system
960 protected final function getFileIoInstance () {
961 return $this->fileIoInstance;
965 * Setter for file I/O instance
967 * @param $fileIoInstance An instance to the file I/O sub-system
970 public final function setFileIoInstance (IoHandler $fileIoInstance) {
971 $this->fileIoInstance = $fileIoInstance;
975 * Protected setter for user instance
977 * @param $userInstance An instance of a user class
980 protected final function setUserInstance (ManageableAccount $userInstance) {
981 $this->userInstance = $userInstance;
985 * Getter for user instance
987 * @return $userInstance An instance of a user class
989 public final function getUserInstance () {
990 return $this->userInstance;
994 * Setter for controller instance (this surely breaks a bit the MVC patterm)
996 * @param $controllerInstance An instance of the controller
999 public final function setControllerInstance (Controller $controllerInstance) {
1000 $this->controllerInstance = $controllerInstance;
1004 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1006 * @return $controllerInstance An instance of the controller
1008 public final function getControllerInstance () {
1009 return $this->controllerInstance;
1013 * Setter for RNG instance
1015 * @param $rngInstance An instance of a random number generator (RNG)
1018 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1019 $this->rngInstance = $rngInstance;
1023 * Getter for RNG instance
1025 * @return $rngInstance An instance of a random number generator (RNG)
1027 public final function getRngInstance () {
1028 return $this->rngInstance;
1032 * Setter for Cryptable instance
1034 * @param $cryptoInstance An instance of a Cryptable class
1037 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1038 $this->cryptoInstance = $cryptoInstance;
1042 * Getter for Cryptable instance
1044 * @return $cryptoInstance An instance of a Cryptable class
1046 public final function getCryptoInstance () {
1047 return $this->cryptoInstance;
1051 * Setter for the list instance
1053 * @param $listInstance A list of Listable
1056 protected final function setListInstance (Listable $listInstance) {
1057 $this->listInstance = $listInstance;
1061 * Getter for the list instance
1063 * @return $listInstance A list of Listable
1065 protected final function getListInstance () {
1066 return $this->listInstance;
1070 * Setter for the menu instance
1072 * @param $menuInstance A RenderableMenu instance
1075 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1076 $this->menuInstance = $menuInstance;
1080 * Getter for the menu instance
1082 * @return $menuInstance A RenderableMenu instance
1084 protected final function getMenuInstance () {
1085 return $this->menuInstance;
1089 * Setter for image instance
1091 * @param $imageInstance An instance of an image
1094 public final function setImageInstance (BaseImage $imageInstance) {
1095 $this->imageInstance = $imageInstance;
1099 * Getter for image instance
1101 * @return $imageInstance An instance of an image
1103 public final function getImageInstance () {
1104 return $this->imageInstance;
1108 * Setter for stacker instance
1110 * @param $stackInstance An instance of an stacker
1113 public final function setStackInstance (Stackable $stackInstance) {
1114 $this->stackInstance = $stackInstance;
1118 * Getter for stacker instance
1120 * @return $stackInstance An instance of an stacker
1122 public final function getStackInstance () {
1123 return $this->stackInstance;
1127 * Setter for compressor instance
1129 * @param $compressorInstance An instance of an compressor
1132 public final function setCompressorInstance (Compressor $compressorInstance) {
1133 $this->compressorInstance = $compressorInstance;
1137 * Getter for compressor instance
1139 * @return $compressorInstance An instance of an compressor
1141 public final function getCompressorInstance () {
1142 return $this->compressorInstance;
1146 * Setter for Parseable instance
1148 * @param $parserInstance An instance of an Parseable
1151 public final function setParserInstance (Parseable $parserInstance) {
1152 $this->parserInstance = $parserInstance;
1156 * Getter for Parseable instance
1158 * @return $parserInstance An instance of an Parseable
1160 public final function getParserInstance () {
1161 return $this->parserInstance;
1165 * Setter for HandleableProtocol instance
1167 * @param $protocolInstance An instance of an HandleableProtocol
1170 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1171 $this->protocolInstance = $protocolInstance;
1175 * Getter for HandleableProtocol instance
1177 * @return $protocolInstance An instance of an HandleableProtocol
1179 public final function getProtocolInstance () {
1180 return $this->protocolInstance;
1184 * Setter for DatabaseWrapper instance
1186 * @param $wrapperInstance An instance of an DatabaseWrapper
1189 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1190 $this->wrapperInstance = $wrapperInstance;
1194 * Getter for DatabaseWrapper instance
1196 * @return $wrapperInstance An instance of an DatabaseWrapper
1198 public final function getWrapperInstance () {
1199 return $this->wrapperInstance;
1203 * Setter for socket resource
1205 * @param $socketResource A valid socket resource
1208 public final function setSocketResource ($socketResource) {
1209 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1210 $this->socketResource = $socketResource;
1214 * Getter for socket resource
1216 * @return $socketResource A valid socket resource
1218 public final function getSocketResource () {
1219 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1220 return $this->socketResource;
1224 * Setter for regular expression
1226 * @param $regularExpression A valid regular expression
1229 public final function setRegularExpression ($regularExpression) {
1230 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1231 $this->regularExpression = $regularExpression;
1235 * Getter for regular expression
1237 * @return $regularExpression A valid regular expression
1239 public final function getRegularExpression () {
1240 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1241 return $this->regularExpression;
1245 * Setter for helper instance
1247 * @param $helperInstance An instance of a helper class
1250 protected final function setHelperInstance (Helper $helperInstance) {
1251 $this->helperInstance = $helperInstance;
1255 * Getter for helper instance
1257 * @return $helperInstance An instance of a helper class
1259 public final function getHelperInstance () {
1260 return $this->helperInstance;
1264 * Setter for a Source instance
1266 * @param $sourceInstance An instance of a Source class
1269 protected final function setSourceInstance (Source $sourceInstance) {
1270 $this->sourceInstance = $sourceInstance;
1274 * Getter for a Source instance
1276 * @return $sourceInstance An instance of a Source class
1278 protected final function getSourceInstance () {
1279 return $this->sourceInstance;
1283 * Setter for a UrlSource instance
1285 * @param $sourceInstance An instance of a UrlSource class
1288 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1289 $this->urlSourceInstance = $urlSourceInstance;
1293 * Getter for a UrlSource instance
1295 * @return $urlSourceInstance An instance of a UrlSource class
1297 protected final function getUrlSourceInstance () {
1298 return $this->urlSourceInstance;
1302 * Getter for a InputStream instance
1304 * @param $inputStreamInstance The InputStream instance
1306 protected final function getInputStreamInstance () {
1307 return $this->inputStreamInstance;
1311 * Setter for a InputStream instance
1313 * @param $inputStreamInstance The InputStream instance
1316 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1317 $this->inputStreamInstance = $inputStreamInstance;
1321 * Getter for a OutputStream instance
1323 * @param $outputStreamInstance The OutputStream instance
1325 protected final function getOutputStreamInstance () {
1326 return $this->outputStreamInstance;
1330 * Setter for a OutputStream instance
1332 * @param $outputStreamInstance The OutputStream instance
1335 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1336 $this->outputStreamInstance = $outputStreamInstance;
1340 * Setter for handler instance
1342 * @param $handlerInstance An instance of a Handleable class
1345 protected final function setHandlerInstance (Handleable $handlerInstance) {
1346 $this->handlerInstance = $handlerInstance;
1350 * Getter for handler instance
1352 * @return $handlerInstance A Networkable instance
1354 protected final function getHandlerInstance () {
1355 return $this->handlerInstance;
1359 * Setter for visitor instance
1361 * @param $visitorInstance A Visitor instance
1364 protected final function setVisitorInstance (Visitor $visitorInstance) {
1365 $this->visitorInstance = $visitorInstance;
1369 * Getter for visitor instance
1371 * @return $visitorInstance A Visitor instance
1373 protected final function getVisitorInstance () {
1374 return $this->visitorInstance;
1378 * Setter for DHT instance
1380 * @param $dhtInstance A Distributable instance
1383 protected final function setDhtInstance (Distributable $dhtInstance) {
1384 $this->dhtInstance = $dhtInstance;
1388 * Getter for DHT instance
1390 * @return $dhtInstance A Distributable instance
1392 protected final function getDhtInstance () {
1393 return $this->dhtInstance;
1397 * Setter for raw package Data
1399 * @param $packageData Raw package Data
1402 public final function setPackageData (array $packageData) {
1403 $this->packageData = $packageData;
1407 * Getter for raw package Data
1409 * @return $packageData Raw package Data
1411 public function getPackageData () {
1412 return $this->packageData;
1417 * Setter for Iterator instance
1419 * @param $iteratorInstance An instance of an Iterator
1422 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1423 $this->iteratorInstance = $iteratorInstance;
1427 * Getter for Iterator instance
1429 * @return $iteratorInstance An instance of an Iterator
1431 public final function getIteratorInstance () {
1432 return $this->iteratorInstance;
1436 * Setter for FilePointer instance
1438 * @param $pointerInstance An instance of an FilePointer class
1441 protected final function setPointerInstance (FilePointer $pointerInstance) {
1442 $this->pointerInstance = $pointerInstance;
1446 * Getter for FilePointer instance
1448 * @return $pointerInstance An instance of an FilePointer class
1450 public final function getPointerInstance () {
1451 return $this->pointerInstance;
1455 * Unsets pointer instance which triggers a call of __destruct() if the
1456 * instance is still there. This is surely not fatal on already "closed"
1457 * file pointer instances.
1459 * I don't want to mess around with above setter by giving it a default
1460 * value NULL as setter should always explicitly only set (existing) object
1461 * instances and NULL is NULL.
1465 protected final function unsetPointerInstance () {
1466 // Simply it to NULL
1467 $this->pointerInstance = NULL;
1471 * Setter for Indexable instance
1473 * @param $indexInstance An instance of an Indexable class
1476 protected final function setIndexInstance (Indexable $indexInstance) {
1477 $this->indexInstance = $indexInstance;
1481 * Getter for Indexable instance
1483 * @return $indexInstance An instance of an Indexable class
1485 public final function getIndexInstance () {
1486 return $this->indexInstance;
1490 * Setter for Block instance
1492 * @param $blockInstance An instance of an Block class
1495 protected final function setBlockInstance (Block $blockInstance) {
1496 $this->blockInstance = $blockInstance;
1500 * Getter for Block instance
1502 * @return $blockInstance An instance of an Block class
1504 public final function getBlockInstance () {
1505 return $this->blockInstance;
1509 * Setter for Minable instance
1511 * @param $minableInstance A Minable instance
1514 protected final function setMinableInstance (Minable $minableInstance) {
1515 $this->minableInstance = $minableInstance;
1519 * Getter for minable instance
1521 * @return $minableInstance A Minable instance
1523 protected final function getMinableInstance () {
1524 return $this->minableInstance;
1528 * Setter for FrameworkDirectory instance
1530 * @param $directoryInstance A FrameworkDirectoryPointer instance
1533 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1534 $this->directoryInstance = $directoryInstance;
1538 * Getter for FrameworkDirectory instance
1540 * @return $directoryInstance A FrameworkDirectory instance
1542 protected final function getDirectoryInstance () {
1543 return $this->directoryInstance;
1547 * Setter for listener instance
1549 * @param $listenerInstance A Listenable instance
1552 protected final function setListenerInstance (Listenable $listenerInstance) {
1553 $this->listenerInstance = $listenerInstance;
1557 * Getter for listener instance
1559 * @return $listenerInstance A Listenable instance
1561 protected final function getListenerInstance () {
1562 return $this->listenerInstance;
1566 * Getter for communicator instance
1568 * @return $communicatorInstance An instance of a Communicator class
1570 public final function getCommunicatorInstance () {
1571 return $this->communicatorInstance;
1575 * Setter for communicator instance
1577 * @param $communicatorInstance An instance of a Communicator class
1580 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1581 $this->communicatorInstance = $communicatorInstance;
1585 * Setter for state instance
1587 * @param $stateInstance A Stateable instance
1590 public final function setStateInstance (Stateable $stateInstance) {
1591 $this->stateInstance = $stateInstance;
1595 * Getter for state instance
1597 * @return $stateInstance A Stateable instance
1599 public final function getStateInstance () {
1600 return $this->stateInstance;
1604 * Setter for output instance
1606 * @param $outputInstance The debug output instance
1609 public final function setOutputInstance (OutputStreamer $outputInstance) {
1610 $this->outputInstance = $outputInstance;
1614 * Getter for output instance
1616 * @return $outputInstance The debug output instance
1618 public final function getOutputInstance () {
1619 return $this->outputInstance;
1623 * Setter for command name
1625 * @param $commandName Last validated command name
1628 protected final function setCommandName ($commandName) {
1629 $this->commandName = $commandName;
1633 * Getter for command name
1635 * @return $commandName Last validated command name
1637 protected final function getCommandName () {
1638 return $this->commandName;
1642 * Setter for controller name
1644 * @param $controllerName Last validated controller name
1647 protected final function setControllerName ($controllerName) {
1648 $this->controllerName = $controllerName;
1652 * Getter for controller name
1654 * @return $controllerName Last validated controller name
1656 protected final function getControllerName () {
1657 return $this->controllerName;
1661 * Getter for protocol name
1663 * @return $protocolName Name of used protocol
1665 public final function getProtocolName () {
1666 return $this->protocolName;
1670 * Setter for protocol name
1672 * @param $protocolName Name of used protocol
1675 protected final function setProtocolName ($protocolName) {
1676 $this->protocolName = $protocolName;
1680 * Checks whether an object equals this object. You should overwrite this
1681 * method to implement own equality checks
1683 * @param $objectInstance An instance of a FrameworkInterface object
1684 * @return $equals Whether both objects equals
1686 public function equals (FrameworkInterface $objectInstance) {
1689 $this->__toString() == $objectInstance->__toString()
1691 $this->hashCode() == $objectInstance->hashCode()
1694 // Return the result
1699 * Generates a generic hash code of this class. You should really overwrite
1700 * this method with your own hash code generator code. But keep KISS in mind.
1702 * @return $hashCode A generic hash code respresenting this whole class
1704 public function hashCode () {
1706 return crc32($this->__toString());
1710 * Formats computer generated price values into human-understandable formats
1711 * with thousand and decimal separators.
1713 * @param $value The in computer format value for a price
1714 * @param $currency The currency symbol (use HTML-valid characters!)
1715 * @param $decNum Number of decimals after commata
1716 * @return $price The for the current language formated price string
1717 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1718 * thousands separator
1721 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1722 // Are all required attriutes set?
1723 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1724 // Throw an exception
1725 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1729 $value = (float) $value;
1731 // Reformat the US number
1732 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1734 // Return as string...
1739 * Appends a trailing slash to a string
1741 * @param $str A string (maybe) without trailing slash
1742 * @return $str A string with an auto-appended trailing slash
1744 public final function addMissingTrailingSlash ($str) {
1745 // Is there a trailing slash?
1746 if (substr($str, -1, 1) != '/') {
1750 // Return string with trailing slash
1755 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1756 * application helper instance (ApplicationHelper by default).
1758 * @param $applicationInstance An application helper instance or
1759 * null if we shall use the default
1760 * @return $templateInstance The template engine instance
1761 * @throws NullPointerException If the discovered application
1762 * instance is still null
1764 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1765 // Is the application instance set?
1766 if (is_null($applicationInstance)) {
1767 // Get the current instance
1768 $applicationInstance = $this->getApplicationInstance();
1771 if (is_null($applicationInstance)) {
1772 // Thrown an exception
1773 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1777 // Initialize the template engine
1778 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1780 // Return the prepared instance
1781 return $templateInstance;
1785 * Debugs this instance by putting out it's full content
1787 * @param $message Optional message to show in debug output
1790 public final function debugInstance ($message = '') {
1791 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1792 restore_error_handler();
1797 // Is a message set?
1798 if (!empty($message)) {
1799 // Construct message
1800 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1803 // Generate the output
1804 $content .= sprintf('<pre>%s</pre>',
1807 print_r($this, TRUE)
1813 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>',
1814 $this->__toString(),
1816 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1821 * Replaces control characters with printable output
1823 * @param $str String with control characters
1824 * @return $str Replaced string
1826 protected function replaceControlCharacters ($str) {
1829 chr(13), '[r]', str_replace(
1830 chr(10), '[n]', str_replace(
1840 * Output a partial stub message for the caller method
1842 * @param $message An optional message to display
1845 protected function partialStub ($message = '') {
1846 // Get the backtrace
1847 $backtrace = debug_backtrace();
1849 // Generate the class::method string
1850 $methodName = 'UnknownClass->unknownMethod';
1851 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1852 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1855 // Construct the full message
1856 $stubMessage = sprintf('[%s:] Partial stub!',
1860 // Is the extra message given?
1861 if (!empty($message)) {
1862 // Then add it as well
1863 $stubMessage .= ' Message: ' . $message;
1866 // Debug instance is there?
1867 if (!is_null($this->getDebugInstance())) {
1868 // Output stub message
1869 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1872 trigger_error($stubMessage);
1878 * Outputs a debug backtrace and stops further script execution
1880 * @param $message An optional message to output
1881 * @param $doExit Whether exit the program (TRUE is default)
1884 public function debugBackTrace ($message = '', $doExit = TRUE) {
1885 // Sorry, there is no other way getting this nice backtrace
1886 if (!empty($message)) {
1888 printf('Message: %s<br />' . PHP_EOL, $message);
1892 debug_print_backtrace();
1896 if ($doExit === TRUE) {
1902 * Creates an instance of a debugger instance
1904 * @param $className Name of the class (currently unsupported)
1905 * @param $lineNumber Line number where the call was made
1906 * @return $debugInstance An instance of a debugger class
1907 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1909 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1910 // Is the instance set?
1911 if (!Registry::getRegistry()->instanceExists('debug')) {
1912 // Init debug instance
1913 $debugInstance = NULL;
1917 // Get a debugger instance
1918 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1919 } catch (NullPointerException $e) {
1920 // Didn't work, no instance there
1921 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1924 // Empty string should be ignored and used for testing the middleware
1925 DebugMiddleware::getSelfInstance()->output('');
1927 // Set it in its own class. This will set it in the registry
1928 $debugInstance->setDebugInstance($debugInstance);
1930 // Get instance from registry
1931 $debugInstance = Registry::getRegistry()->getDebugInstance();
1935 return $debugInstance;
1939 * Simple output of a message with line-break
1941 * @param $message Message to output
1944 public function outputLine ($message) {
1946 print($message . PHP_EOL);
1950 * Outputs a debug message whether to debug instance (should be set!) or
1951 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1952 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1954 * @param $message Message we shall send out...
1955 * @param $doPrint Whether print or die here (default: print)
1956 * @paran $stripTags Whether to strip tags (default: FALSE)
1959 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1960 // Set debug instance to NULL
1961 $debugInstance = NULL;
1965 // Get debug instance
1966 $debugInstance = $this->getDebugInstance();
1967 } catch (NullPointerException $e) {
1968 // The debug instance is not set (yet)
1971 // Is the debug instance there?
1972 if (is_object($debugInstance)) {
1973 // Use debug output handler
1974 $debugInstance->output($message, $stripTags);
1976 if ($doPrint === FALSE) {
1977 // Die here if not printed
1981 // Are debug times enabled?
1982 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1984 $message = $this->getPrintableExecutionTime() . $message;
1988 if ($doPrint === TRUE) {
1990 $this->outputLine($message);
1999 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2001 * @param $str The string, what ever it is needs to be converted
2002 * @return $className Generated class name
2004 public static final function convertToClassName ($str) {
2008 // Convert all dashes in underscores
2009 $str = self::convertDashesToUnderscores($str);
2011 // Now use that underscores to get classname parts for hungarian style
2012 foreach (explode('_', $str) as $strPart) {
2013 // Make the class name part lower case and first upper case
2014 $className .= ucfirst(strtolower($strPart));
2017 // Return class name
2022 * Converts dashes to underscores, e.g. useable for configuration entries
2024 * @param $str The string with maybe dashes inside
2025 * @return $str The converted string with no dashed, but underscores
2027 public static final function convertDashesToUnderscores ($str) {
2029 $str = str_replace('-', '_', $str);
2031 // Return converted string
2036 * Marks up the code by adding e.g. line numbers
2038 * @param $phpCode Unmarked PHP code
2039 * @return $markedCode Marked PHP code
2041 public function markupCode ($phpCode) {
2046 $errorArray = error_get_last();
2048 // Init the code with error message
2049 if (is_array($errorArray)) {
2051 $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>',
2052 basename($errorArray['file']),
2053 $errorArray['line'],
2054 $errorArray['message'],
2059 // Add line number to the code
2060 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2062 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2064 htmlentities($code, ENT_QUOTES)
2073 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2074 * beatiful for web-based front-ends. If null is given a message id
2075 * null_timestamp will be resolved and returned.
2077 * @param $timestamp Timestamp to prepare (filter) for display
2078 * @return $readable A readable timestamp
2080 public function doFilterFormatTimestamp ($timestamp) {
2081 // Default value to return
2084 // Is the timestamp null?
2085 if (is_null($timestamp)) {
2086 // Get a message string
2087 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2089 switch ($this->getLanguageInstance()->getLanguageCode()) {
2090 case 'de': // German format is a bit different to default
2091 // Split the GMT stamp up
2092 $dateTime = explode(' ', $timestamp );
2093 $dateArray = explode('-', $dateTime[0]);
2094 $timeArray = explode(':', $dateTime[1]);
2096 // Construct the timestamp
2097 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2107 default: // Default is pass-through
2108 $readable = $timestamp;
2118 * Filter a given number into a localized number
2120 * @param $value The raw value from e.g. database
2121 * @return $localized Localized value
2123 public function doFilterFormatNumber ($value) {
2124 // Generate it from config and localize dependencies
2125 switch ($this->getLanguageInstance()->getLanguageCode()) {
2126 case 'de': // German format is a bit different to default
2127 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2130 default: // US, etc.
2131 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2140 * "Getter" for databse entry
2142 * @return $entry An array with database entries
2143 * @throws NullPointerException If the database result is not found
2144 * @throws InvalidDatabaseResultException If the database result is invalid
2146 protected final function getDatabaseEntry () {
2147 // Is there an instance?
2148 if (!$this->getResultInstance() instanceof SearchableResult) {
2149 // Throw an exception here
2150 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2154 $this->getResultInstance()->rewind();
2156 // Do we have an entry?
2157 if ($this->getResultInstance()->valid() === FALSE) {
2158 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2159 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2163 $this->getResultInstance()->next();
2166 $entry = $this->getResultInstance()->current();
2173 * Getter for field name
2175 * @param $fieldName Field name which we shall get
2176 * @return $fieldValue Field value from the user
2177 * @throws NullPointerException If the result instance is null
2179 public final function getField ($fieldName) {
2180 // Default field value
2183 // Get result instance
2184 $resultInstance = $this->getResultInstance();
2186 // Is this instance null?
2187 if (is_null($resultInstance)) {
2188 // Then the user instance is no longer valid (expired cookies?)
2189 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2192 // Get current array
2193 $fieldArray = $resultInstance->current();
2194 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2196 // Convert dashes to underscore
2197 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2199 // Does the field exist?
2200 if ($this->isFieldSet($fieldName)) {
2202 $fieldValue = $fieldArray[$fieldName2];
2203 } elseif (defined('DEVELOPER')) {
2204 // Missing field entry, may require debugging
2205 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2207 // Missing field entry, may require debugging
2208 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2216 * Checks if given field is set
2218 * @param $fieldName Field name to check
2219 * @return $isSet Whether the given field name is set
2220 * @throws NullPointerException If the result instance is null
2222 public function isFieldSet ($fieldName) {
2223 // Get result instance
2224 $resultInstance = $this->getResultInstance();
2226 // Is this instance null?
2227 if (is_null($resultInstance)) {
2228 // Then the user instance is no longer valid (expired cookies?)
2229 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2232 // Get current array
2233 $fieldArray = $resultInstance->current();
2234 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2236 // Convert dashes to underscore
2237 $fieldName = self::convertDashesToUnderscores($fieldName);
2240 $isSet = isset($fieldArray[$fieldName]);
2247 * Flushs all pending updates to the database layer
2251 public function flushPendingUpdates () {
2252 // Get result instance
2253 $resultInstance = $this->getResultInstance();
2255 // Do we have data to update?
2256 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2257 // Get wrapper class name config entry
2258 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2260 // Create object instance
2261 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2263 // Yes, then send the whole result to the database layer
2264 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2269 * Outputs a deprecation warning to the developer.
2271 * @param $message The message we shall output to the developer
2273 * @todo Write a logging mechanism for productive mode
2275 public function deprecationWarning ($message) {
2276 // Is developer mode active?
2277 if (defined('DEVELOPER')) {
2278 // Debug instance is there?
2279 if (!is_null($this->getDebugInstance())) {
2280 // Output stub message
2281 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2284 trigger_error($message . "<br />\n");
2288 // @TODO Finish this part!
2289 $this->partialStub('Developer mode inactive. Message:' . $message);
2294 * Checks whether the given PHP extension is loaded
2296 * @param $phpExtension The PHP extension we shall check
2297 * @return $isLoaded Whether the PHP extension is loaded
2299 public final function isPhpExtensionLoaded ($phpExtension) {
2301 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2308 * "Getter" as a time() replacement but with milliseconds. You should use this
2309 * method instead of the encapsulated getimeofday() function.
2311 * @return $milliTime Timestamp with milliseconds
2313 public function getMilliTime () {
2314 // Get the time of day as float
2315 $milliTime = gettimeofday(TRUE);
2322 * Idles (sleeps) for given milliseconds
2324 * @return $hasSlept Whether it goes fine
2326 public function idle ($milliSeconds) {
2327 // Sleep is fine by default
2330 // Idle so long with found function
2331 if (function_exists('time_sleep_until')) {
2332 // Get current time and add idle time
2333 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2335 // New PHP 5.1.0 function found, ignore errors
2336 $hasSlept = @time_sleep_until($sleepUntil);
2339 * My Sun station doesn't have that function even with latest PHP
2342 usleep($milliSeconds * 1000);
2349 * Converts a hexadecimal string, even with negative sign as first string to
2350 * a decimal number using BC functions.
2352 * This work is based on comment #86673 on php.net documentation page at:
2353 * <http://de.php.net/manual/en/function.dechex.php#86673>
2355 * @param $hex Hexadecimal string
2356 * @return $dec Decimal number
2358 protected function hex2dec ($hex) {
2359 // Convert to all lower-case
2360 $hex = strtolower($hex);
2362 // Detect sign (negative/positive numbers)
2364 if (substr($hex, 0, 1) == '-') {
2366 $hex = substr($hex, 1);
2369 // Decode the hexadecimal string into a decimal number
2371 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2372 $factor = self::$hexdec[substr($hex, $i, 1)];
2373 $dec = bcadd($dec, bcmul($factor, $e));
2376 // Return the decimal number
2377 return $sign . $dec;
2381 * Converts even very large decimal numbers, also signed, to a hexadecimal
2384 * This work is based on comment #97756 on php.net documentation page at:
2385 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2387 * @param $dec Decimal number, even with negative sign
2388 * @param $maxLength Optional maximum length of the string
2389 * @return $hex Hexadecimal string
2391 protected function dec2hex ($dec, $maxLength = 0) {
2392 // maxLength can be zero or devideable by 2
2393 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2395 // Detect sign (negative/positive numbers)
2402 // Encode the decimal number into a hexadecimal string
2405 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2407 } while ($dec >= 1);
2410 * Leading zeros are required for hex-decimal "numbers". In some
2411 * situations more leading zeros are wanted, so check for both
2414 if ($maxLength > 0) {
2415 // Prepend more zeros
2416 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2417 } elseif ((strlen($hex) % 2) != 0) {
2418 // Only make string's length dividable by 2
2422 // Return the hexadecimal string
2423 return $sign . $hex;
2427 * Converts a ASCII string (0 to 255) into a decimal number.
2429 * @param $asc The ASCII string to be converted
2430 * @return $dec Decimal number
2432 protected function asc2dec ($asc) {
2433 // Convert it into a hexadecimal number
2434 $hex = bin2hex($asc);
2436 // And back into a decimal number
2437 $dec = $this->hex2dec($hex);
2444 * Converts a decimal number into an ASCII string.
2446 * @param $dec Decimal number
2447 * @return $asc An ASCII string
2449 protected function dec2asc ($dec) {
2450 // First convert the number into a hexadecimal string
2451 $hex = $this->dec2hex($dec);
2453 // Then convert it into the ASCII string
2454 $asc = $this->hex2asc($hex);
2461 * Converts a hexadecimal number into an ASCII string. Negative numbers
2464 * @param $hex Hexadecimal string
2465 * @return $asc An ASCII string
2467 protected function hex2asc ($hex) {
2468 // Check for length, it must be devideable by 2
2469 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2470 assert((strlen($hex) % 2) == 0);
2474 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2475 // Get the decimal number of the chunk
2476 $part = hexdec(substr($hex, $idx, 2));
2478 // Add it to the final string
2482 // Return the final string
2487 * Checks whether the given encoded data was encoded with Base64
2489 * @param $encodedData Encoded data we shall check
2490 * @return $isBase64 Whether the encoded data is Base64
2492 protected function isBase64Encoded ($encodedData) {
2494 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2501 * "Getter" to get response/request type from analysis of the system.
2503 * @return $responseType Analyzed response type
2505 protected static function getResponseTypeFromSystem () {
2506 // Default is console
2507 $responseType = 'console';
2509 // Is 'HTTP_HOST' set?
2510 if (isset($_SERVER['HTTP_HOST'])) {
2512 * Then it is a HTML response/request as RSS and so on may be
2513 * transfered over HTTP as well.
2515 $responseType = 'html';
2519 return $responseType;
2523 * Gets a cache key from Criteria instance
2525 * @param $criteriaInstance An instance of a Criteria class
2526 * @param $onlyKeys Only use these keys for a cache key
2527 * @return $cacheKey A cache key suitable for lookup/storage purposes
2529 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2531 $cacheKey = sprintf('%s@%s',
2532 $this->__toString(),
2533 $criteriaInstance->getCacheKey($onlyKeys)
2537 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2542 * Getter for startup time in miliseconds
2544 * @return $startupTime Startup time in miliseconds
2546 protected function getStartupTime () {
2547 return self::$startupTime;
2551 * "Getter" for a printable currently execution time in nice braces
2553 * @return $executionTime Current execution time in nice braces
2555 protected function getPrintableExecutionTime () {
2556 // Caculate the execution time
2557 $executionTime = microtime(TRUE) - $this->getStartupTime();
2559 // Pack it in nice braces
2560 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2563 return $executionTime;
2567 * Hashes a given string with a simple but stronger hash function (no salt)
2568 * and hex-encode it.
2570 * @param $str The string to be hashed
2571 * @return $hash The hash from string $str
2573 public static final function hash ($str) {
2574 // Hash given string with (better secure) hasher
2575 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2582 * "Getter" for length of hash() output. This will be "cached" to speed up
2585 * @return $length Length of hash() output
2587 public static final function getHashLength () {
2589 if (is_null(self::$hashLength)) {
2590 // No, then hash a string and save its length.
2591 self::$hashLength = strlen(self::hash('abc123'));
2595 return self::$hashLength;
2599 * Checks whether the given number is really a number (only chars 0-9).
2601 * @param $num A string consisting only chars between 0 and 9
2602 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2603 * @param $assertMismatch Whether to assert mismatches
2604 * @return $ret The (hopefully) secured numbered value
2606 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2607 // Filter all numbers out
2608 $ret = preg_replace('/[^0123456789]/', '', $num);
2611 if ($castValue === TRUE) {
2612 // Cast to biggest numeric type
2613 $ret = (double) $ret;
2616 // Assert only if requested
2617 if ($assertMismatch === TRUE) {
2618 // Has the whole value changed?
2619 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2627 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2629 * @param $num A string consisting only chars between 0 and 9
2630 * @param $assertMismatch Whether to assert mismatches
2631 * @return $ret The (hopefully) secured hext-numbered value
2633 public function hexval ($num, $assertMismatch = FALSE) {
2634 // Filter all numbers out
2635 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2637 // Assert only if requested
2638 if ($assertMismatch === TRUE) {
2639 // Has the whole value changed?
2640 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2648 * Checks whether start/end marker are set
2650 * @param $data Data to be checked
2651 * @return $isset Whether start/end marker are set
2653 public final function ifStartEndMarkersSet ($data) {
2655 $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));
2657 // ... and return it
2662 * Determines if an element is set in the generic array
2664 * @param $keyGroup Main group for the key
2665 * @param $subGroup Sub group for the key
2666 * @param $key Key to check
2667 * @param $element Element to check
2668 * @return $isset Whether the given key is set
2670 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2672 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2675 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2681 * Determines if a key is set in the generic array
2683 * @param $keyGroup Main group for the key
2684 * @param $subGroup Sub group for the key
2685 * @param $key Key to check
2686 * @return $isset Whether the given key is set
2688 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2690 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2693 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2701 * Determines if a group is set in the generic array
2703 * @param $keyGroup Main group
2704 * @param $subGroup Sub group
2705 * @return $isset Whether the given group is set
2707 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2709 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2712 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2719 * Getter for sub key group
2721 * @param $keyGroup Main key group
2722 * @param $subGroup Sub key group
2723 * @return $array An array with all array elements
2725 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2727 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2728 // No, then abort here
2729 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2734 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2737 return $this->genericArray[$keyGroup][$subGroup];
2741 * Unsets a given key in generic array
2743 * @param $keyGroup Main group for the key
2744 * @param $subGroup Sub group for the key
2745 * @param $key Key to unset
2748 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2750 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2753 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2757 * Unsets a given element in generic array
2759 * @param $keyGroup Main group for the key
2760 * @param $subGroup Sub group for the key
2761 * @param $key Key to unset
2762 * @param $element Element to unset
2765 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2767 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2770 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2774 * Append a string to a given generic array key
2776 * @param $keyGroup Main group for the key
2777 * @param $subGroup Sub group for the key
2778 * @param $key Key to unset
2779 * @param $value Value to add/append
2782 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2784 //* 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);
2786 // Is it already there?
2787 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2789 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2792 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2797 * Append a string to a given generic array element
2799 * @param $keyGroup Main group for the key
2800 * @param $subGroup Sub group for the key
2801 * @param $key Key to unset
2802 * @param $element Element to check
2803 * @param $value Value to add/append
2806 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2808 //* 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);
2810 // Is it already there?
2811 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2813 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2816 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2821 * Sets a string in a given generic array element
2823 * @param $keyGroup Main group for the key
2824 * @param $subGroup Sub group for the key
2825 * @param $key Key to unset
2826 * @param $element Element to check
2827 * @param $value Value to add/append
2830 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2832 //* 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);
2835 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2839 * Initializes given generic array group
2841 * @param $keyGroup Main group for the key
2842 * @param $subGroup Sub group for the key
2843 * @param $key Key to use
2844 * @param $forceInit Optionally force initialization
2847 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2849 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2851 // Is it already set?
2852 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2853 // Already initialized
2854 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2859 $this->genericArray[$keyGroup][$subGroup] = array();
2863 * Initializes given generic array key
2865 * @param $keyGroup Main group for the key
2866 * @param $subGroup Sub group for the key
2867 * @param $key Key to use
2868 * @param $forceInit Optionally force initialization
2871 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2873 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2875 // Is it already set?
2876 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2877 // Already initialized
2878 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2883 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2887 * Initializes given generic array element
2889 * @param $keyGroup Main group for the key
2890 * @param $subGroup Sub group for the key
2891 * @param $key Key to use
2892 * @param $element Element to use
2893 * @param $forceInit Optionally force initialization
2896 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2898 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2900 // Is it already set?
2901 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2902 // Already initialized
2903 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2908 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2912 * Pushes an element to a generic key
2914 * @param $keyGroup Main group for the key
2915 * @param $subGroup Sub group for the key
2916 * @param $key Key to use
2917 * @param $value Value to add/append
2918 * @return $count Number of array elements
2920 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2922 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2925 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2927 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2931 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2934 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2935 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2940 * Pushes an element to a generic array element
2942 * @param $keyGroup Main group for the key
2943 * @param $subGroup Sub group for the key
2944 * @param $key Key to use
2945 * @param $element Element to check
2946 * @param $value Value to add/append
2947 * @return $count Number of array elements
2949 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2951 //* 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));
2954 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2956 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2960 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2963 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2964 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2969 * Pops an element from a generic group
2971 * @param $keyGroup Main group for the key
2972 * @param $subGroup Sub group for the key
2973 * @param $key Key to unset
2974 * @return $value Last "popped" value
2976 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2978 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2981 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2983 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2988 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2991 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2992 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2997 * Shifts an element from a generic group
2999 * @param $keyGroup Main group for the key
3000 * @param $subGroup Sub group for the key
3001 * @param $key Key to unset
3002 * @return $value Last "popped" value
3004 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3006 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3009 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3011 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3016 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3019 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3020 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3025 * Count generic array group
3027 * @param $keyGroup Main group for the key
3028 * @return $count Count of given group
3030 protected final function countGenericArray ($keyGroup) {
3032 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3035 if (!isset($this->genericArray[$keyGroup])) {
3037 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3042 $count = count($this->genericArray[$keyGroup]);
3045 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3052 * Count generic array sub group
3054 * @param $keyGroup Main group for the key
3055 * @param $subGroup Sub group for the key
3056 * @return $count Count of given group
3058 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3060 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3063 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3065 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3070 $count = count($this->genericArray[$keyGroup][$subGroup]);
3073 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3080 * Count generic array elements
3082 * @param $keyGroup Main group for the key
3083 * @param $subGroup Sub group for the key
3084 * @para $key Key to count
3085 * @return $count Count of given key
3087 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3089 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3092 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3094 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3096 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3098 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3103 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3106 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3113 * Getter for whole generic group array
3115 * @param $keyGroup Key group to get
3116 * @return $array Whole generic array group
3118 protected final function getGenericArray ($keyGroup) {
3120 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3123 if (!isset($this->genericArray[$keyGroup])) {
3125 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3130 return $this->genericArray[$keyGroup];
3134 * Setter for generic array key
3136 * @param $keyGroup Key group to get
3137 * @param $subGroup Sub group for the key
3138 * @param $key Key to unset
3139 * @param $value Mixed value from generic array element
3142 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3144 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3147 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3151 * Getter for generic array key
3153 * @param $keyGroup Key group to get
3154 * @param $subGroup Sub group for the key
3155 * @param $key Key to unset
3156 * @return $value Mixed value from generic array element
3158 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3160 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3163 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3165 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3170 return $this->genericArray[$keyGroup][$subGroup][$key];
3174 * Sets a value in given generic array key/element
3176 * @param $keyGroup Main group for the key
3177 * @param $subGroup Sub group for the key
3178 * @param $key Key to set
3179 * @param $element Element to set
3180 * @param $value Value to set
3183 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3185 //* 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));
3188 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3192 * Getter for generic array element
3194 * @param $keyGroup Key group to get
3195 * @param $subGroup Sub group for the key
3196 * @param $key Key to look for
3197 * @param $element Element to look for
3198 * @return $value Mixed value from generic array element
3200 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3202 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3205 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3207 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3212 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3216 * Checks if a given sub group is valid (array)
3218 * @param $keyGroup Key group to get
3219 * @param $subGroup Sub group for the key
3220 * @return $isValid Whether given sub group is valid
3222 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3224 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3227 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3234 * Checks if a given key is valid (array)
3236 * @param $keyGroup Key group to get
3237 * @param $subGroup Sub group for the key
3238 * @param $key Key to check
3239 * @return $isValid Whether given sub group is valid
3241 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3243 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3246 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3253 * Initializes the web output instance
3257 protected function initWebOutputInstance () {
3258 // Get application instance
3259 $applicationInstance = Registry::getRegistry()->getInstance('app');
3261 // Is this a response instance?
3262 if ($this instanceof Responseable) {
3263 // Then set it in application instance
3264 $applicationInstance->setResponseInstance($this);
3267 // Init web output instance
3268 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3271 $this->setWebOutputInstance($outputInstance);
3275 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3277 * @param $boolean Boolean value
3278 * @return $translated Translated boolean value
3280 public static final function translateBooleanToYesNo ($boolean) {
3281 // Make sure it is really boolean
3282 assert(is_bool($boolean));
3285 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3287 // ... and return it
3292 * Encodes raw data (almost any type) by "serializing" it and then pack it
3293 * into a "binary format".
3295 * @param $rawData Raw data (almost any type)
3296 * @return $encoded Encoded data
3298 protected function encodeData ($rawData) {
3299 // Make sure no objects or resources pass through
3300 assert(!is_object($rawData));
3301 assert(!is_resource($rawData));
3303 // First "serialize" it (json_encode() is faster than serialize())
3304 $encoded = $this->packString(json_encode($rawData));
3311 * Pack a string into a "binary format". Please execuse me that this is
3312 * widely undocumented. :-(
3314 * @param $str Unpacked string
3315 * @return $packed Packed string
3316 * @todo Improve documentation
3318 protected function packString ($str) {
3320 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3322 // First compress the string (gzcompress is okay)
3323 $str = gzcompress($str);
3328 // And start the "encoding" loop
3329 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3331 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3332 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3334 if (($idx + $i) <= strlen($str)) {
3335 $ord = ord(substr($str, ($idx + $i), 1));
3337 $add = $ord * pow(256, $factor);
3341 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3345 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3346 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3348 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3349 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3355 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3360 * Checks whether the given file/path is in open_basedir(). This does not
3361 * gurantee that the file is actually readable and/or writeable. If you need
3362 * such gurantee then please use isReadableFile() instead.
3364 * @param $filePathName Name of the file/path to be checked
3365 * @return $isReachable Whether it is within open_basedir()
3367 protected static function isReachableFilePath ($filePathName) {
3368 // Is not reachable by default
3369 $isReachable = FALSE;
3371 // Get open_basedir parameter
3372 $openBaseDir = ini_get('open_basedir');
3375 if (!empty($openBaseDir)) {
3376 // Check all entries
3377 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3378 // Check on existence
3379 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3381 $isReachable = TRUE;
3385 // If open_basedir is not set, all is allowed
3386 $isReachable = TRUE;
3390 return $isReachable;
3394 * Checks whether the give file is within open_basedir() (done by
3395 * isReachableFilePath()), is actually a file and is readable.
3397 * @param $fileName Name of the file to be checked
3398 * @return $isReadable Whether the file is readable (and therefor exists)
3400 public static function isReadableFile ($fileName) {
3401 // Default is not readable
3402 $isReadable = FALSE;
3404 // Is within parameters, so check if it is a file and readable
3405 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3412 * Creates a full-qualified file name (FQFN) for given file name by adding
3413 * a configured temporary file path to it.
3415 * @param $fileName Name for temporary file
3416 * @return $fqfn Full-qualified file name
3417 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3418 * @throws FileIoException If the file cannot be written
3420 protected static function createTempPathForFile ($fileName) {
3422 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3424 // Is the path writeable?
3425 if (!is_writable($basePath)) {
3426 // Path is write-protected
3427 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3431 $fqfn = $basePath . '/' . $fileName;
3434 if (!self::isReachableFilePath($fqfn)) {
3436 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3444 * "Getter" for a printable state name
3446 * @return $stateName Name of the node's state in a printable format
3448 public final function getPrintableState () {
3449 // Default is 'null'
3450 $stateName = 'null';
3452 // Get the state instance
3453 $stateInstance = $this->getStateInstance();
3455 // Is it an instance of Stateable?
3456 if ($stateInstance instanceof Stateable) {
3457 // Then use that state name
3458 $stateName = $stateInstance->getStateName();
3466 * Handles socket error for given socket resource and peer data. This method
3467 * validates $socketResource if it is a valid resource (see is_resource())
3468 * but assumes valid data in array $recipientData, except that
3469 * count($recipientData) is always 2.
3471 * @param $method Value of __METHOD__ from calling method
3472 * @param $line Value of __LINE__ from calling method
3473 * @param $socketResource A valid socket resource
3474 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3476 * @throws InvalidSocketException If $socketResource is no socket resource
3477 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3478 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3480 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3481 // This method handles only socket resources
3482 if (!is_resource($socketResource)) {
3483 // No resource, abort here
3484 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3487 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3488 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3489 assert(isset($socketData[0]));
3490 assert(isset($socketData[1]));
3492 // Get error code for first validation (0 is not an error)
3493 $errorCode = socket_last_error($socketResource);
3495 // If the error code is zero, someone called this method without an error
3496 if ($errorCode == 0) {
3497 // No error detected (or previously cleared outside this method)
3498 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3501 // Get handler (method) name
3502 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3504 // Call-back the error handler method
3505 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3507 // Finally clear the error because it has been handled
3508 socket_clear_error($socketResource);