3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Compressor\Compressor;
7 use CoreFramework\Configuration\FrameworkConfiguration;
8 use CoreFramework\Connection\Database\DatabaseConnection;
9 use CoreFramework\Controller\Controller;
10 use CoreFramework\Criteria\Criteria;
11 use CoreFramework\Criteria\Local\LocalSearchCriteria;
12 use CoreFramework\Criteria\Local\LocalUpdateCriteria;
13 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
14 use CoreFramework\Factory\ObjectFactory;
15 use CoreFramework\Filesystem\FrameworkDirectory;
16 use CoreFramework\Generic\FrameworkInterface;
17 use CoreFramework\Generic\NullPointerException;
18 use CoreFramework\Handler\Stream\IoHandler;
19 use CoreFramework\Loader\ClassLoader;
20 use CoreFramework\Manager\ManageableApplication;
21 use CoreFramework\Middleware\Compressor\CompressorChannel;
22 use CoreFramework\Middleware\Debug\DebugMiddleware;
23 use CoreFramework\Parser\Parseable;
24 use CoreFramework\Registry\Register;
25 use CoreFramework\Registry\Registry;
26 use CoreFramework\Request\Requestable;
27 use CoreFramework\Resolver\Resolver;
28 use CoreFramework\Result\Database\CachedDatabaseResult;
29 use CoreFramework\Result\Search\SearchableResult;
30 use CoreFramework\Response\Responseable;
31 use CoreFramework\Stream\Output\OutputStreamer;
32 use CoreFramework\Template\CompileableTemplate;
33 use CoreFramework\User\ManageableAccount;
34 use CoreFramework\Wrapper\Database\DatabaseWrapper;
41 * The simulator system class is the super class of all other classes. This
42 * class handles saving of games etc.
44 * @author Roland Haeder <webmaster@shipsimu.org>
46 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
47 * @license GNU GPL 3.0 or any newer version
48 * @link http://www.shipsimu.org
50 * This program is free software: you can redistribute it and/or modify
51 * it under the terms of the GNU General Public License as published by
52 * the Free Software Foundation, either version 3 of the License, or
53 * (at your option) any later version.
55 * This program is distributed in the hope that it will be useful,
56 * but WITHOUT ANY WARRANTY; without even the implied warranty of
57 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
58 * GNU General Public License for more details.
60 * You should have received a copy of the GNU General Public License
61 * along with this program. If not, see <http://www.gnu.org/licenses/>.
63 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
65 * Length of output from hash()
67 private static $hashLength = NULL;
72 private $realClass = 'BaseFrameworkSystem';
75 * Instance of a Requestable class
77 private $requestInstance = NULL;
80 * Instance of a Responseable class
82 private $responseInstance = NULL;
85 * Search criteria instance
87 private $searchInstance = NULL;
90 * Update criteria instance
92 private $updateInstance = NULL;
95 * The file I/O instance for the template loader
97 private $fileIoInstance = NULL;
102 private $resolverInstance = NULL;
105 * Template engine instance
107 private $templateInstance = NULL;
110 * Database result instance
112 private $resultInstance = NULL;
115 * Instance for user class
117 private $userInstance = NULL;
120 * A controller instance
122 private $controllerInstance = NULL;
127 private $rngInstance = NULL;
130 * Instance of a crypto helper
132 private $cryptoInstance = NULL;
135 * Instance of an Iterator class
137 private $iteratorInstance = NULL;
140 * Instance of the list
142 private $listInstance = NULL;
147 private $menuInstance = NULL;
150 * Instance of the image
152 private $imageInstance = NULL;
155 * Instance of the stacker
157 private $stackInstance = NULL;
160 * A Compressor instance
162 private $compressorInstance = NULL;
165 * A Parseable instance
167 private $parserInstance = NULL;
170 * A HandleableProtocol instance
172 private $protocolInstance = NULL;
175 * A database wrapper instance
177 private $databaseInstance = NULL;
180 * A helper instance for the form
182 private $helperInstance = NULL;
185 * An instance of a Source class
187 private $sourceInstance = NULL;
190 * An instance of a UrlSource class
192 private $urlSourceInstance = NULL;
195 * An instance of a InputStream class
197 private $inputStreamInstance = NULL;
200 * An instance of a OutputStream class
202 private $outputStreamInstance = NULL;
205 * Networkable handler instance
207 private $handlerInstance = NULL;
210 * Visitor handler instance
212 private $visitorInstance = NULL;
217 private $dhtInstance = NULL;
220 * An instance of a database wrapper class
222 private $wrapperInstance = NULL;
225 * An instance of a file I/O pointer class (not handler)
227 private $pointerInstance = NULL;
230 * An instance of an Indexable class
232 private $indexInstance = NULL;
235 * An instance of a Block class
237 private $blockInstance = NULL;
242 private $minableInstance = NULL;
245 * A FrameworkDirectory instance
247 private $directoryInstance = NULL;
252 private $listenerInstance = NULL;
255 * An instance of a communicator
257 private $communicatorInstance = NULL;
260 * The concrete output instance
262 private $outputInstance = NULL;
267 private $stateInstance = NULL;
270 * Thousands separator
272 private $thousands = '.'; // German
277 private $decimals = ','; // German
282 private $socketResource = FALSE;
285 * Regular expression to use for validation
287 private $regularExpression = '';
292 private $packageData = array();
297 private $genericArray = array();
302 private $commandName = '';
307 private $controllerName = '';
310 * Name of used protocol
312 private $protocolName = 'invalid';
315 * Array with bitmasks and such for pack/unpack methods to support both
316 * 32-bit and 64-bit systems
318 private $packingData = array(
321 'left' => 0xffff0000,
322 'right' => 0x0000ffff,
328 'left' => 0xffffffff00000000,
329 'right' => 0x00000000ffffffff,
336 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
338 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
340 private $archArrayElement = FALSE;
342 /***********************
343 * Exception codes.... *
344 ***********************/
346 // @todo Try to clean these constants up
347 const EXCEPTION_IS_NULL_POINTER = 0x001;
348 const EXCEPTION_IS_NO_OBJECT = 0x002;
349 const EXCEPTION_IS_NO_ARRAY = 0x003;
350 const EXCEPTION_MISSING_METHOD = 0x004;
351 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
352 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
353 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
354 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
355 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
356 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
357 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
358 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
359 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
360 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
361 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
362 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
363 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
364 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
365 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
366 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
367 const EXCEPTION_PATH_NOT_FOUND = 0x015;
368 const EXCEPTION_INVALID_PATH_NAME = 0x016;
369 const EXCEPTION_READ_PROTECED_PATH = 0x017;
370 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
371 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
372 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
373 const EXCEPTION_INVALID_RESOURCE = 0x01b;
374 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
375 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
376 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
377 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
378 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
379 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
380 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
381 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
382 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
383 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
384 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
385 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
386 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
387 const EXCEPTION_INVALID_STRING = 0x029;
388 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
389 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
390 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
391 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
392 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
393 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
394 const EXCEPTION_MISSING_ELEMENT = 0x030;
395 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
396 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
397 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
398 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
399 const EXCEPTION_FATAL_ERROR = 0x035;
400 const EXCEPTION_FILE_NOT_FOUND = 0x036;
401 const EXCEPTION_ASSERTION_FAILED = 0x037;
402 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
403 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
404 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
405 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
406 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
407 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
410 * Hexadecimal->Decimal translation array
412 private static $hexdec = array(
432 * Decimal->hexadecimal translation array
434 private static $dechex = array(
454 * Startup time in miliseconds
456 private static $startupTime = 0;
459 * Protected super constructor
461 * @param $className Name of the class
464 protected function __construct ($className) {
466 $this->setRealClass($className);
468 // Set configuration instance if no registry ...
469 if (!$this instanceof Register) {
470 // ... because registries doesn't need to be configured
471 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
474 // Is the startup time set? (0 cannot be TRUE anymore)
475 if (self::$startupTime == 0) {
477 self::$startupTime = microtime(TRUE);
481 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
485 * Destructor for all classes. You should not call this method on your own.
489 public function __destruct () {
490 // Flush any updated entries to the database
491 $this->flushPendingUpdates();
493 // Is this object already destroyed?
494 if ($this->__toString() != 'DestructedObject') {
495 // Destroy all informations about this class but keep some text about it alive
496 $this->setRealClass('DestructedObject');
497 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
498 // Already destructed object
499 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
504 // Do not call this twice
505 trigger_error(__METHOD__ . ': Called twice.');
511 * The __call() method where all non-implemented methods end up
513 * @param $methodName Name of the missing method
514 * @args $args Arguments passed to the method
517 public final function __call ($methodName, $args) {
518 return self::__callStatic($methodName, $args);
522 * The __callStatic() method where all non-implemented static methods end up
524 * @param $methodName Name of the missing method
525 * @args $args Arguments passed to the method
528 public static final function __callStatic ($methodName, $args) {
530 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
532 // Init argument string
535 // Is it NULL, empty or an array?
536 if (is_null($args)) {
538 $argsString = 'NULL';
539 } elseif (is_array($args)) {
543 // Some arguments are there
544 foreach ($args as $arg) {
545 // Add data about the argument
546 $argsString .= gettype($arg) . ':';
549 // Found a NULL argument
550 $argsString .= 'NULL';
551 } elseif (is_string($arg)) {
552 // Add length for strings
553 $argsString .= strlen($arg);
554 } elseif ((is_int($arg)) || (is_float($arg))) {
557 } elseif (is_array($arg)) {
558 // .. or size if array
559 $argsString .= count($arg);
560 } elseif (is_object($arg)) {
562 $reflection = new ReflectionClass($arg);
564 // Is an other object, maybe no __toString() available
565 $argsString .= $reflection->getName();
566 } elseif ($arg === TRUE) {
567 // ... is boolean 'TRUE'
568 $argsString .= 'TRUE';
569 } elseif ($arg === FALSE) {
570 // ... is boolean 'FALSE'
571 $argsString .= 'FALSE';
574 // Comma for next one
579 if (substr($argsString, -2, 1) == ',') {
580 $argsString = substr($argsString, 0, -2);
586 // Invalid arguments!
587 $argsString = '!INVALID:' . gettype($args) . '!';
590 // Output stub message
591 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
592 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
602 * Getter for $realClass
604 * @return $realClass The name of the real class (not BaseFrameworkSystem)
606 public function __toString () {
607 return $this->realClass;
611 * Magic method to catch setting of missing but set class fields/attributes
613 * @param $name Name of the field/attribute
614 * @param $value Value to store
617 public final function __set ($name, $value) {
618 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
621 print_r($value, TRUE)
626 * Magic method to catch getting of missing fields/attributes
628 * @param $name Name of the field/attribute
631 public final function __get ($name) {
632 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
638 * Magic method to catch unsetting of missing fields/attributes
640 * @param $name Name of the field/attribute
643 public final function __unset ($name) {
644 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
650 * Magic method to catch object serialization
652 * @return $unsupported Unsupported method
653 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
655 public final function __sleep () {
656 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
660 * Magic method to catch object deserialization
662 * @return $unsupported Unsupported method
663 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
665 public final function __wakeup () {
666 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
670 * Magic method to catch calls when an object instance is called
672 * @return $unsupported Unsupported method
673 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
675 public final function __invoke () {
676 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
680 * Setter for the real class name
682 * @param $realClass Class name (string)
685 public final function setRealClass ($realClass) {
687 $this->realClass = (string) $realClass;
691 * Setter for database result instance
693 * @param $resultInstance An instance of a database result class
695 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
697 protected final function setResultInstance (SearchableResult $resultInstance) {
698 $this->resultInstance = $resultInstance;
702 * Getter for database result instance
704 * @return $resultInstance An instance of a database result class
706 public final function getResultInstance () {
707 return $this->resultInstance;
711 * Setter for template engine instances
713 * @param $templateInstance An instance of a template engine class
716 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
717 $this->templateInstance = $templateInstance;
721 * Getter for template engine instances
723 * @return $templateInstance An instance of a template engine class
725 protected final function getTemplateInstance () {
726 return $this->templateInstance;
730 * Setter for search instance
732 * @param $searchInstance Searchable criteria instance
735 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
736 $this->searchInstance = $searchInstance;
740 * Getter for search instance
742 * @return $searchInstance Searchable criteria instance
744 public final function getSearchInstance () {
745 return $this->searchInstance;
749 * Setter for update instance
751 * @param $updateInstance An instance of a LocalUpdateCriteria clase
754 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
755 $this->updateInstance = $updateInstance;
759 * Getter for update instance
761 * @return $updateInstance Updateable criteria instance
763 public final function getUpdateInstance () {
764 return $this->updateInstance;
768 * Setter for resolver instance
770 * @param $resolverInstance Instance of a command resolver class
773 public final function setResolverInstance (Resolver $resolverInstance) {
774 $this->resolverInstance = $resolverInstance;
778 * Getter for resolver instance
780 * @return $resolverInstance Instance of a command resolver class
782 public final function getResolverInstance () {
783 return $this->resolverInstance;
787 * Setter for language instance
789 * @param $configInstance The configuration instance which shall
790 * be FrameworkConfiguration
793 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
794 Registry::getRegistry()->addInstance('config', $configInstance);
798 * Getter for configuration instance
800 * @return $configInstance Configuration instance
802 public final function getConfigInstance () {
803 $configInstance = Registry::getRegistry()->getInstance('config');
804 return $configInstance;
808 * Setter for debug instance
810 * @param $debugInstance The instance for debug output class
813 public final function setDebugInstance (DebugMiddleware $debugInstance) {
814 Registry::getRegistry()->addInstance('debug', $debugInstance);
818 * Getter for debug instance
820 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
822 public final function getDebugInstance () {
823 // Get debug instance
824 $debugInstance = Registry::getRegistry()->getInstance('debug');
827 return $debugInstance;
831 * Setter for web output instance
833 * @param $webInstance The instance for web output class
836 public final function setWebOutputInstance (OutputStreamer $webInstance) {
837 Registry::getRegistry()->addInstance('web_output', $webInstance);
841 * Getter for web output instance
843 * @return $webOutputInstance - Instance to class WebOutput
845 public final function getWebOutputInstance () {
846 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
847 return $webOutputInstance;
851 * Setter for database instance
853 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
856 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
857 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
861 * Getter for database layer
863 * @return $databaseInstance The database layer instance
865 public final function getDatabaseInstance () {
867 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
870 return $databaseInstance;
874 * Setter for compressor channel
876 * @param $compressorInstance An instance of CompressorChannel
879 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
880 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
884 * Getter for compressor channel
886 * @return $compressorInstance The compressor channel
888 public final function getCompressorChannel () {
889 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
890 return $compressorInstance;
894 * Protected getter for a manageable application helper class
896 * @return $applicationInstance An instance of a manageable application helper class
898 protected final function getApplicationInstance () {
899 $applicationInstance = Registry::getRegistry()->getInstance('application');
900 return $applicationInstance;
904 * Setter for a manageable application helper class
906 * @param $applicationInstance An instance of a manageable application helper class
909 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
910 Registry::getRegistry()->addInstance('application', $applicationInstance);
914 * Setter for request instance
916 * @param $requestInstance An instance of a Requestable class
919 public final function setRequestInstance (Requestable $requestInstance) {
920 $this->requestInstance = $requestInstance;
924 * Getter for request instance
926 * @return $requestInstance An instance of a Requestable class
928 public final function getRequestInstance () {
929 return $this->requestInstance;
933 * Setter for response instance
935 * @param $responseInstance An instance of a Responseable class
938 public final function setResponseInstance (Responseable $responseInstance) {
939 $this->responseInstance = $responseInstance;
943 * Getter for response instance
945 * @return $responseInstance An instance of a Responseable class
947 public final function getResponseInstance () {
948 return $this->responseInstance;
952 * Private getter for language instance
954 * @return $langInstance An instance to the language sub-system
956 protected final function getLanguageInstance () {
957 $langInstance = Registry::getRegistry()->getInstance('language');
958 return $langInstance;
962 * Setter for language instance
964 * @param $langInstance An instance to the language sub-system
966 * @see LanguageSystem
968 public final function setLanguageInstance (ManageableLanguage $langInstance) {
969 Registry::getRegistry()->addInstance('language', $langInstance);
973 * Private getter for file IO instance
975 * @return $fileIoInstance An instance to the file I/O sub-system
977 protected final function getFileIoInstance () {
978 return $this->fileIoInstance;
982 * Setter for file I/O instance
984 * @param $fileIoInstance An instance to the file I/O sub-system
987 public final function setFileIoInstance (IoHandler $fileIoInstance) {
988 $this->fileIoInstance = $fileIoInstance;
992 * Protected setter for user instance
994 * @param $userInstance An instance of a user class
997 protected final function setUserInstance (ManageableAccount $userInstance) {
998 $this->userInstance = $userInstance;
1002 * Getter for user instance
1004 * @return $userInstance An instance of a user class
1006 public final function getUserInstance () {
1007 return $this->userInstance;
1011 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1013 * @param $controllerInstance An instance of the controller
1016 public final function setControllerInstance (Controller $controllerInstance) {
1017 $this->controllerInstance = $controllerInstance;
1021 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1023 * @return $controllerInstance An instance of the controller
1025 public final function getControllerInstance () {
1026 return $this->controllerInstance;
1030 * Setter for RNG instance
1032 * @param $rngInstance An instance of a random number generator (RNG)
1035 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1036 $this->rngInstance = $rngInstance;
1040 * Getter for RNG instance
1042 * @return $rngInstance An instance of a random number generator (RNG)
1044 public final function getRngInstance () {
1045 return $this->rngInstance;
1049 * Setter for Cryptable instance
1051 * @param $cryptoInstance An instance of a Cryptable class
1054 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1055 $this->cryptoInstance = $cryptoInstance;
1059 * Getter for Cryptable instance
1061 * @return $cryptoInstance An instance of a Cryptable class
1063 public final function getCryptoInstance () {
1064 return $this->cryptoInstance;
1068 * Setter for the list instance
1070 * @param $listInstance A list of Listable
1073 protected final function setListInstance (Listable $listInstance) {
1074 $this->listInstance = $listInstance;
1078 * Getter for the list instance
1080 * @return $listInstance A list of Listable
1082 protected final function getListInstance () {
1083 return $this->listInstance;
1087 * Setter for the menu instance
1089 * @param $menuInstance A RenderableMenu instance
1092 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1093 $this->menuInstance = $menuInstance;
1097 * Getter for the menu instance
1099 * @return $menuInstance A RenderableMenu instance
1101 protected final function getMenuInstance () {
1102 return $this->menuInstance;
1106 * Setter for image instance
1108 * @param $imageInstance An instance of an image
1111 public final function setImageInstance (BaseImage $imageInstance) {
1112 $this->imageInstance = $imageInstance;
1116 * Getter for image instance
1118 * @return $imageInstance An instance of an image
1120 public final function getImageInstance () {
1121 return $this->imageInstance;
1125 * Setter for stacker instance
1127 * @param $stackInstance An instance of an stacker
1130 public final function setStackInstance (Stackable $stackInstance) {
1131 $this->stackInstance = $stackInstance;
1135 * Getter for stacker instance
1137 * @return $stackInstance An instance of an stacker
1139 public final function getStackInstance () {
1140 return $this->stackInstance;
1144 * Setter for compressor instance
1146 * @param $compressorInstance An instance of an compressor
1149 public final function setCompressorInstance (Compressor $compressorInstance) {
1150 $this->compressorInstance = $compressorInstance;
1154 * Getter for compressor instance
1156 * @return $compressorInstance An instance of an compressor
1158 public final function getCompressorInstance () {
1159 return $this->compressorInstance;
1163 * Setter for Parseable instance
1165 * @param $parserInstance An instance of an Parseable
1168 public final function setParserInstance (Parseable $parserInstance) {
1169 $this->parserInstance = $parserInstance;
1173 * Getter for Parseable instance
1175 * @return $parserInstance An instance of an Parseable
1177 public final function getParserInstance () {
1178 return $this->parserInstance;
1182 * Setter for HandleableProtocol instance
1184 * @param $protocolInstance An instance of an HandleableProtocol
1187 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1188 $this->protocolInstance = $protocolInstance;
1192 * Getter for HandleableProtocol instance
1194 * @return $protocolInstance An instance of an HandleableProtocol
1196 public final function getProtocolInstance () {
1197 return $this->protocolInstance;
1201 * Setter for DatabaseWrapper instance
1203 * @param $wrapperInstance An instance of an DatabaseWrapper
1206 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1207 $this->wrapperInstance = $wrapperInstance;
1211 * Getter for DatabaseWrapper instance
1213 * @return $wrapperInstance An instance of an DatabaseWrapper
1215 public final function getWrapperInstance () {
1216 return $this->wrapperInstance;
1220 * Setter for socket resource
1222 * @param $socketResource A valid socket resource
1225 public final function setSocketResource ($socketResource) {
1226 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1227 $this->socketResource = $socketResource;
1231 * Getter for socket resource
1233 * @return $socketResource A valid socket resource
1235 public final function getSocketResource () {
1236 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1237 return $this->socketResource;
1241 * Setter for regular expression
1243 * @param $regularExpression A valid regular expression
1246 public final function setRegularExpression ($regularExpression) {
1247 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1248 $this->regularExpression = $regularExpression;
1252 * Getter for regular expression
1254 * @return $regularExpression A valid regular expression
1256 public final function getRegularExpression () {
1257 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1258 return $this->regularExpression;
1262 * Setter for helper instance
1264 * @param $helperInstance An instance of a helper class
1267 protected final function setHelperInstance (Helper $helperInstance) {
1268 $this->helperInstance = $helperInstance;
1272 * Getter for helper instance
1274 * @return $helperInstance An instance of a helper class
1276 public final function getHelperInstance () {
1277 return $this->helperInstance;
1281 * Setter for a Source instance
1283 * @param $sourceInstance An instance of a Source class
1286 protected final function setSourceInstance (Source $sourceInstance) {
1287 $this->sourceInstance = $sourceInstance;
1291 * Getter for a Source instance
1293 * @return $sourceInstance An instance of a Source class
1295 protected final function getSourceInstance () {
1296 return $this->sourceInstance;
1300 * Setter for a UrlSource instance
1302 * @param $sourceInstance An instance of a UrlSource class
1305 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1306 $this->urlSourceInstance = $urlSourceInstance;
1310 * Getter for a UrlSource instance
1312 * @return $urlSourceInstance An instance of a UrlSource class
1314 protected final function getUrlSourceInstance () {
1315 return $this->urlSourceInstance;
1319 * Getter for a InputStream instance
1321 * @param $inputStreamInstance The InputStream instance
1323 protected final function getInputStreamInstance () {
1324 return $this->inputStreamInstance;
1328 * Setter for a InputStream instance
1330 * @param $inputStreamInstance The InputStream instance
1333 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1334 $this->inputStreamInstance = $inputStreamInstance;
1338 * Getter for a OutputStream instance
1340 * @param $outputStreamInstance The OutputStream instance
1342 protected final function getOutputStreamInstance () {
1343 return $this->outputStreamInstance;
1347 * Setter for a OutputStream instance
1349 * @param $outputStreamInstance The OutputStream instance
1352 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1353 $this->outputStreamInstance = $outputStreamInstance;
1357 * Setter for handler instance
1359 * @param $handlerInstance An instance of a Handleable class
1362 protected final function setHandlerInstance (Handleable $handlerInstance) {
1363 $this->handlerInstance = $handlerInstance;
1367 * Getter for handler instance
1369 * @return $handlerInstance A Networkable instance
1371 protected final function getHandlerInstance () {
1372 return $this->handlerInstance;
1376 * Setter for visitor instance
1378 * @param $visitorInstance A Visitor instance
1381 protected final function setVisitorInstance (Visitor $visitorInstance) {
1382 $this->visitorInstance = $visitorInstance;
1386 * Getter for visitor instance
1388 * @return $visitorInstance A Visitor instance
1390 protected final function getVisitorInstance () {
1391 return $this->visitorInstance;
1395 * Setter for DHT instance
1397 * @param $dhtInstance A Distributable instance
1400 protected final function setDhtInstance (Distributable $dhtInstance) {
1401 $this->dhtInstance = $dhtInstance;
1405 * Getter for DHT instance
1407 * @return $dhtInstance A Distributable instance
1409 protected final function getDhtInstance () {
1410 return $this->dhtInstance;
1414 * Setter for raw package Data
1416 * @param $packageData Raw package Data
1419 public final function setPackageData (array $packageData) {
1420 $this->packageData = $packageData;
1424 * Getter for raw package Data
1426 * @return $packageData Raw package Data
1428 public function getPackageData () {
1429 return $this->packageData;
1434 * Setter for Iterator instance
1436 * @param $iteratorInstance An instance of an Iterator
1439 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1440 $this->iteratorInstance = $iteratorInstance;
1444 * Getter for Iterator instance
1446 * @return $iteratorInstance An instance of an Iterator
1448 public final function getIteratorInstance () {
1449 return $this->iteratorInstance;
1453 * Setter for FilePointer instance
1455 * @param $pointerInstance An instance of an FilePointer class
1458 protected final function setPointerInstance (FilePointer $pointerInstance) {
1459 $this->pointerInstance = $pointerInstance;
1463 * Getter for FilePointer instance
1465 * @return $pointerInstance An instance of an FilePointer class
1467 public final function getPointerInstance () {
1468 return $this->pointerInstance;
1472 * Unsets pointer instance which triggers a call of __destruct() if the
1473 * instance is still there. This is surely not fatal on already "closed"
1474 * file pointer instances.
1476 * I don't want to mess around with above setter by giving it a default
1477 * value NULL as setter should always explicitly only set (existing) object
1478 * instances and NULL is NULL.
1482 protected final function unsetPointerInstance () {
1483 // Simply it to NULL
1484 $this->pointerInstance = NULL;
1488 * Setter for Indexable instance
1490 * @param $indexInstance An instance of an Indexable class
1493 protected final function setIndexInstance (Indexable $indexInstance) {
1494 $this->indexInstance = $indexInstance;
1498 * Getter for Indexable instance
1500 * @return $indexInstance An instance of an Indexable class
1502 public final function getIndexInstance () {
1503 return $this->indexInstance;
1507 * Setter for Block instance
1509 * @param $blockInstance An instance of an Block class
1512 protected final function setBlockInstance (Block $blockInstance) {
1513 $this->blockInstance = $blockInstance;
1517 * Getter for Block instance
1519 * @return $blockInstance An instance of an Block class
1521 public final function getBlockInstance () {
1522 return $this->blockInstance;
1526 * Setter for Minable instance
1528 * @param $minableInstance A Minable instance
1531 protected final function setMinableInstance (Minable $minableInstance) {
1532 $this->minableInstance = $minableInstance;
1536 * Getter for minable instance
1538 * @return $minableInstance A Minable instance
1540 protected final function getMinableInstance () {
1541 return $this->minableInstance;
1545 * Setter for FrameworkDirectory instance
1547 * @param $directoryInstance A FrameworkDirectory instance
1550 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1551 $this->directoryInstance = $directoryInstance;
1555 * Getter for FrameworkDirectory instance
1557 * @return $directoryInstance A FrameworkDirectory instance
1559 protected final function getDirectoryInstance () {
1560 return $this->directoryInstance;
1564 * Setter for listener instance
1566 * @param $listenerInstance A Listenable instance
1569 protected final function setListenerInstance (Listenable $listenerInstance) {
1570 $this->listenerInstance = $listenerInstance;
1574 * Getter for listener instance
1576 * @return $listenerInstance A Listenable instance
1578 protected final function getListenerInstance () {
1579 return $this->listenerInstance;
1583 * Getter for communicator instance
1585 * @return $communicatorInstance An instance of a Communicator class
1587 public final function getCommunicatorInstance () {
1588 return $this->communicatorInstance;
1592 * Setter for communicator instance
1594 * @param $communicatorInstance An instance of a Communicator class
1597 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1598 $this->communicatorInstance = $communicatorInstance;
1602 * Setter for state instance
1604 * @param $stateInstance A Stateable instance
1607 public final function setStateInstance (Stateable $stateInstance) {
1608 $this->stateInstance = $stateInstance;
1612 * Getter for state instance
1614 * @return $stateInstance A Stateable instance
1616 public final function getStateInstance () {
1617 return $this->stateInstance;
1621 * Setter for output instance
1623 * @param $outputInstance The debug output instance
1626 public final function setOutputInstance (OutputStreamer $outputInstance) {
1627 $this->outputInstance = $outputInstance;
1631 * Getter for output instance
1633 * @return $outputInstance The debug output instance
1635 public final function getOutputInstance () {
1636 return $this->outputInstance;
1640 * Setter for command name
1642 * @param $commandName Last validated command name
1645 protected final function setCommandName ($commandName) {
1646 $this->commandName = $commandName;
1650 * Getter for command name
1652 * @return $commandName Last validated command name
1654 protected final function getCommandName () {
1655 return $this->commandName;
1659 * Setter for controller name
1661 * @param $controllerName Last validated controller name
1664 protected final function setControllerName ($controllerName) {
1665 $this->controllerName = $controllerName;
1669 * Getter for controller name
1671 * @return $controllerName Last validated controller name
1673 protected final function getControllerName () {
1674 return $this->controllerName;
1678 * Getter for protocol name
1680 * @return $protocolName Name of used protocol
1682 public final function getProtocolName () {
1683 return $this->protocolName;
1687 * Setter for protocol name
1689 * @param $protocolName Name of used protocol
1692 protected final function setProtocolName ($protocolName) {
1693 $this->protocolName = $protocolName;
1697 * Checks whether an object equals this object. You should overwrite this
1698 * method to implement own equality checks
1700 * @param $objectInstance An instance of a FrameworkInterface object
1701 * @return $equals Whether both objects equals
1703 public function equals (FrameworkInterface $objectInstance) {
1706 $this->__toString() == $objectInstance->__toString()
1708 $this->hashCode() == $objectInstance->hashCode()
1711 // Return the result
1716 * Generates a generic hash code of this class. You should really overwrite
1717 * this method with your own hash code generator code. But keep KISS in mind.
1719 * @return $hashCode A generic hash code respresenting this whole class
1721 public function hashCode () {
1723 return crc32($this->__toString());
1727 * Formats computer generated price values into human-understandable formats
1728 * with thousand and decimal separators.
1730 * @param $value The in computer format value for a price
1731 * @param $currency The currency symbol (use HTML-valid characters!)
1732 * @param $decNum Number of decimals after commata
1733 * @return $price The for the current language formated price string
1734 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1735 * thousands separator
1738 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1739 // Are all required attriutes set?
1740 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1741 // Throw an exception
1742 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1746 $value = (float) $value;
1748 // Reformat the US number
1749 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1751 // Return as string...
1756 * Appends a trailing slash to a string
1758 * @param $str A string (maybe) without trailing slash
1759 * @return $str A string with an auto-appended trailing slash
1761 public final function addMissingTrailingSlash ($str) {
1762 // Is there a trailing slash?
1763 if (substr($str, -1, 1) != '/') {
1767 // Return string with trailing slash
1772 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1773 * application helper instance (ApplicationHelper by default).
1775 * @param $applicationInstance An application helper instance or
1776 * null if we shall use the default
1777 * @return $templateInstance The template engine instance
1778 * @throws NullPointerException If the discovered application
1779 * instance is still null
1781 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1782 // Is the application instance set?
1783 if (is_null($applicationInstance)) {
1784 // Get the current instance
1785 $applicationInstance = $this->getApplicationInstance();
1788 if (is_null($applicationInstance)) {
1789 // Thrown an exception
1790 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1794 // Initialize the template engine
1795 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1797 // Return the prepared instance
1798 return $templateInstance;
1802 * Debugs this instance by putting out it's full content
1804 * @param $message Optional message to show in debug output
1807 public final function debugInstance ($message = '') {
1808 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1809 restore_error_handler();
1814 // Is a message set?
1815 if (!empty($message)) {
1816 // Construct message
1817 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1820 // Generate the output
1821 $content .= sprintf('<pre>%s</pre>',
1824 print_r($this, TRUE)
1830 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>',
1831 $this->__toString(),
1833 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1838 * Replaces control characters with printable output
1840 * @param $str String with control characters
1841 * @return $str Replaced string
1843 protected function replaceControlCharacters ($str) {
1846 chr(13), '[r]', str_replace(
1847 chr(10), '[n]', str_replace(
1857 * Output a partial stub message for the caller method
1859 * @param $message An optional message to display
1862 protected function partialStub ($message = '') {
1863 // Get the backtrace
1864 $backtrace = debug_backtrace();
1866 // Generate the class::method string
1867 $methodName = 'UnknownClass->unknownMethod';
1868 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1869 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1872 // Construct the full message
1873 $stubMessage = sprintf('[%s:] Partial stub!',
1877 // Is the extra message given?
1878 if (!empty($message)) {
1879 // Then add it as well
1880 $stubMessage .= ' Message: ' . $message;
1883 // Debug instance is there?
1884 if (!is_null($this->getDebugInstance())) {
1885 // Output stub message
1886 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1889 trigger_error($stubMessage);
1895 * Outputs a debug backtrace and stops further script execution
1897 * @param $message An optional message to output
1898 * @param $doExit Whether exit the program (TRUE is default)
1901 public function debugBackTrace ($message = '', $doExit = TRUE) {
1902 // Sorry, there is no other way getting this nice backtrace
1903 if (!empty($message)) {
1905 printf('Message: %s<br />' . PHP_EOL, $message);
1909 debug_print_backtrace();
1913 if ($doExit === TRUE) {
1919 * Creates an instance of a debugger instance
1921 * @param $className Name of the class (currently unsupported)
1922 * @param $lineNumber Line number where the call was made
1923 * @return $debugInstance An instance of a debugger class
1924 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1926 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1927 // Is the instance set?
1928 if (!Registry::getRegistry()->instanceExists('debug')) {
1929 // Init debug instance
1930 $debugInstance = NULL;
1934 // Get a debugger instance
1935 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1936 } catch (NullPointerException $e) {
1937 // Didn't work, no instance there
1938 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1941 // Empty string should be ignored and used for testing the middleware
1942 DebugMiddleware::getSelfInstance()->output('');
1944 // Set it in its own class. This will set it in the registry
1945 $debugInstance->setDebugInstance($debugInstance);
1947 // Get instance from registry
1948 $debugInstance = Registry::getRegistry()->getDebugInstance();
1952 return $debugInstance;
1956 * Simple output of a message with line-break
1958 * @param $message Message to output
1961 public function outputLine ($message) {
1963 print($message . PHP_EOL);
1967 * Outputs a debug message whether to debug instance (should be set!) or
1968 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1969 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1971 * @param $message Message we shall send out...
1972 * @param $doPrint Whether print or die here (default: print)
1973 * @paran $stripTags Whether to strip tags (default: FALSE)
1976 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1977 // Set debug instance to NULL
1978 $debugInstance = NULL;
1982 // Get debug instance
1983 $debugInstance = $this->getDebugInstance();
1984 } catch (NullPointerException $e) {
1985 // The debug instance is not set (yet)
1988 // Is the debug instance there?
1989 if (is_object($debugInstance)) {
1990 // Use debug output handler
1991 $debugInstance->output($message, $stripTags);
1993 if ($doPrint === FALSE) {
1994 // Die here if not printed
1998 // Are debug times enabled?
1999 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
2001 $message = $this->getPrintableExecutionTime() . $message;
2005 if ($doPrint === TRUE) {
2007 $this->outputLine($message);
2016 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2018 * @param $str The string, what ever it is needs to be converted
2019 * @return $className Generated class name
2021 public static final function convertToClassName ($str) {
2025 // Convert all dashes in underscores
2026 $str = self::convertDashesToUnderscores($str);
2028 // Now use that underscores to get classname parts for hungarian style
2029 foreach (explode('_', $str) as $strPart) {
2030 // Make the class name part lower case and first upper case
2031 $className .= ucfirst(strtolower($strPart));
2034 // Return class name
2039 * Converts dashes to underscores, e.g. useable for configuration entries
2041 * @param $str The string with maybe dashes inside
2042 * @return $str The converted string with no dashed, but underscores
2044 public static final function convertDashesToUnderscores ($str) {
2046 $str = str_replace('-', '_', $str);
2048 // Return converted string
2053 * Marks up the code by adding e.g. line numbers
2055 * @param $phpCode Unmarked PHP code
2056 * @return $markedCode Marked PHP code
2058 public function markupCode ($phpCode) {
2063 $errorArray = error_get_last();
2065 // Init the code with error message
2066 if (is_array($errorArray)) {
2068 $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>',
2069 basename($errorArray['file']),
2070 $errorArray['line'],
2071 $errorArray['message'],
2076 // Add line number to the code
2077 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2079 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2081 htmlentities($code, ENT_QUOTES)
2090 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2091 * beatiful for web-based front-ends. If null is given a message id
2092 * null_timestamp will be resolved and returned.
2094 * @param $timestamp Timestamp to prepare (filter) for display
2095 * @return $readable A readable timestamp
2097 public function doFilterFormatTimestamp ($timestamp) {
2098 // Default value to return
2101 // Is the timestamp null?
2102 if (is_null($timestamp)) {
2103 // Get a message string
2104 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2106 switch ($this->getLanguageInstance()->getLanguageCode()) {
2107 case 'de': // German format is a bit different to default
2108 // Split the GMT stamp up
2109 $dateTime = explode(' ', $timestamp );
2110 $dateArray = explode('-', $dateTime[0]);
2111 $timeArray = explode(':', $dateTime[1]);
2113 // Construct the timestamp
2114 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2124 default: // Default is pass-through
2125 $readable = $timestamp;
2135 * Filter a given number into a localized number
2137 * @param $value The raw value from e.g. database
2138 * @return $localized Localized value
2140 public function doFilterFormatNumber ($value) {
2141 // Generate it from config and localize dependencies
2142 switch ($this->getLanguageInstance()->getLanguageCode()) {
2143 case 'de': // German format is a bit different to default
2144 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2147 default: // US, etc.
2148 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2157 * "Getter" for databse entry
2159 * @return $entry An array with database entries
2160 * @throws NullPointerException If the database result is not found
2161 * @throws InvalidDatabaseResultException If the database result is invalid
2163 protected final function getDatabaseEntry () {
2164 // Is there an instance?
2165 if (!$this->getResultInstance() instanceof SearchableResult) {
2166 // Throw an exception here
2167 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2171 $this->getResultInstance()->rewind();
2173 // Do we have an entry?
2174 if ($this->getResultInstance()->valid() === FALSE) {
2175 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2176 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2180 $this->getResultInstance()->next();
2183 $entry = $this->getResultInstance()->current();
2190 * Getter for field name
2192 * @param $fieldName Field name which we shall get
2193 * @return $fieldValue Field value from the user
2194 * @throws NullPointerException If the result instance is null
2196 public final function getField ($fieldName) {
2197 // Default field value
2200 // Get result instance
2201 $resultInstance = $this->getResultInstance();
2203 // Is this instance null?
2204 if (is_null($resultInstance)) {
2205 // Then the user instance is no longer valid (expired cookies?)
2206 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2209 // Get current array
2210 $fieldArray = $resultInstance->current();
2211 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2213 // Convert dashes to underscore
2214 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2216 // Does the field exist?
2217 if ($this->isFieldSet($fieldName)) {
2219 $fieldValue = $fieldArray[$fieldName2];
2220 } elseif (defined('DEVELOPER')) {
2221 // Missing field entry, may require debugging
2222 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2224 // Missing field entry, may require debugging
2225 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2233 * Checks if given field is set
2235 * @param $fieldName Field name to check
2236 * @return $isSet Whether the given field name is set
2237 * @throws NullPointerException If the result instance is null
2239 public function isFieldSet ($fieldName) {
2240 // Get result instance
2241 $resultInstance = $this->getResultInstance();
2243 // Is this instance null?
2244 if (is_null($resultInstance)) {
2245 // Then the user instance is no longer valid (expired cookies?)
2246 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2249 // Get current array
2250 $fieldArray = $resultInstance->current();
2251 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2253 // Convert dashes to underscore
2254 $fieldName = self::convertDashesToUnderscores($fieldName);
2257 $isSet = isset($fieldArray[$fieldName]);
2264 * Flushs all pending updates to the database layer
2268 public function flushPendingUpdates () {
2269 // Get result instance
2270 $resultInstance = $this->getResultInstance();
2272 // Do we have data to update?
2273 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2274 // Get wrapper class name config entry
2275 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2277 // Create object instance
2278 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2280 // Yes, then send the whole result to the database layer
2281 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2286 * Outputs a deprecation warning to the developer.
2288 * @param $message The message we shall output to the developer
2290 * @todo Write a logging mechanism for productive mode
2292 public function deprecationWarning ($message) {
2293 // Is developer mode active?
2294 if (defined('DEVELOPER')) {
2295 // Debug instance is there?
2296 if (!is_null($this->getDebugInstance())) {
2297 // Output stub message
2298 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2301 trigger_error($message . "<br />\n");
2305 // @TODO Finish this part!
2306 $this->partialStub('Developer mode inactive. Message:' . $message);
2311 * Checks whether the given PHP extension is loaded
2313 * @param $phpExtension The PHP extension we shall check
2314 * @return $isLoaded Whether the PHP extension is loaded
2316 public final function isPhpExtensionLoaded ($phpExtension) {
2318 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2325 * "Getter" as a time() replacement but with milliseconds. You should use this
2326 * method instead of the encapsulated getimeofday() function.
2328 * @return $milliTime Timestamp with milliseconds
2330 public function getMilliTime () {
2331 // Get the time of day as float
2332 $milliTime = gettimeofday(TRUE);
2339 * Idles (sleeps) for given milliseconds
2341 * @return $hasSlept Whether it goes fine
2343 public function idle ($milliSeconds) {
2344 // Sleep is fine by default
2347 // Idle so long with found function
2348 if (function_exists('time_sleep_until')) {
2349 // Get current time and add idle time
2350 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2352 // New PHP 5.1.0 function found, ignore errors
2353 $hasSlept = @time_sleep_until($sleepUntil);
2356 * My Sun station doesn't have that function even with latest PHP
2359 usleep($milliSeconds * 1000);
2366 * Converts a hexadecimal string, even with negative sign as first string to
2367 * a decimal number using BC functions.
2369 * This work is based on comment #86673 on php.net documentation page at:
2370 * <http://de.php.net/manual/en/function.dechex.php#86673>
2372 * @param $hex Hexadecimal string
2373 * @return $dec Decimal number
2375 protected function hex2dec ($hex) {
2376 // Convert to all lower-case
2377 $hex = strtolower($hex);
2379 // Detect sign (negative/positive numbers)
2381 if (substr($hex, 0, 1) == '-') {
2383 $hex = substr($hex, 1);
2386 // Decode the hexadecimal string into a decimal number
2388 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2389 $factor = self::$hexdec[substr($hex, $i, 1)];
2390 $dec = bcadd($dec, bcmul($factor, $e));
2393 // Return the decimal number
2394 return $sign . $dec;
2398 * Converts even very large decimal numbers, also signed, to a hexadecimal
2401 * This work is based on comment #97756 on php.net documentation page at:
2402 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2404 * @param $dec Decimal number, even with negative sign
2405 * @param $maxLength Optional maximum length of the string
2406 * @return $hex Hexadecimal string
2408 protected function dec2hex ($dec, $maxLength = 0) {
2409 // maxLength can be zero or devideable by 2
2410 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2412 // Detect sign (negative/positive numbers)
2419 // Encode the decimal number into a hexadecimal string
2422 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2424 } while ($dec >= 1);
2427 * Leading zeros are required for hex-decimal "numbers". In some
2428 * situations more leading zeros are wanted, so check for both
2431 if ($maxLength > 0) {
2432 // Prepend more zeros
2433 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2434 } elseif ((strlen($hex) % 2) != 0) {
2435 // Only make string's length dividable by 2
2439 // Return the hexadecimal string
2440 return $sign . $hex;
2444 * Converts a ASCII string (0 to 255) into a decimal number.
2446 * @param $asc The ASCII string to be converted
2447 * @return $dec Decimal number
2449 protected function asc2dec ($asc) {
2450 // Convert it into a hexadecimal number
2451 $hex = bin2hex($asc);
2453 // And back into a decimal number
2454 $dec = $this->hex2dec($hex);
2461 * Converts a decimal number into an ASCII string.
2463 * @param $dec Decimal number
2464 * @return $asc An ASCII string
2466 protected function dec2asc ($dec) {
2467 // First convert the number into a hexadecimal string
2468 $hex = $this->dec2hex($dec);
2470 // Then convert it into the ASCII string
2471 $asc = $this->hex2asc($hex);
2478 * Converts a hexadecimal number into an ASCII string. Negative numbers
2481 * @param $hex Hexadecimal string
2482 * @return $asc An ASCII string
2484 protected function hex2asc ($hex) {
2485 // Check for length, it must be devideable by 2
2486 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2487 assert((strlen($hex) % 2) == 0);
2491 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2492 // Get the decimal number of the chunk
2493 $part = hexdec(substr($hex, $idx, 2));
2495 // Add it to the final string
2499 // Return the final string
2504 * Checks whether the given encoded data was encoded with Base64
2506 * @param $encodedData Encoded data we shall check
2507 * @return $isBase64 Whether the encoded data is Base64
2509 protected function isBase64Encoded ($encodedData) {
2511 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2518 * "Getter" to get response/request type from analysis of the system.
2520 * @return $responseType Analyzed response type
2522 protected static function getResponseTypeFromSystem () {
2523 // Default is console
2524 $responseType = 'console';
2526 // Is 'HTTP_HOST' set?
2527 if (isset($_SERVER['HTTP_HOST'])) {
2529 * Then it is a HTML response/request as RSS and so on may be
2530 * transfered over HTTP as well.
2532 $responseType = 'html';
2536 return $responseType;
2540 * Gets a cache key from Criteria instance
2542 * @param $criteriaInstance An instance of a Criteria class
2543 * @param $onlyKeys Only use these keys for a cache key
2544 * @return $cacheKey A cache key suitable for lookup/storage purposes
2546 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2548 $cacheKey = sprintf('%s@%s',
2549 $this->__toString(),
2550 $criteriaInstance->getCacheKey($onlyKeys)
2554 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2559 * Getter for startup time in miliseconds
2561 * @return $startupTime Startup time in miliseconds
2563 protected function getStartupTime () {
2564 return self::$startupTime;
2568 * "Getter" for a printable currently execution time in nice braces
2570 * @return $executionTime Current execution time in nice braces
2572 protected function getPrintableExecutionTime () {
2573 // Caculate the execution time
2574 $executionTime = microtime(TRUE) - $this->getStartupTime();
2576 // Pack it in nice braces
2577 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2580 return $executionTime;
2584 * Hashes a given string with a simple but stronger hash function (no salt)
2585 * and hex-encode it.
2587 * @param $str The string to be hashed
2588 * @return $hash The hash from string $str
2590 public static final function hash ($str) {
2591 // Hash given string with (better secure) hasher
2592 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2599 * "Getter" for length of hash() output. This will be "cached" to speed up
2602 * @return $length Length of hash() output
2604 public static final function getHashLength () {
2606 if (is_null(self::$hashLength)) {
2607 // No, then hash a string and save its length.
2608 self::$hashLength = strlen(self::hash('abc123'));
2612 return self::$hashLength;
2616 * Checks whether the given number is really a number (only chars 0-9).
2618 * @param $num A string consisting only chars between 0 and 9
2619 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2620 * @param $assertMismatch Whether to assert mismatches
2621 * @return $ret The (hopefully) secured numbered value
2623 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2624 // Filter all numbers out
2625 $ret = preg_replace('/[^0123456789]/', '', $num);
2628 if ($castValue === TRUE) {
2629 // Cast to biggest numeric type
2630 $ret = (double) $ret;
2633 // Assert only if requested
2634 if ($assertMismatch === TRUE) {
2635 // Has the whole value changed?
2636 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2644 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2646 * @param $num A string consisting only chars between 0 and 9
2647 * @param $assertMismatch Whether to assert mismatches
2648 * @return $ret The (hopefully) secured hext-numbered value
2650 public function hexval ($num, $assertMismatch = FALSE) {
2651 // Filter all numbers out
2652 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2654 // Assert only if requested
2655 if ($assertMismatch === TRUE) {
2656 // Has the whole value changed?
2657 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2665 * Checks whether start/end marker are set
2667 * @param $data Data to be checked
2668 * @return $isset Whether start/end marker are set
2670 public final function ifStartEndMarkersSet ($data) {
2672 $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));
2674 // ... and return it
2679 * Determines if an element 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 * @param $element Element to check
2685 * @return $isset Whether the given key is set
2687 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2689 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2692 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2698 * Determines if a key is set in the generic array
2700 * @param $keyGroup Main group for the key
2701 * @param $subGroup Sub group for the key
2702 * @param $key Key to check
2703 * @return $isset Whether the given key is set
2705 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2707 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2710 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2718 * Determines if a group is set in the generic array
2720 * @param $keyGroup Main group
2721 * @param $subGroup Sub group
2722 * @return $isset Whether the given group is set
2724 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2726 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2729 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2736 * Getter for sub key group
2738 * @param $keyGroup Main key group
2739 * @param $subGroup Sub key group
2740 * @return $array An array with all array elements
2742 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2744 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2745 // No, then abort here
2746 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2751 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2754 return $this->genericArray[$keyGroup][$subGroup];
2758 * Unsets a given key in generic array
2760 * @param $keyGroup Main group for the key
2761 * @param $subGroup Sub group for the key
2762 * @param $key Key to unset
2765 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2767 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2770 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2774 * Unsets a given element in generic array
2776 * @param $keyGroup Main group for the key
2777 * @param $subGroup Sub group for the key
2778 * @param $key Key to unset
2779 * @param $element Element to unset
2782 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2784 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2787 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2791 * Append a string to a given generic array key
2793 * @param $keyGroup Main group for the key
2794 * @param $subGroup Sub group for the key
2795 * @param $key Key to unset
2796 * @param $value Value to add/append
2799 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2801 //* 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);
2803 // Is it already there?
2804 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2806 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2809 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2814 * Append a string to a given generic array element
2816 * @param $keyGroup Main group for the key
2817 * @param $subGroup Sub group for the key
2818 * @param $key Key to unset
2819 * @param $element Element to check
2820 * @param $value Value to add/append
2823 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2825 //* 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);
2827 // Is it already there?
2828 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2830 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2833 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2838 * Sets a string in a given generic array element
2840 * @param $keyGroup Main group for the key
2841 * @param $subGroup Sub group for the key
2842 * @param $key Key to unset
2843 * @param $element Element to check
2844 * @param $value Value to add/append
2847 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2849 //* 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);
2852 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2856 * Initializes given generic array group
2858 * @param $keyGroup Main group for the key
2859 * @param $subGroup Sub group for the key
2860 * @param $key Key to use
2861 * @param $forceInit Optionally force initialization
2864 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2866 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2868 // Is it already set?
2869 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2870 // Already initialized
2871 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2876 $this->genericArray[$keyGroup][$subGroup] = array();
2880 * Initializes given generic array key
2882 * @param $keyGroup Main group for the key
2883 * @param $subGroup Sub group for the key
2884 * @param $key Key to use
2885 * @param $forceInit Optionally force initialization
2888 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2890 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2892 // Is it already set?
2893 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2894 // Already initialized
2895 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2900 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2904 * Initializes given generic array element
2906 * @param $keyGroup Main group for the key
2907 * @param $subGroup Sub group for the key
2908 * @param $key Key to use
2909 * @param $element Element to use
2910 * @param $forceInit Optionally force initialization
2913 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2915 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2917 // Is it already set?
2918 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2919 // Already initialized
2920 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2925 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2929 * Pushes an element to a generic key
2931 * @param $keyGroup Main group for the key
2932 * @param $subGroup Sub group for the key
2933 * @param $key Key to use
2934 * @param $value Value to add/append
2935 * @return $count Number of array elements
2937 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2939 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2942 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2944 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2948 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2951 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2952 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2957 * Pushes an element to a generic array element
2959 * @param $keyGroup Main group for the key
2960 * @param $subGroup Sub group for the key
2961 * @param $key Key to use
2962 * @param $element Element to check
2963 * @param $value Value to add/append
2964 * @return $count Number of array elements
2966 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2968 //* 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));
2971 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2973 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2977 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2980 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2981 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2986 * Pops an element from a generic group
2988 * @param $keyGroup Main group for the key
2989 * @param $subGroup Sub group for the key
2990 * @param $key Key to unset
2991 * @return $value Last "popped" value
2993 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2995 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2998 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3000 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3005 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
3008 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3009 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3014 * Shifts an element from a generic group
3016 * @param $keyGroup Main group for the key
3017 * @param $subGroup Sub group for the key
3018 * @param $key Key to unset
3019 * @return $value Last "popped" value
3021 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3023 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3026 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3028 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3033 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3036 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3037 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3042 * Count generic array group
3044 * @param $keyGroup Main group for the key
3045 * @return $count Count of given group
3047 protected final function countGenericArray ($keyGroup) {
3049 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3052 if (!isset($this->genericArray[$keyGroup])) {
3054 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3059 $count = count($this->genericArray[$keyGroup]);
3062 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3069 * Count generic array sub group
3071 * @param $keyGroup Main group for the key
3072 * @param $subGroup Sub group for the key
3073 * @return $count Count of given group
3075 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3077 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3080 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3082 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3087 $count = count($this->genericArray[$keyGroup][$subGroup]);
3090 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3097 * Count generic array elements
3099 * @param $keyGroup Main group for the key
3100 * @param $subGroup Sub group for the key
3101 * @para $key Key to count
3102 * @return $count Count of given key
3104 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3106 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3109 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3111 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3113 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3115 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3120 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3123 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3130 * Getter for whole generic group array
3132 * @param $keyGroup Key group to get
3133 * @return $array Whole generic array group
3135 protected final function getGenericArray ($keyGroup) {
3137 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3140 if (!isset($this->genericArray[$keyGroup])) {
3142 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3147 return $this->genericArray[$keyGroup];
3151 * Setter 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 * @param $value Mixed value from generic array element
3159 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3161 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3164 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3168 * Getter for generic array key
3170 * @param $keyGroup Key group to get
3171 * @param $subGroup Sub group for the key
3172 * @param $key Key to unset
3173 * @return $value Mixed value from generic array element
3175 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3177 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3180 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3182 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3187 return $this->genericArray[$keyGroup][$subGroup][$key];
3191 * Sets a value in given generic array key/element
3193 * @param $keyGroup Main group for the key
3194 * @param $subGroup Sub group for the key
3195 * @param $key Key to set
3196 * @param $element Element to set
3197 * @param $value Value to set
3200 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3202 //* 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));
3205 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3209 * Getter for generic array element
3211 * @param $keyGroup Key group to get
3212 * @param $subGroup Sub group for the key
3213 * @param $key Key to look for
3214 * @param $element Element to look for
3215 * @return $value Mixed value from generic array element
3217 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3219 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3222 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3224 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3229 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3233 * Checks if a given sub group is valid (array)
3235 * @param $keyGroup Key group to get
3236 * @param $subGroup Sub group for the key
3237 * @return $isValid Whether given sub group is valid
3239 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3241 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3244 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3251 * Checks if a given key is valid (array)
3253 * @param $keyGroup Key group to get
3254 * @param $subGroup Sub group for the key
3255 * @param $key Key to check
3256 * @return $isValid Whether given sub group is valid
3258 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3260 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3263 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3270 * Initializes the web output instance
3274 protected function initWebOutputInstance () {
3275 // Get application instance
3276 $applicationInstance = Registry::getRegistry()->getInstance('app');
3278 // Is this a response instance?
3279 if ($this instanceof Responseable) {
3280 // Then set it in application instance
3281 $applicationInstance->setResponseInstance($this);
3284 // Init web output instance
3285 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3288 $this->setWebOutputInstance($outputInstance);
3292 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3294 * @param $boolean Boolean value
3295 * @return $translated Translated boolean value
3297 public static final function translateBooleanToYesNo ($boolean) {
3298 // Make sure it is really boolean
3299 assert(is_bool($boolean));
3302 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3304 // ... and return it
3309 * Encodes raw data (almost any type) by "serializing" it and then pack it
3310 * into a "binary format".
3312 * @param $rawData Raw data (almost any type)
3313 * @return $encoded Encoded data
3315 protected function encodeData ($rawData) {
3316 // Make sure no objects or resources pass through
3317 assert(!is_object($rawData));
3318 assert(!is_resource($rawData));
3320 // First "serialize" it (json_encode() is faster than serialize())
3321 $encoded = $this->packString(json_encode($rawData));
3328 * Pack a string into a "binary format". Please execuse me that this is
3329 * widely undocumented. :-(
3331 * @param $str Unpacked string
3332 * @return $packed Packed string
3333 * @todo Improve documentation
3335 protected function packString ($str) {
3337 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3339 // First compress the string (gzcompress is okay)
3340 $str = gzcompress($str);
3345 // And start the "encoding" loop
3346 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3348 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3349 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3351 if (($idx + $i) <= strlen($str)) {
3352 $ord = ord(substr($str, ($idx + $i), 1));
3354 $add = $ord * pow(256, $factor);
3358 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3362 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3363 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3365 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3366 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3372 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3377 * Checks whether the given file/path is in open_basedir(). This does not
3378 * gurantee that the file is actually readable and/or writeable. If you need
3379 * such gurantee then please use isReadableFile() instead.
3381 * @param $filePathName Name of the file/path to be checked
3382 * @return $isReachable Whether it is within open_basedir()
3384 protected static function isReachableFilePath ($filePathName) {
3385 // Is not reachable by default
3386 $isReachable = FALSE;
3388 // Get open_basedir parameter
3389 $openBaseDir = ini_get('open_basedir');
3392 if (!empty($openBaseDir)) {
3393 // Check all entries
3394 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3395 // Check on existence
3396 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3398 $isReachable = TRUE;
3402 // If open_basedir is not set, all is allowed
3403 $isReachable = TRUE;
3407 return $isReachable;
3411 * Checks whether the give file is within open_basedir() (done by
3412 * isReachableFilePath()), is actually a file and is readable.
3414 * @param $fileName Name of the file to be checked
3415 * @return $isReadable Whether the file is readable (and therefor exists)
3417 public static function isReadableFile ($fileName) {
3418 // Default is not readable
3419 $isReadable = FALSE;
3421 // Is within parameters, so check if it is a file and readable
3422 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3429 * Creates a full-qualified file name (FQFN) for given file name by adding
3430 * a configured temporary file path to it.
3432 * @param $fileName Name for temporary file
3433 * @return $fqfn Full-qualified file name
3434 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3435 * @throws FileIoException If the file cannot be written
3437 protected static function createTempPathForFile ($fileName) {
3439 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3441 // Is the path writeable?
3442 if (!is_writable($basePath)) {
3443 // Path is write-protected
3444 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3448 $fqfn = $basePath . '/' . $fileName;
3451 if (!self::isReachableFilePath($fqfn)) {
3453 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3461 * "Getter" for a printable state name
3463 * @return $stateName Name of the node's state in a printable format
3465 public final function getPrintableState () {
3466 // Default is 'null'
3467 $stateName = 'null';
3469 // Get the state instance
3470 $stateInstance = $this->getStateInstance();
3472 // Is it an instance of Stateable?
3473 if ($stateInstance instanceof Stateable) {
3474 // Then use that state name
3475 $stateName = $stateInstance->getStateName();
3483 * Handles socket error for given socket resource and peer data. This method
3484 * validates $socketResource if it is a valid resource (see is_resource())
3485 * but assumes valid data in array $recipientData, except that
3486 * count($recipientData) is always 2.
3488 * @param $method Value of __METHOD__ from calling method
3489 * @param $line Value of __LINE__ from calling method
3490 * @param $socketResource A valid socket resource
3491 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3493 * @throws InvalidSocketException If $socketResource is no socket resource
3494 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3495 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3497 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3498 // This method handles only socket resources
3499 if (!is_resource($socketResource)) {
3500 // No resource, abort here
3501 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3504 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3505 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3506 assert(isset($socketData[0]));
3507 assert(isset($socketData[1]));
3509 // Get error code for first validation (0 is not an error)
3510 $errorCode = socket_last_error($socketResource);
3512 // If the error code is zero, someone called this method without an error
3513 if ($errorCode == 0) {
3514 // No error detected (or previously cleared outside this method)
3515 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3518 // Get handler (method) name
3519 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3521 // Call-back the error handler method
3522 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3524 // Finally clear the error because it has been handled
3525 socket_clear_error($socketResource);