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\Crypto\RandomNumber\RandomNumberGenerator;
14 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
15 use CoreFramework\Factory\ObjectFactory;
16 use CoreFramework\Filesystem\Block;
17 use CoreFramework\Filesystem\FilePointer;
18 use CoreFramework\Filesystem\FrameworkDirectory;
19 use CoreFramework\Generic\FrameworkInterface;
20 use CoreFramework\Generic\NullPointerException;
21 use CoreFramework\Handler\Stream\IoHandler;
22 use CoreFramework\Index\Indexable;
23 use CoreFramework\Listener\Listenable;
24 use CoreFramework\Lists\Listable;
25 use CoreFramework\Loader\ClassLoader;
26 use CoreFramework\Manager\ManageableApplication;
27 use CoreFramework\Middleware\Compressor\CompressorChannel;
28 use CoreFramework\Middleware\Debug\DebugMiddleware;
29 use CoreFramework\Parser\Parseable;
30 use CoreFramework\Registry\Register;
31 use CoreFramework\Registry\Registry;
32 use CoreFramework\Request\Requestable;
33 use CoreFramework\Resolver\Resolver;
34 use CoreFramework\Result\Database\CachedDatabaseResult;
35 use CoreFramework\Result\Search\SearchableResult;
36 use CoreFramework\Response\Responseable;
37 use CoreFramework\Stacker\Stackable;
38 use CoreFramework\Stream\Output\OutputStreamer;
39 use CoreFramework\Template\CompileableTemplate;
40 use CoreFramework\User\ManageableAccount;
41 use CoreFramework\Visitor\Visitor;
42 use CoreFramework\Wrapper\Database\DatabaseWrapper;
50 * The simulator system class is the super class of all other classes. This
51 * class handles saving of games etc.
53 * @author Roland Haeder <webmaster@shipsimu.org>
55 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
56 * @license GNU GPL 3.0 or any newer version
57 * @link http://www.shipsimu.org
59 * This program is free software: you can redistribute it and/or modify
60 * it under the terms of the GNU General Public License as published by
61 * the Free Software Foundation, either version 3 of the License, or
62 * (at your option) any later version.
64 * This program is distributed in the hope that it will be useful,
65 * but WITHOUT ANY WARRANTY; without even the implied warranty of
66 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
67 * GNU General Public License for more details.
69 * You should have received a copy of the GNU General Public License
70 * along with this program. If not, see <http://www.gnu.org/licenses/>.
72 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
74 * Length of output from hash()
76 private static $hashLength = NULL;
81 private $realClass = 'BaseFrameworkSystem';
84 * Instance of a Requestable class
86 private $requestInstance = NULL;
89 * Instance of a Responseable class
91 private $responseInstance = NULL;
94 * Search criteria instance
96 private $searchInstance = NULL;
99 * Update criteria instance
101 private $updateInstance = NULL;
104 * The file I/O instance for the template loader
106 private $fileIoInstance = NULL;
111 private $resolverInstance = NULL;
114 * Template engine instance
116 private $templateInstance = NULL;
119 * Database result instance
121 private $resultInstance = NULL;
124 * Instance for user class
126 private $userInstance = NULL;
129 * A controller instance
131 private $controllerInstance = NULL;
136 private $rngInstance = NULL;
139 * Instance of a crypto helper
141 private $cryptoInstance = NULL;
144 * Instance of an Iterator class
146 private $iteratorInstance = NULL;
149 * Instance of the list
151 private $listInstance = NULL;
156 private $menuInstance = NULL;
159 * Instance of the image
161 private $imageInstance = NULL;
164 * Instance of the stacker
166 private $stackInstance = NULL;
169 * A Compressor instance
171 private $compressorInstance = NULL;
174 * A Parseable instance
176 private $parserInstance = NULL;
179 * A HandleableProtocol instance
181 private $protocolInstance = NULL;
184 * A database wrapper instance
186 private $databaseInstance = NULL;
189 * A helper instance for the form
191 private $helperInstance = NULL;
194 * An instance of a Source class
196 private $sourceInstance = NULL;
199 * An instance of a UrlSource class
201 private $urlSourceInstance = NULL;
204 * An instance of a InputStream class
206 private $inputStreamInstance = NULL;
209 * An instance of a OutputStream class
211 private $outputStreamInstance = NULL;
214 * Networkable handler instance
216 private $handlerInstance = NULL;
219 * Visitor handler instance
221 private $visitorInstance = NULL;
226 private $dhtInstance = NULL;
229 * An instance of a database wrapper class
231 private $wrapperInstance = NULL;
234 * An instance of a file I/O pointer class (not handler)
236 private $pointerInstance = NULL;
239 * An instance of an Indexable class
241 private $indexInstance = NULL;
244 * An instance of a Block class
246 private $blockInstance = NULL;
251 private $minableInstance = NULL;
254 * A FrameworkDirectory instance
256 private $directoryInstance = NULL;
261 private $listenerInstance = NULL;
264 * An instance of a communicator
266 private $communicatorInstance = NULL;
269 * The concrete output instance
271 private $outputInstance = NULL;
276 private $stateInstance = NULL;
279 * Thousands separator
281 private $thousands = '.'; // German
286 private $decimals = ','; // German
291 private $socketResource = FALSE;
294 * Regular expression to use for validation
296 private $regularExpression = '';
301 private $packageData = array();
306 private $genericArray = array();
311 private $commandName = '';
316 private $controllerName = '';
319 * Name of used protocol
321 private $protocolName = 'invalid';
324 * Array with bitmasks and such for pack/unpack methods to support both
325 * 32-bit and 64-bit systems
327 private $packingData = array(
330 'left' => 0xffff0000,
331 'right' => 0x0000ffff,
337 'left' => 0xffffffff00000000,
338 'right' => 0x00000000ffffffff,
345 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
347 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
349 private $archArrayElement = FALSE;
351 /***********************
352 * Exception codes.... *
353 ***********************/
355 // @todo Try to clean these constants up
356 const EXCEPTION_IS_NULL_POINTER = 0x001;
357 const EXCEPTION_IS_NO_OBJECT = 0x002;
358 const EXCEPTION_IS_NO_ARRAY = 0x003;
359 const EXCEPTION_MISSING_METHOD = 0x004;
360 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
361 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
362 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
363 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
364 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
365 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
366 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
367 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
368 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
369 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
370 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
371 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
372 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
373 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
374 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
375 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
376 const EXCEPTION_PATH_NOT_FOUND = 0x015;
377 const EXCEPTION_INVALID_PATH_NAME = 0x016;
378 const EXCEPTION_READ_PROTECED_PATH = 0x017;
379 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
380 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
381 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
382 const EXCEPTION_INVALID_RESOURCE = 0x01b;
383 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
384 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
385 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
386 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
387 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
388 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
389 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
390 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
391 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
392 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
393 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
394 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
395 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
396 const EXCEPTION_INVALID_STRING = 0x029;
397 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
398 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
399 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
400 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
401 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
402 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
403 const EXCEPTION_MISSING_ELEMENT = 0x030;
404 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
405 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
406 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
407 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
408 const EXCEPTION_FATAL_ERROR = 0x035;
409 const EXCEPTION_FILE_NOT_FOUND = 0x036;
410 const EXCEPTION_ASSERTION_FAILED = 0x037;
411 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
412 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
413 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
414 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
415 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
416 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
419 * Hexadecimal->Decimal translation array
421 private static $hexdec = array(
441 * Decimal->hexadecimal translation array
443 private static $dechex = array(
463 * Startup time in miliseconds
465 private static $startupTime = 0;
468 * Protected super constructor
470 * @param $className Name of the class
473 protected function __construct ($className) {
475 $this->setRealClass($className);
477 // Set configuration instance if no registry ...
478 if (!$this instanceof Register) {
479 // ... because registries doesn't need to be configured
480 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
483 // Is the startup time set? (0 cannot be TRUE anymore)
484 if (self::$startupTime == 0) {
486 self::$startupTime = microtime(TRUE);
490 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
494 * Destructor for all classes. You should not call this method on your own.
498 public function __destruct () {
499 // Flush any updated entries to the database
500 $this->flushPendingUpdates();
502 // Is this object already destroyed?
503 if ($this->__toString() != 'DestructedObject') {
504 // Destroy all informations about this class but keep some text about it alive
505 $this->setRealClass('DestructedObject');
506 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
507 // Already destructed object
508 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
513 // Do not call this twice
514 trigger_error(__METHOD__ . ': Called twice.');
520 * The __call() method where all non-implemented methods end up
522 * @param $methodName Name of the missing method
523 * @args $args Arguments passed to the method
526 public final function __call ($methodName, $args) {
527 return self::__callStatic($methodName, $args);
531 * The __callStatic() method where all non-implemented static methods end up
533 * @param $methodName Name of the missing method
534 * @args $args Arguments passed to the method
537 public static final function __callStatic ($methodName, $args) {
539 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
541 // Init argument string
544 // Is it NULL, empty or an array?
545 if (is_null($args)) {
547 $argsString = 'NULL';
548 } elseif (is_array($args)) {
552 // Some arguments are there
553 foreach ($args as $arg) {
554 // Add data about the argument
555 $argsString .= gettype($arg) . ':';
558 // Found a NULL argument
559 $argsString .= 'NULL';
560 } elseif (is_string($arg)) {
561 // Add length for strings
562 $argsString .= strlen($arg);
563 } elseif ((is_int($arg)) || (is_float($arg))) {
566 } elseif (is_array($arg)) {
567 // .. or size if array
568 $argsString .= count($arg);
569 } elseif (is_object($arg)) {
571 $reflection = new ReflectionClass($arg);
573 // Is an other object, maybe no __toString() available
574 $argsString .= $reflection->getName();
575 } elseif ($arg === TRUE) {
576 // ... is boolean 'TRUE'
577 $argsString .= 'TRUE';
578 } elseif ($arg === FALSE) {
579 // ... is boolean 'FALSE'
580 $argsString .= 'FALSE';
583 // Comma for next one
588 if (substr($argsString, -2, 1) == ',') {
589 $argsString = substr($argsString, 0, -2);
595 // Invalid arguments!
596 $argsString = '!INVALID:' . gettype($args) . '!';
599 // Output stub message
600 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
601 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
611 * Getter for $realClass
613 * @return $realClass The name of the real class (not BaseFrameworkSystem)
615 public function __toString () {
616 return $this->realClass;
620 * Magic method to catch setting of missing but set class fields/attributes
622 * @param $name Name of the field/attribute
623 * @param $value Value to store
626 public final function __set ($name, $value) {
627 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
630 print_r($value, TRUE)
635 * Magic method to catch getting of missing fields/attributes
637 * @param $name Name of the field/attribute
640 public final function __get ($name) {
641 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
647 * Magic method to catch unsetting of missing fields/attributes
649 * @param $name Name of the field/attribute
652 public final function __unset ($name) {
653 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
659 * Magic method to catch object serialization
661 * @return $unsupported Unsupported method
662 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
664 public final function __sleep () {
665 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
669 * Magic method to catch object deserialization
671 * @return $unsupported Unsupported method
672 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
674 public final function __wakeup () {
675 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
679 * Magic method to catch calls when an object instance is called
681 * @return $unsupported Unsupported method
682 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
684 public final function __invoke () {
685 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
689 * Setter for the real class name
691 * @param $realClass Class name (string)
694 public final function setRealClass ($realClass) {
696 $this->realClass = (string) $realClass;
700 * Setter for database result instance
702 * @param $resultInstance An instance of a database result class
704 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
706 protected final function setResultInstance (SearchableResult $resultInstance) {
707 $this->resultInstance = $resultInstance;
711 * Getter for database result instance
713 * @return $resultInstance An instance of a database result class
715 public final function getResultInstance () {
716 return $this->resultInstance;
720 * Setter for template engine instances
722 * @param $templateInstance An instance of a template engine class
725 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
726 $this->templateInstance = $templateInstance;
730 * Getter for template engine instances
732 * @return $templateInstance An instance of a template engine class
734 protected final function getTemplateInstance () {
735 return $this->templateInstance;
739 * Setter for search instance
741 * @param $searchInstance Searchable criteria instance
744 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
745 $this->searchInstance = $searchInstance;
749 * Getter for search instance
751 * @return $searchInstance Searchable criteria instance
753 public final function getSearchInstance () {
754 return $this->searchInstance;
758 * Setter for update instance
760 * @param $updateInstance An instance of a LocalUpdateCriteria clase
763 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
764 $this->updateInstance = $updateInstance;
768 * Getter for update instance
770 * @return $updateInstance Updateable criteria instance
772 public final function getUpdateInstance () {
773 return $this->updateInstance;
777 * Setter for resolver instance
779 * @param $resolverInstance Instance of a command resolver class
782 public final function setResolverInstance (Resolver $resolverInstance) {
783 $this->resolverInstance = $resolverInstance;
787 * Getter for resolver instance
789 * @return $resolverInstance Instance of a command resolver class
791 public final function getResolverInstance () {
792 return $this->resolverInstance;
796 * Setter for language instance
798 * @param $configInstance The configuration instance which shall
799 * be FrameworkConfiguration
802 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
803 Registry::getRegistry()->addInstance('config', $configInstance);
807 * Getter for configuration instance
809 * @return $configInstance Configuration instance
811 public final function getConfigInstance () {
812 $configInstance = Registry::getRegistry()->getInstance('config');
813 return $configInstance;
817 * Setter for debug instance
819 * @param $debugInstance The instance for debug output class
822 public final function setDebugInstance (DebugMiddleware $debugInstance) {
823 Registry::getRegistry()->addInstance('debug', $debugInstance);
827 * Getter for debug instance
829 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
831 public final function getDebugInstance () {
832 // Get debug instance
833 $debugInstance = Registry::getRegistry()->getInstance('debug');
836 return $debugInstance;
840 * Setter for web output instance
842 * @param $webInstance The instance for web output class
845 public final function setWebOutputInstance (OutputStreamer $webInstance) {
846 Registry::getRegistry()->addInstance('web_output', $webInstance);
850 * Getter for web output instance
852 * @return $webOutputInstance - Instance to class WebOutput
854 public final function getWebOutputInstance () {
855 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
856 return $webOutputInstance;
860 * Setter for database instance
862 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
865 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
866 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
870 * Getter for database layer
872 * @return $databaseInstance The database layer instance
874 public final function getDatabaseInstance () {
876 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
879 return $databaseInstance;
883 * Setter for compressor channel
885 * @param $compressorInstance An instance of CompressorChannel
888 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
889 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
893 * Getter for compressor channel
895 * @return $compressorInstance The compressor channel
897 public final function getCompressorChannel () {
898 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
899 return $compressorInstance;
903 * Protected getter for a manageable application helper class
905 * @return $applicationInstance An instance of a manageable application helper class
907 protected final function getApplicationInstance () {
908 $applicationInstance = Registry::getRegistry()->getInstance('application');
909 return $applicationInstance;
913 * Setter for a manageable application helper class
915 * @param $applicationInstance An instance of a manageable application helper class
918 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
919 Registry::getRegistry()->addInstance('application', $applicationInstance);
923 * Setter for request instance
925 * @param $requestInstance An instance of a Requestable class
928 public final function setRequestInstance (Requestable $requestInstance) {
929 $this->requestInstance = $requestInstance;
933 * Getter for request instance
935 * @return $requestInstance An instance of a Requestable class
937 public final function getRequestInstance () {
938 return $this->requestInstance;
942 * Setter for response instance
944 * @param $responseInstance An instance of a Responseable class
947 public final function setResponseInstance (Responseable $responseInstance) {
948 $this->responseInstance = $responseInstance;
952 * Getter for response instance
954 * @return $responseInstance An instance of a Responseable class
956 public final function getResponseInstance () {
957 return $this->responseInstance;
961 * Private getter for language instance
963 * @return $langInstance An instance to the language sub-system
965 protected final function getLanguageInstance () {
966 $langInstance = Registry::getRegistry()->getInstance('language');
967 return $langInstance;
971 * Setter for language instance
973 * @param $langInstance An instance to the language sub-system
975 * @see LanguageSystem
977 public final function setLanguageInstance (ManageableLanguage $langInstance) {
978 Registry::getRegistry()->addInstance('language', $langInstance);
982 * Private getter for file IO instance
984 * @return $fileIoInstance An instance to the file I/O sub-system
986 protected final function getFileIoInstance () {
987 return $this->fileIoInstance;
991 * Setter for file I/O instance
993 * @param $fileIoInstance An instance to the file I/O sub-system
996 public final function setFileIoInstance (IoHandler $fileIoInstance) {
997 $this->fileIoInstance = $fileIoInstance;
1001 * Protected setter for user instance
1003 * @param $userInstance An instance of a user class
1006 protected final function setUserInstance (ManageableAccount $userInstance) {
1007 $this->userInstance = $userInstance;
1011 * Getter for user instance
1013 * @return $userInstance An instance of a user class
1015 public final function getUserInstance () {
1016 return $this->userInstance;
1020 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1022 * @param $controllerInstance An instance of the controller
1025 public final function setControllerInstance (Controller $controllerInstance) {
1026 $this->controllerInstance = $controllerInstance;
1030 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1032 * @return $controllerInstance An instance of the controller
1034 public final function getControllerInstance () {
1035 return $this->controllerInstance;
1039 * Setter for RNG instance
1041 * @param $rngInstance An instance of a random number generator (RNG)
1044 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1045 $this->rngInstance = $rngInstance;
1049 * Getter for RNG instance
1051 * @return $rngInstance An instance of a random number generator (RNG)
1053 public final function getRngInstance () {
1054 return $this->rngInstance;
1058 * Setter for Cryptable instance
1060 * @param $cryptoInstance An instance of a Cryptable class
1063 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1064 $this->cryptoInstance = $cryptoInstance;
1068 * Getter for Cryptable instance
1070 * @return $cryptoInstance An instance of a Cryptable class
1072 public final function getCryptoInstance () {
1073 return $this->cryptoInstance;
1077 * Setter for the list instance
1079 * @param $listInstance A list of Listable
1082 protected final function setListInstance (Listable $listInstance) {
1083 $this->listInstance = $listInstance;
1087 * Getter for the list instance
1089 * @return $listInstance A list of Listable
1091 protected final function getListInstance () {
1092 return $this->listInstance;
1096 * Setter for the menu instance
1098 * @param $menuInstance A RenderableMenu instance
1101 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1102 $this->menuInstance = $menuInstance;
1106 * Getter for the menu instance
1108 * @return $menuInstance A RenderableMenu instance
1110 protected final function getMenuInstance () {
1111 return $this->menuInstance;
1115 * Setter for image instance
1117 * @param $imageInstance An instance of an image
1120 public final function setImageInstance (BaseImage $imageInstance) {
1121 $this->imageInstance = $imageInstance;
1125 * Getter for image instance
1127 * @return $imageInstance An instance of an image
1129 public final function getImageInstance () {
1130 return $this->imageInstance;
1134 * Setter for stacker instance
1136 * @param $stackInstance An instance of an stacker
1139 public final function setStackInstance (Stackable $stackInstance) {
1140 $this->stackInstance = $stackInstance;
1144 * Getter for stacker instance
1146 * @return $stackInstance An instance of an stacker
1148 public final function getStackInstance () {
1149 return $this->stackInstance;
1153 * Setter for compressor instance
1155 * @param $compressorInstance An instance of an compressor
1158 public final function setCompressorInstance (Compressor $compressorInstance) {
1159 $this->compressorInstance = $compressorInstance;
1163 * Getter for compressor instance
1165 * @return $compressorInstance An instance of an compressor
1167 public final function getCompressorInstance () {
1168 return $this->compressorInstance;
1172 * Setter for Parseable instance
1174 * @param $parserInstance An instance of an Parseable
1177 public final function setParserInstance (Parseable $parserInstance) {
1178 $this->parserInstance = $parserInstance;
1182 * Getter for Parseable instance
1184 * @return $parserInstance An instance of an Parseable
1186 public final function getParserInstance () {
1187 return $this->parserInstance;
1191 * Setter for HandleableProtocol instance
1193 * @param $protocolInstance An instance of an HandleableProtocol
1196 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1197 $this->protocolInstance = $protocolInstance;
1201 * Getter for HandleableProtocol instance
1203 * @return $protocolInstance An instance of an HandleableProtocol
1205 public final function getProtocolInstance () {
1206 return $this->protocolInstance;
1210 * Setter for DatabaseWrapper instance
1212 * @param $wrapperInstance An instance of an DatabaseWrapper
1215 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1216 $this->wrapperInstance = $wrapperInstance;
1220 * Getter for DatabaseWrapper instance
1222 * @return $wrapperInstance An instance of an DatabaseWrapper
1224 public final function getWrapperInstance () {
1225 return $this->wrapperInstance;
1229 * Setter for socket resource
1231 * @param $socketResource A valid socket resource
1234 public final function setSocketResource ($socketResource) {
1235 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1236 $this->socketResource = $socketResource;
1240 * Getter for socket resource
1242 * @return $socketResource A valid socket resource
1244 public final function getSocketResource () {
1245 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1246 return $this->socketResource;
1250 * Setter for regular expression
1252 * @param $regularExpression A valid regular expression
1255 public final function setRegularExpression ($regularExpression) {
1256 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1257 $this->regularExpression = $regularExpression;
1261 * Getter for regular expression
1263 * @return $regularExpression A valid regular expression
1265 public final function getRegularExpression () {
1266 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1267 return $this->regularExpression;
1271 * Setter for helper instance
1273 * @param $helperInstance An instance of a helper class
1276 protected final function setHelperInstance (Helper $helperInstance) {
1277 $this->helperInstance = $helperInstance;
1281 * Getter for helper instance
1283 * @return $helperInstance An instance of a helper class
1285 public final function getHelperInstance () {
1286 return $this->helperInstance;
1290 * Setter for a Source instance
1292 * @param $sourceInstance An instance of a Source class
1295 protected final function setSourceInstance (Source $sourceInstance) {
1296 $this->sourceInstance = $sourceInstance;
1300 * Getter for a Source instance
1302 * @return $sourceInstance An instance of a Source class
1304 protected final function getSourceInstance () {
1305 return $this->sourceInstance;
1309 * Setter for a UrlSource instance
1311 * @param $sourceInstance An instance of a UrlSource class
1314 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1315 $this->urlSourceInstance = $urlSourceInstance;
1319 * Getter for a UrlSource instance
1321 * @return $urlSourceInstance An instance of a UrlSource class
1323 protected final function getUrlSourceInstance () {
1324 return $this->urlSourceInstance;
1328 * Getter for a InputStream instance
1330 * @param $inputStreamInstance The InputStream instance
1332 protected final function getInputStreamInstance () {
1333 return $this->inputStreamInstance;
1337 * Setter for a InputStream instance
1339 * @param $inputStreamInstance The InputStream instance
1342 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1343 $this->inputStreamInstance = $inputStreamInstance;
1347 * Getter for a OutputStream instance
1349 * @param $outputStreamInstance The OutputStream instance
1351 protected final function getOutputStreamInstance () {
1352 return $this->outputStreamInstance;
1356 * Setter for a OutputStream instance
1358 * @param $outputStreamInstance The OutputStream instance
1361 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1362 $this->outputStreamInstance = $outputStreamInstance;
1366 * Setter for handler instance
1368 * @param $handlerInstance An instance of a Handleable class
1371 protected final function setHandlerInstance (Handleable $handlerInstance) {
1372 $this->handlerInstance = $handlerInstance;
1376 * Getter for handler instance
1378 * @return $handlerInstance A Networkable instance
1380 protected final function getHandlerInstance () {
1381 return $this->handlerInstance;
1385 * Setter for visitor instance
1387 * @param $visitorInstance A Visitor instance
1390 protected final function setVisitorInstance (Visitor $visitorInstance) {
1391 $this->visitorInstance = $visitorInstance;
1395 * Getter for visitor instance
1397 * @return $visitorInstance A Visitor instance
1399 protected final function getVisitorInstance () {
1400 return $this->visitorInstance;
1404 * Setter for DHT instance
1406 * @param $dhtInstance A Distributable instance
1409 protected final function setDhtInstance (Distributable $dhtInstance) {
1410 $this->dhtInstance = $dhtInstance;
1414 * Getter for DHT instance
1416 * @return $dhtInstance A Distributable instance
1418 protected final function getDhtInstance () {
1419 return $this->dhtInstance;
1423 * Setter for raw package Data
1425 * @param $packageData Raw package Data
1428 public final function setPackageData (array $packageData) {
1429 $this->packageData = $packageData;
1433 * Getter for raw package Data
1435 * @return $packageData Raw package Data
1437 public function getPackageData () {
1438 return $this->packageData;
1443 * Setter for Iterator instance
1445 * @param $iteratorInstance An instance of an Iterator
1448 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1449 $this->iteratorInstance = $iteratorInstance;
1453 * Getter for Iterator instance
1455 * @return $iteratorInstance An instance of an Iterator
1457 public final function getIteratorInstance () {
1458 return $this->iteratorInstance;
1462 * Setter for FilePointer instance
1464 * @param $pointerInstance An instance of an FilePointer class
1467 protected final function setPointerInstance (FilePointer $pointerInstance) {
1468 $this->pointerInstance = $pointerInstance;
1472 * Getter for FilePointer instance
1474 * @return $pointerInstance An instance of an FilePointer class
1476 public final function getPointerInstance () {
1477 return $this->pointerInstance;
1481 * Unsets pointer instance which triggers a call of __destruct() if the
1482 * instance is still there. This is surely not fatal on already "closed"
1483 * file pointer instances.
1485 * I don't want to mess around with above setter by giving it a default
1486 * value NULL as setter should always explicitly only set (existing) object
1487 * instances and NULL is NULL.
1491 protected final function unsetPointerInstance () {
1492 // Simply it to NULL
1493 $this->pointerInstance = NULL;
1497 * Setter for Indexable instance
1499 * @param $indexInstance An instance of an Indexable class
1502 protected final function setIndexInstance (Indexable $indexInstance) {
1503 $this->indexInstance = $indexInstance;
1507 * Getter for Indexable instance
1509 * @return $indexInstance An instance of an Indexable class
1511 public final function getIndexInstance () {
1512 return $this->indexInstance;
1516 * Setter for Block instance
1518 * @param $blockInstance An instance of an Block class
1521 protected final function setBlockInstance (Block $blockInstance) {
1522 $this->blockInstance = $blockInstance;
1526 * Getter for Block instance
1528 * @return $blockInstance An instance of an Block class
1530 public final function getBlockInstance () {
1531 return $this->blockInstance;
1535 * Setter for Minable instance
1537 * @param $minableInstance A Minable instance
1540 protected final function setMinableInstance (Minable $minableInstance) {
1541 $this->minableInstance = $minableInstance;
1545 * Getter for minable instance
1547 * @return $minableInstance A Minable instance
1549 protected final function getMinableInstance () {
1550 return $this->minableInstance;
1554 * Setter for FrameworkDirectory instance
1556 * @param $directoryInstance A FrameworkDirectory instance
1559 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1560 $this->directoryInstance = $directoryInstance;
1564 * Getter for FrameworkDirectory instance
1566 * @return $directoryInstance A FrameworkDirectory instance
1568 protected final function getDirectoryInstance () {
1569 return $this->directoryInstance;
1573 * Setter for listener instance
1575 * @param $listenerInstance A Listenable instance
1578 protected final function setListenerInstance (Listenable $listenerInstance) {
1579 $this->listenerInstance = $listenerInstance;
1583 * Getter for listener instance
1585 * @return $listenerInstance A Listenable instance
1587 protected final function getListenerInstance () {
1588 return $this->listenerInstance;
1592 * Getter for communicator instance
1594 * @return $communicatorInstance An instance of a Communicator class
1596 public final function getCommunicatorInstance () {
1597 return $this->communicatorInstance;
1601 * Setter for communicator instance
1603 * @param $communicatorInstance An instance of a Communicator class
1606 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1607 $this->communicatorInstance = $communicatorInstance;
1611 * Setter for state instance
1613 * @param $stateInstance A Stateable instance
1616 public final function setStateInstance (Stateable $stateInstance) {
1617 $this->stateInstance = $stateInstance;
1621 * Getter for state instance
1623 * @return $stateInstance A Stateable instance
1625 public final function getStateInstance () {
1626 return $this->stateInstance;
1630 * Setter for output instance
1632 * @param $outputInstance The debug output instance
1635 public final function setOutputInstance (OutputStreamer $outputInstance) {
1636 $this->outputInstance = $outputInstance;
1640 * Getter for output instance
1642 * @return $outputInstance The debug output instance
1644 public final function getOutputInstance () {
1645 return $this->outputInstance;
1649 * Setter for command name
1651 * @param $commandName Last validated command name
1654 protected final function setCommandName ($commandName) {
1655 $this->commandName = $commandName;
1659 * Getter for command name
1661 * @return $commandName Last validated command name
1663 protected final function getCommandName () {
1664 return $this->commandName;
1668 * Setter for controller name
1670 * @param $controllerName Last validated controller name
1673 protected final function setControllerName ($controllerName) {
1674 $this->controllerName = $controllerName;
1678 * Getter for controller name
1680 * @return $controllerName Last validated controller name
1682 protected final function getControllerName () {
1683 return $this->controllerName;
1687 * Getter for protocol name
1689 * @return $protocolName Name of used protocol
1691 public final function getProtocolName () {
1692 return $this->protocolName;
1696 * Setter for protocol name
1698 * @param $protocolName Name of used protocol
1701 protected final function setProtocolName ($protocolName) {
1702 $this->protocolName = $protocolName;
1706 * Checks whether an object equals this object. You should overwrite this
1707 * method to implement own equality checks
1709 * @param $objectInstance An instance of a FrameworkInterface object
1710 * @return $equals Whether both objects equals
1712 public function equals (FrameworkInterface $objectInstance) {
1715 $this->__toString() == $objectInstance->__toString()
1717 $this->hashCode() == $objectInstance->hashCode()
1720 // Return the result
1725 * Generates a generic hash code of this class. You should really overwrite
1726 * this method with your own hash code generator code. But keep KISS in mind.
1728 * @return $hashCode A generic hash code respresenting this whole class
1730 public function hashCode () {
1732 return crc32($this->__toString());
1736 * Formats computer generated price values into human-understandable formats
1737 * with thousand and decimal separators.
1739 * @param $value The in computer format value for a price
1740 * @param $currency The currency symbol (use HTML-valid characters!)
1741 * @param $decNum Number of decimals after commata
1742 * @return $price The for the current language formated price string
1743 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1744 * thousands separator
1747 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1748 // Are all required attriutes set?
1749 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1750 // Throw an exception
1751 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1755 $value = (float) $value;
1757 // Reformat the US number
1758 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1760 // Return as string...
1765 * Appends a trailing slash to a string
1767 * @param $str A string (maybe) without trailing slash
1768 * @return $str A string with an auto-appended trailing slash
1770 public final function addMissingTrailingSlash ($str) {
1771 // Is there a trailing slash?
1772 if (substr($str, -1, 1) != '/') {
1776 // Return string with trailing slash
1781 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1782 * application helper instance (ApplicationHelper by default).
1784 * @param $applicationInstance An application helper instance or
1785 * null if we shall use the default
1786 * @return $templateInstance The template engine instance
1787 * @throws NullPointerException If the discovered application
1788 * instance is still null
1790 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1791 // Is the application instance set?
1792 if (is_null($applicationInstance)) {
1793 // Get the current instance
1794 $applicationInstance = $this->getApplicationInstance();
1797 if (is_null($applicationInstance)) {
1798 // Thrown an exception
1799 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1803 // Initialize the template engine
1804 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1806 // Return the prepared instance
1807 return $templateInstance;
1811 * Debugs this instance by putting out it's full content
1813 * @param $message Optional message to show in debug output
1816 public final function debugInstance ($message = '') {
1817 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1818 restore_error_handler();
1823 // Is a message set?
1824 if (!empty($message)) {
1825 // Construct message
1826 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1829 // Generate the output
1830 $content .= sprintf('<pre>%s</pre>',
1833 print_r($this, TRUE)
1839 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>',
1840 $this->__toString(),
1842 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1847 * Replaces control characters with printable output
1849 * @param $str String with control characters
1850 * @return $str Replaced string
1852 protected function replaceControlCharacters ($str) {
1855 chr(13), '[r]', str_replace(
1856 chr(10), '[n]', str_replace(
1866 * Output a partial stub message for the caller method
1868 * @param $message An optional message to display
1871 protected function partialStub ($message = '') {
1872 // Get the backtrace
1873 $backtrace = debug_backtrace();
1875 // Generate the class::method string
1876 $methodName = 'UnknownClass->unknownMethod';
1877 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1878 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1881 // Construct the full message
1882 $stubMessage = sprintf('[%s:] Partial stub!',
1886 // Is the extra message given?
1887 if (!empty($message)) {
1888 // Then add it as well
1889 $stubMessage .= ' Message: ' . $message;
1892 // Debug instance is there?
1893 if (!is_null($this->getDebugInstance())) {
1894 // Output stub message
1895 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1898 trigger_error($stubMessage);
1904 * Outputs a debug backtrace and stops further script execution
1906 * @param $message An optional message to output
1907 * @param $doExit Whether exit the program (TRUE is default)
1910 public function debugBackTrace ($message = '', $doExit = TRUE) {
1911 // Sorry, there is no other way getting this nice backtrace
1912 if (!empty($message)) {
1914 printf('Message: %s<br />' . PHP_EOL, $message);
1918 debug_print_backtrace();
1922 if ($doExit === TRUE) {
1928 * Creates an instance of a debugger instance
1930 * @param $className Name of the class (currently unsupported)
1931 * @param $lineNumber Line number where the call was made
1932 * @return $debugInstance An instance of a debugger class
1933 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1935 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1936 // Is the instance set?
1937 if (!Registry::getRegistry()->instanceExists('debug')) {
1938 // Init debug instance
1939 $debugInstance = NULL;
1943 // Get a debugger instance
1944 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1945 } catch (NullPointerException $e) {
1946 // Didn't work, no instance there
1947 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1950 // Empty string should be ignored and used for testing the middleware
1951 DebugMiddleware::getSelfInstance()->output('');
1953 // Set it in its own class. This will set it in the registry
1954 $debugInstance->setDebugInstance($debugInstance);
1956 // Get instance from registry
1957 $debugInstance = Registry::getRegistry()->getDebugInstance();
1961 return $debugInstance;
1965 * Simple output of a message with line-break
1967 * @param $message Message to output
1970 public function outputLine ($message) {
1972 print($message . PHP_EOL);
1976 * Outputs a debug message whether to debug instance (should be set!) or
1977 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1978 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1980 * @param $message Message we shall send out...
1981 * @param $doPrint Whether print or die here (default: print)
1982 * @paran $stripTags Whether to strip tags (default: FALSE)
1985 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1986 // Set debug instance to NULL
1987 $debugInstance = NULL;
1991 // Get debug instance
1992 $debugInstance = $this->getDebugInstance();
1993 } catch (NullPointerException $e) {
1994 // The debug instance is not set (yet)
1997 // Is the debug instance there?
1998 if (is_object($debugInstance)) {
1999 // Use debug output handler
2000 $debugInstance->output($message, $stripTags);
2002 if ($doPrint === FALSE) {
2003 // Die here if not printed
2007 // Are debug times enabled?
2008 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
2010 $message = $this->getPrintableExecutionTime() . $message;
2014 if ($doPrint === TRUE) {
2016 $this->outputLine($message);
2025 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2027 * @param $str The string, what ever it is needs to be converted
2028 * @return $className Generated class name
2030 public static final function convertToClassName ($str) {
2034 // Convert all dashes in underscores
2035 $str = self::convertDashesToUnderscores($str);
2037 // Now use that underscores to get classname parts for hungarian style
2038 foreach (explode('_', $str) as $strPart) {
2039 // Make the class name part lower case and first upper case
2040 $className .= ucfirst(strtolower($strPart));
2043 // Return class name
2048 * Converts dashes to underscores, e.g. useable for configuration entries
2050 * @param $str The string with maybe dashes inside
2051 * @return $str The converted string with no dashed, but underscores
2053 public static final function convertDashesToUnderscores ($str) {
2055 $str = str_replace('-', '_', $str);
2057 // Return converted string
2062 * Marks up the code by adding e.g. line numbers
2064 * @param $phpCode Unmarked PHP code
2065 * @return $markedCode Marked PHP code
2067 public function markupCode ($phpCode) {
2072 $errorArray = error_get_last();
2074 // Init the code with error message
2075 if (is_array($errorArray)) {
2077 $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>',
2078 basename($errorArray['file']),
2079 $errorArray['line'],
2080 $errorArray['message'],
2085 // Add line number to the code
2086 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2088 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2090 htmlentities($code, ENT_QUOTES)
2099 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2100 * beatiful for web-based front-ends. If null is given a message id
2101 * null_timestamp will be resolved and returned.
2103 * @param $timestamp Timestamp to prepare (filter) for display
2104 * @return $readable A readable timestamp
2106 public function doFilterFormatTimestamp ($timestamp) {
2107 // Default value to return
2110 // Is the timestamp null?
2111 if (is_null($timestamp)) {
2112 // Get a message string
2113 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2115 switch ($this->getLanguageInstance()->getLanguageCode()) {
2116 case 'de': // German format is a bit different to default
2117 // Split the GMT stamp up
2118 $dateTime = explode(' ', $timestamp );
2119 $dateArray = explode('-', $dateTime[0]);
2120 $timeArray = explode(':', $dateTime[1]);
2122 // Construct the timestamp
2123 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2133 default: // Default is pass-through
2134 $readable = $timestamp;
2144 * Filter a given number into a localized number
2146 * @param $value The raw value from e.g. database
2147 * @return $localized Localized value
2149 public function doFilterFormatNumber ($value) {
2150 // Generate it from config and localize dependencies
2151 switch ($this->getLanguageInstance()->getLanguageCode()) {
2152 case 'de': // German format is a bit different to default
2153 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2156 default: // US, etc.
2157 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2166 * "Getter" for databse entry
2168 * @return $entry An array with database entries
2169 * @throws NullPointerException If the database result is not found
2170 * @throws InvalidDatabaseResultException If the database result is invalid
2172 protected final function getDatabaseEntry () {
2173 // Is there an instance?
2174 if (!$this->getResultInstance() instanceof SearchableResult) {
2175 // Throw an exception here
2176 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2180 $this->getResultInstance()->rewind();
2182 // Do we have an entry?
2183 if ($this->getResultInstance()->valid() === FALSE) {
2184 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2185 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2189 $this->getResultInstance()->next();
2192 $entry = $this->getResultInstance()->current();
2199 * Getter for field name
2201 * @param $fieldName Field name which we shall get
2202 * @return $fieldValue Field value from the user
2203 * @throws NullPointerException If the result instance is null
2205 public final function getField ($fieldName) {
2206 // Default field value
2209 // Get result instance
2210 $resultInstance = $this->getResultInstance();
2212 // Is this instance null?
2213 if (is_null($resultInstance)) {
2214 // Then the user instance is no longer valid (expired cookies?)
2215 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2218 // Get current array
2219 $fieldArray = $resultInstance->current();
2220 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2222 // Convert dashes to underscore
2223 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2225 // Does the field exist?
2226 if ($this->isFieldSet($fieldName)) {
2228 $fieldValue = $fieldArray[$fieldName2];
2229 } elseif (defined('DEVELOPER')) {
2230 // Missing field entry, may require debugging
2231 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2233 // Missing field entry, may require debugging
2234 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2242 * Checks if given field is set
2244 * @param $fieldName Field name to check
2245 * @return $isSet Whether the given field name is set
2246 * @throws NullPointerException If the result instance is null
2248 public function isFieldSet ($fieldName) {
2249 // Get result instance
2250 $resultInstance = $this->getResultInstance();
2252 // Is this instance null?
2253 if (is_null($resultInstance)) {
2254 // Then the user instance is no longer valid (expired cookies?)
2255 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2258 // Get current array
2259 $fieldArray = $resultInstance->current();
2260 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2262 // Convert dashes to underscore
2263 $fieldName = self::convertDashesToUnderscores($fieldName);
2266 $isSet = isset($fieldArray[$fieldName]);
2273 * Flushs all pending updates to the database layer
2277 public function flushPendingUpdates () {
2278 // Get result instance
2279 $resultInstance = $this->getResultInstance();
2281 // Do we have data to update?
2282 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2283 // Get wrapper class name config entry
2284 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2286 // Create object instance
2287 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2289 // Yes, then send the whole result to the database layer
2290 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2295 * Outputs a deprecation warning to the developer.
2297 * @param $message The message we shall output to the developer
2299 * @todo Write a logging mechanism for productive mode
2301 public function deprecationWarning ($message) {
2302 // Is developer mode active?
2303 if (defined('DEVELOPER')) {
2304 // Debug instance is there?
2305 if (!is_null($this->getDebugInstance())) {
2306 // Output stub message
2307 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2310 trigger_error($message . "<br />\n");
2314 // @TODO Finish this part!
2315 $this->partialStub('Developer mode inactive. Message:' . $message);
2320 * Checks whether the given PHP extension is loaded
2322 * @param $phpExtension The PHP extension we shall check
2323 * @return $isLoaded Whether the PHP extension is loaded
2325 public final function isPhpExtensionLoaded ($phpExtension) {
2327 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2334 * "Getter" as a time() replacement but with milliseconds. You should use this
2335 * method instead of the encapsulated getimeofday() function.
2337 * @return $milliTime Timestamp with milliseconds
2339 public function getMilliTime () {
2340 // Get the time of day as float
2341 $milliTime = gettimeofday(TRUE);
2348 * Idles (sleeps) for given milliseconds
2350 * @return $hasSlept Whether it goes fine
2352 public function idle ($milliSeconds) {
2353 // Sleep is fine by default
2356 // Idle so long with found function
2357 if (function_exists('time_sleep_until')) {
2358 // Get current time and add idle time
2359 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2361 // New PHP 5.1.0 function found, ignore errors
2362 $hasSlept = @time_sleep_until($sleepUntil);
2365 * My Sun station doesn't have that function even with latest PHP
2368 usleep($milliSeconds * 1000);
2375 * Converts a hexadecimal string, even with negative sign as first string to
2376 * a decimal number using BC functions.
2378 * This work is based on comment #86673 on php.net documentation page at:
2379 * <http://de.php.net/manual/en/function.dechex.php#86673>
2381 * @param $hex Hexadecimal string
2382 * @return $dec Decimal number
2384 protected function hex2dec ($hex) {
2385 // Convert to all lower-case
2386 $hex = strtolower($hex);
2388 // Detect sign (negative/positive numbers)
2390 if (substr($hex, 0, 1) == '-') {
2392 $hex = substr($hex, 1);
2395 // Decode the hexadecimal string into a decimal number
2397 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2398 $factor = self::$hexdec[substr($hex, $i, 1)];
2399 $dec = bcadd($dec, bcmul($factor, $e));
2402 // Return the decimal number
2403 return $sign . $dec;
2407 * Converts even very large decimal numbers, also signed, to a hexadecimal
2410 * This work is based on comment #97756 on php.net documentation page at:
2411 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2413 * @param $dec Decimal number, even with negative sign
2414 * @param $maxLength Optional maximum length of the string
2415 * @return $hex Hexadecimal string
2417 protected function dec2hex ($dec, $maxLength = 0) {
2418 // maxLength can be zero or devideable by 2
2419 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2421 // Detect sign (negative/positive numbers)
2428 // Encode the decimal number into a hexadecimal string
2431 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2433 } while ($dec >= 1);
2436 * Leading zeros are required for hex-decimal "numbers". In some
2437 * situations more leading zeros are wanted, so check for both
2440 if ($maxLength > 0) {
2441 // Prepend more zeros
2442 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2443 } elseif ((strlen($hex) % 2) != 0) {
2444 // Only make string's length dividable by 2
2448 // Return the hexadecimal string
2449 return $sign . $hex;
2453 * Converts a ASCII string (0 to 255) into a decimal number.
2455 * @param $asc The ASCII string to be converted
2456 * @return $dec Decimal number
2458 protected function asc2dec ($asc) {
2459 // Convert it into a hexadecimal number
2460 $hex = bin2hex($asc);
2462 // And back into a decimal number
2463 $dec = $this->hex2dec($hex);
2470 * Converts a decimal number into an ASCII string.
2472 * @param $dec Decimal number
2473 * @return $asc An ASCII string
2475 protected function dec2asc ($dec) {
2476 // First convert the number into a hexadecimal string
2477 $hex = $this->dec2hex($dec);
2479 // Then convert it into the ASCII string
2480 $asc = $this->hex2asc($hex);
2487 * Converts a hexadecimal number into an ASCII string. Negative numbers
2490 * @param $hex Hexadecimal string
2491 * @return $asc An ASCII string
2493 protected function hex2asc ($hex) {
2494 // Check for length, it must be devideable by 2
2495 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2496 assert((strlen($hex) % 2) == 0);
2500 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2501 // Get the decimal number of the chunk
2502 $part = hexdec(substr($hex, $idx, 2));
2504 // Add it to the final string
2508 // Return the final string
2513 * Checks whether the given encoded data was encoded with Base64
2515 * @param $encodedData Encoded data we shall check
2516 * @return $isBase64 Whether the encoded data is Base64
2518 protected function isBase64Encoded ($encodedData) {
2520 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2527 * "Getter" to get response/request type from analysis of the system.
2529 * @return $responseType Analyzed response type
2531 protected static function getResponseTypeFromSystem () {
2532 // Default is console
2533 $responseType = 'console';
2535 // Is 'HTTP_HOST' set?
2536 if (isset($_SERVER['HTTP_HOST'])) {
2538 * Then it is a HTML response/request as RSS and so on may be
2539 * transfered over HTTP as well.
2541 $responseType = 'html';
2545 return $responseType;
2549 * Gets a cache key from Criteria instance
2551 * @param $criteriaInstance An instance of a Criteria class
2552 * @param $onlyKeys Only use these keys for a cache key
2553 * @return $cacheKey A cache key suitable for lookup/storage purposes
2555 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2557 $cacheKey = sprintf('%s@%s',
2558 $this->__toString(),
2559 $criteriaInstance->getCacheKey($onlyKeys)
2563 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2568 * Getter for startup time in miliseconds
2570 * @return $startupTime Startup time in miliseconds
2572 protected function getStartupTime () {
2573 return self::$startupTime;
2577 * "Getter" for a printable currently execution time in nice braces
2579 * @return $executionTime Current execution time in nice braces
2581 protected function getPrintableExecutionTime () {
2582 // Caculate the execution time
2583 $executionTime = microtime(TRUE) - $this->getStartupTime();
2585 // Pack it in nice braces
2586 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2589 return $executionTime;
2593 * Hashes a given string with a simple but stronger hash function (no salt)
2594 * and hex-encode it.
2596 * @param $str The string to be hashed
2597 * @return $hash The hash from string $str
2599 public static final function hash ($str) {
2600 // Hash given string with (better secure) hasher
2601 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2608 * "Getter" for length of hash() output. This will be "cached" to speed up
2611 * @return $length Length of hash() output
2613 public static final function getHashLength () {
2615 if (is_null(self::$hashLength)) {
2616 // No, then hash a string and save its length.
2617 self::$hashLength = strlen(self::hash('abc123'));
2621 return self::$hashLength;
2625 * Checks whether the given number is really a number (only chars 0-9).
2627 * @param $num A string consisting only chars between 0 and 9
2628 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2629 * @param $assertMismatch Whether to assert mismatches
2630 * @return $ret The (hopefully) secured numbered value
2632 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2633 // Filter all numbers out
2634 $ret = preg_replace('/[^0123456789]/', '', $num);
2637 if ($castValue === TRUE) {
2638 // Cast to biggest numeric type
2639 $ret = (double) $ret;
2642 // Assert only if requested
2643 if ($assertMismatch === TRUE) {
2644 // Has the whole value changed?
2645 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2653 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2655 * @param $num A string consisting only chars between 0 and 9
2656 * @param $assertMismatch Whether to assert mismatches
2657 * @return $ret The (hopefully) secured hext-numbered value
2659 public function hexval ($num, $assertMismatch = FALSE) {
2660 // Filter all numbers out
2661 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2663 // Assert only if requested
2664 if ($assertMismatch === TRUE) {
2665 // Has the whole value changed?
2666 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2674 * Checks whether start/end marker are set
2676 * @param $data Data to be checked
2677 * @return $isset Whether start/end marker are set
2679 public final function ifStartEndMarkersSet ($data) {
2681 $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));
2683 // ... and return it
2688 * Determines if an element is set in the generic array
2690 * @param $keyGroup Main group for the key
2691 * @param $subGroup Sub group for the key
2692 * @param $key Key to check
2693 * @param $element Element to check
2694 * @return $isset Whether the given key is set
2696 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2698 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2701 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2707 * Determines if a key is set in the generic array
2709 * @param $keyGroup Main group for the key
2710 * @param $subGroup Sub group for the key
2711 * @param $key Key to check
2712 * @return $isset Whether the given key is set
2714 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2716 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2719 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2727 * Determines if a group is set in the generic array
2729 * @param $keyGroup Main group
2730 * @param $subGroup Sub group
2731 * @return $isset Whether the given group is set
2733 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2735 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2738 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2745 * Getter for sub key group
2747 * @param $keyGroup Main key group
2748 * @param $subGroup Sub key group
2749 * @return $array An array with all array elements
2751 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2753 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2754 // No, then abort here
2755 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2760 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2763 return $this->genericArray[$keyGroup][$subGroup];
2767 * Unsets a given key in generic array
2769 * @param $keyGroup Main group for the key
2770 * @param $subGroup Sub group for the key
2771 * @param $key Key to unset
2774 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2776 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2779 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2783 * Unsets a given element in generic array
2785 * @param $keyGroup Main group for the key
2786 * @param $subGroup Sub group for the key
2787 * @param $key Key to unset
2788 * @param $element Element to unset
2791 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2793 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2796 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2800 * Append a string to a given generic array key
2802 * @param $keyGroup Main group for the key
2803 * @param $subGroup Sub group for the key
2804 * @param $key Key to unset
2805 * @param $value Value to add/append
2808 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2810 //* 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);
2812 // Is it already there?
2813 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2815 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2818 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2823 * Append a string to a given generic array element
2825 * @param $keyGroup Main group for the key
2826 * @param $subGroup Sub group for the key
2827 * @param $key Key to unset
2828 * @param $element Element to check
2829 * @param $value Value to add/append
2832 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2834 //* 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);
2836 // Is it already there?
2837 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2839 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2842 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2847 * Sets a string in a given generic array element
2849 * @param $keyGroup Main group for the key
2850 * @param $subGroup Sub group for the key
2851 * @param $key Key to unset
2852 * @param $element Element to check
2853 * @param $value Value to add/append
2856 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2858 //* 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);
2861 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2865 * Initializes given generic array group
2867 * @param $keyGroup Main group for the key
2868 * @param $subGroup Sub group for the key
2869 * @param $key Key to use
2870 * @param $forceInit Optionally force initialization
2873 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2875 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2877 // Is it already set?
2878 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2879 // Already initialized
2880 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2885 $this->genericArray[$keyGroup][$subGroup] = array();
2889 * Initializes given generic array key
2891 * @param $keyGroup Main group for the key
2892 * @param $subGroup Sub group for the key
2893 * @param $key Key to use
2894 * @param $forceInit Optionally force initialization
2897 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2899 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2901 // Is it already set?
2902 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2903 // Already initialized
2904 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2909 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2913 * Initializes given generic array element
2915 * @param $keyGroup Main group for the key
2916 * @param $subGroup Sub group for the key
2917 * @param $key Key to use
2918 * @param $element Element to use
2919 * @param $forceInit Optionally force initialization
2922 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2924 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2926 // Is it already set?
2927 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2928 // Already initialized
2929 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2934 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2938 * Pushes an element to a generic key
2940 * @param $keyGroup Main group for the key
2941 * @param $subGroup Sub group for the key
2942 * @param $key Key to use
2943 * @param $value Value to add/append
2944 * @return $count Number of array elements
2946 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2948 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2951 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2953 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2957 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2960 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2961 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2966 * Pushes an element to a generic array element
2968 * @param $keyGroup Main group for the key
2969 * @param $subGroup Sub group for the key
2970 * @param $key Key to use
2971 * @param $element Element to check
2972 * @param $value Value to add/append
2973 * @return $count Number of array elements
2975 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2977 //* 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));
2980 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2982 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2986 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2989 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2990 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2995 * Pops an element from a generic group
2997 * @param $keyGroup Main group for the key
2998 * @param $subGroup Sub group for the key
2999 * @param $key Key to unset
3000 * @return $value Last "popped" value
3002 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
3004 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3007 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3009 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3014 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
3017 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3018 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3023 * Shifts an element from a generic group
3025 * @param $keyGroup Main group for the key
3026 * @param $subGroup Sub group for the key
3027 * @param $key Key to unset
3028 * @return $value Last "popped" value
3030 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3032 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3035 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3037 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3042 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3045 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3046 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3051 * Count generic array group
3053 * @param $keyGroup Main group for the key
3054 * @return $count Count of given group
3056 protected final function countGenericArray ($keyGroup) {
3058 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3061 if (!isset($this->genericArray[$keyGroup])) {
3063 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3068 $count = count($this->genericArray[$keyGroup]);
3071 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3078 * Count generic array sub group
3080 * @param $keyGroup Main group for the key
3081 * @param $subGroup Sub group for the key
3082 * @return $count Count of given group
3084 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3086 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3089 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3091 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3096 $count = count($this->genericArray[$keyGroup][$subGroup]);
3099 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3106 * Count generic array elements
3108 * @param $keyGroup Main group for the key
3109 * @param $subGroup Sub group for the key
3110 * @para $key Key to count
3111 * @return $count Count of given key
3113 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3115 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3118 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3120 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3122 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3124 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3129 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3132 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3139 * Getter for whole generic group array
3141 * @param $keyGroup Key group to get
3142 * @return $array Whole generic array group
3144 protected final function getGenericArray ($keyGroup) {
3146 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3149 if (!isset($this->genericArray[$keyGroup])) {
3151 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3156 return $this->genericArray[$keyGroup];
3160 * Setter for generic array key
3162 * @param $keyGroup Key group to get
3163 * @param $subGroup Sub group for the key
3164 * @param $key Key to unset
3165 * @param $value Mixed value from generic array element
3168 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3170 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3173 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3177 * Getter for generic array key
3179 * @param $keyGroup Key group to get
3180 * @param $subGroup Sub group for the key
3181 * @param $key Key to unset
3182 * @return $value Mixed value from generic array element
3184 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3186 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3189 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3191 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3196 return $this->genericArray[$keyGroup][$subGroup][$key];
3200 * Sets a value in given generic array key/element
3202 * @param $keyGroup Main group for the key
3203 * @param $subGroup Sub group for the key
3204 * @param $key Key to set
3205 * @param $element Element to set
3206 * @param $value Value to set
3209 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3211 //* 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));
3214 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3218 * Getter for generic array element
3220 * @param $keyGroup Key group to get
3221 * @param $subGroup Sub group for the key
3222 * @param $key Key to look for
3223 * @param $element Element to look for
3224 * @return $value Mixed value from generic array element
3226 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3228 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3231 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3233 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3238 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3242 * Checks if a given sub group is valid (array)
3244 * @param $keyGroup Key group to get
3245 * @param $subGroup Sub group for the key
3246 * @return $isValid Whether given sub group is valid
3248 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3250 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3253 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3260 * Checks if a given key is valid (array)
3262 * @param $keyGroup Key group to get
3263 * @param $subGroup Sub group for the key
3264 * @param $key Key to check
3265 * @return $isValid Whether given sub group is valid
3267 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3269 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3272 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3279 * Initializes the web output instance
3283 protected function initWebOutputInstance () {
3284 // Get application instance
3285 $applicationInstance = Registry::getRegistry()->getInstance('app');
3287 // Is this a response instance?
3288 if ($this instanceof Responseable) {
3289 // Then set it in application instance
3290 $applicationInstance->setResponseInstance($this);
3293 // Init web output instance
3294 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3297 $this->setWebOutputInstance($outputInstance);
3301 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3303 * @param $boolean Boolean value
3304 * @return $translated Translated boolean value
3306 public static final function translateBooleanToYesNo ($boolean) {
3307 // Make sure it is really boolean
3308 assert(is_bool($boolean));
3311 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3313 // ... and return it
3318 * Encodes raw data (almost any type) by "serializing" it and then pack it
3319 * into a "binary format".
3321 * @param $rawData Raw data (almost any type)
3322 * @return $encoded Encoded data
3324 protected function encodeData ($rawData) {
3325 // Make sure no objects or resources pass through
3326 assert(!is_object($rawData));
3327 assert(!is_resource($rawData));
3329 // First "serialize" it (json_encode() is faster than serialize())
3330 $encoded = $this->packString(json_encode($rawData));
3337 * Pack a string into a "binary format". Please execuse me that this is
3338 * widely undocumented. :-(
3340 * @param $str Unpacked string
3341 * @return $packed Packed string
3342 * @todo Improve documentation
3344 protected function packString ($str) {
3346 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3348 // First compress the string (gzcompress is okay)
3349 $str = gzcompress($str);
3354 // And start the "encoding" loop
3355 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3357 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3358 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3360 if (($idx + $i) <= strlen($str)) {
3361 $ord = ord(substr($str, ($idx + $i), 1));
3363 $add = $ord * pow(256, $factor);
3367 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3371 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3372 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3374 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3375 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3381 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3386 * Checks whether the given file/path is in open_basedir(). This does not
3387 * gurantee that the file is actually readable and/or writeable. If you need
3388 * such gurantee then please use isReadableFile() instead.
3390 * @param $filePathName Name of the file/path to be checked
3391 * @return $isReachable Whether it is within open_basedir()
3393 protected static function isReachableFilePath ($filePathName) {
3394 // Is not reachable by default
3395 $isReachable = FALSE;
3397 // Get open_basedir parameter
3398 $openBaseDir = ini_get('open_basedir');
3401 if (!empty($openBaseDir)) {
3402 // Check all entries
3403 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3404 // Check on existence
3405 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3407 $isReachable = TRUE;
3411 // If open_basedir is not set, all is allowed
3412 $isReachable = TRUE;
3416 return $isReachable;
3420 * Checks whether the give file is within open_basedir() (done by
3421 * isReachableFilePath()), is actually a file and is readable.
3423 * @param $fileName Name of the file to be checked
3424 * @return $isReadable Whether the file is readable (and therefor exists)
3426 public static function isReadableFile ($fileName) {
3427 // Default is not readable
3428 $isReadable = FALSE;
3430 // Is within parameters, so check if it is a file and readable
3431 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3438 * Creates a full-qualified file name (FQFN) for given file name by adding
3439 * a configured temporary file path to it.
3441 * @param $fileName Name for temporary file
3442 * @return $fqfn Full-qualified file name
3443 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3444 * @throws FileIoException If the file cannot be written
3446 protected static function createTempPathForFile ($fileName) {
3448 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3450 // Is the path writeable?
3451 if (!is_writable($basePath)) {
3452 // Path is write-protected
3453 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3457 $fqfn = $basePath . '/' . $fileName;
3460 if (!self::isReachableFilePath($fqfn)) {
3462 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3470 * "Getter" for a printable state name
3472 * @return $stateName Name of the node's state in a printable format
3474 public final function getPrintableState () {
3475 // Default is 'null'
3476 $stateName = 'null';
3478 // Get the state instance
3479 $stateInstance = $this->getStateInstance();
3481 // Is it an instance of Stateable?
3482 if ($stateInstance instanceof Stateable) {
3483 // Then use that state name
3484 $stateName = $stateInstance->getStateName();
3492 * Handles socket error for given socket resource and peer data. This method
3493 * validates $socketResource if it is a valid resource (see is_resource())
3494 * but assumes valid data in array $recipientData, except that
3495 * count($recipientData) is always 2.
3497 * @param $method Value of __METHOD__ from calling method
3498 * @param $line Value of __LINE__ from calling method
3499 * @param $socketResource A valid socket resource
3500 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3502 * @throws InvalidSocketException If $socketResource is no socket resource
3503 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3504 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3506 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3507 // This method handles only socket resources
3508 if (!is_resource($socketResource)) {
3509 // No resource, abort here
3510 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3513 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3514 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3515 assert(isset($socketData[0]));
3516 assert(isset($socketData[1]));
3518 // Get error code for first validation (0 is not an error)
3519 $errorCode = socket_last_error($socketResource);
3521 // If the error code is zero, someone called this method without an error
3522 if ($errorCode == 0) {
3523 // No error detected (or previously cleared outside this method)
3524 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3527 // Get handler (method) name
3528 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3530 // Call-back the error handler method
3531 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3533 // Finally clear the error because it has been handled
3534 socket_clear_error($socketResource);