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\Listener\Listenable;
23 use CoreFramework\Lists\Listable;
24 use CoreFramework\Loader\ClassLoader;
25 use CoreFramework\Manager\ManageableApplication;
26 use CoreFramework\Middleware\Compressor\CompressorChannel;
27 use CoreFramework\Middleware\Debug\DebugMiddleware;
28 use CoreFramework\Parser\Parseable;
29 use CoreFramework\Registry\Register;
30 use CoreFramework\Registry\Registry;
31 use CoreFramework\Request\Requestable;
32 use CoreFramework\Resolver\Resolver;
33 use CoreFramework\Result\Database\CachedDatabaseResult;
34 use CoreFramework\Result\Search\SearchableResult;
35 use CoreFramework\Response\Responseable;
36 use CoreFramework\Stream\Output\OutputStreamer;
37 use CoreFramework\Template\CompileableTemplate;
38 use CoreFramework\User\ManageableAccount;
39 use CoreFramework\Visitor\Visitor;
40 use CoreFramework\Wrapper\Database\DatabaseWrapper;
47 * The simulator system class is the super class of all other classes. This
48 * class handles saving of games etc.
50 * @author Roland Haeder <webmaster@shipsimu.org>
52 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
53 * @license GNU GPL 3.0 or any newer version
54 * @link http://www.shipsimu.org
56 * This program is free software: you can redistribute it and/or modify
57 * it under the terms of the GNU General Public License as published by
58 * the Free Software Foundation, either version 3 of the License, or
59 * (at your option) any later version.
61 * This program is distributed in the hope that it will be useful,
62 * but WITHOUT ANY WARRANTY; without even the implied warranty of
63 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
64 * GNU General Public License for more details.
66 * You should have received a copy of the GNU General Public License
67 * along with this program. If not, see <http://www.gnu.org/licenses/>.
69 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
71 * Length of output from hash()
73 private static $hashLength = NULL;
78 private $realClass = 'BaseFrameworkSystem';
81 * Instance of a Requestable class
83 private $requestInstance = NULL;
86 * Instance of a Responseable class
88 private $responseInstance = NULL;
91 * Search criteria instance
93 private $searchInstance = NULL;
96 * Update criteria instance
98 private $updateInstance = NULL;
101 * The file I/O instance for the template loader
103 private $fileIoInstance = NULL;
108 private $resolverInstance = NULL;
111 * Template engine instance
113 private $templateInstance = NULL;
116 * Database result instance
118 private $resultInstance = NULL;
121 * Instance for user class
123 private $userInstance = NULL;
126 * A controller instance
128 private $controllerInstance = NULL;
133 private $rngInstance = NULL;
136 * Instance of a crypto helper
138 private $cryptoInstance = NULL;
141 * Instance of an Iterator class
143 private $iteratorInstance = NULL;
146 * Instance of the list
148 private $listInstance = NULL;
153 private $menuInstance = NULL;
156 * Instance of the image
158 private $imageInstance = NULL;
161 * Instance of the stacker
163 private $stackInstance = NULL;
166 * A Compressor instance
168 private $compressorInstance = NULL;
171 * A Parseable instance
173 private $parserInstance = NULL;
176 * A HandleableProtocol instance
178 private $protocolInstance = NULL;
181 * A database wrapper instance
183 private $databaseInstance = NULL;
186 * A helper instance for the form
188 private $helperInstance = NULL;
191 * An instance of a Source class
193 private $sourceInstance = NULL;
196 * An instance of a UrlSource class
198 private $urlSourceInstance = NULL;
201 * An instance of a InputStream class
203 private $inputStreamInstance = NULL;
206 * An instance of a OutputStream class
208 private $outputStreamInstance = NULL;
211 * Networkable handler instance
213 private $handlerInstance = NULL;
216 * Visitor handler instance
218 private $visitorInstance = NULL;
223 private $dhtInstance = NULL;
226 * An instance of a database wrapper class
228 private $wrapperInstance = NULL;
231 * An instance of a file I/O pointer class (not handler)
233 private $pointerInstance = NULL;
236 * An instance of an Indexable class
238 private $indexInstance = NULL;
241 * An instance of a Block class
243 private $blockInstance = NULL;
248 private $minableInstance = NULL;
251 * A FrameworkDirectory instance
253 private $directoryInstance = NULL;
258 private $listenerInstance = NULL;
261 * An instance of a communicator
263 private $communicatorInstance = NULL;
266 * The concrete output instance
268 private $outputInstance = NULL;
273 private $stateInstance = NULL;
276 * Thousands separator
278 private $thousands = '.'; // German
283 private $decimals = ','; // German
288 private $socketResource = FALSE;
291 * Regular expression to use for validation
293 private $regularExpression = '';
298 private $packageData = array();
303 private $genericArray = array();
308 private $commandName = '';
313 private $controllerName = '';
316 * Name of used protocol
318 private $protocolName = 'invalid';
321 * Array with bitmasks and such for pack/unpack methods to support both
322 * 32-bit and 64-bit systems
324 private $packingData = array(
327 'left' => 0xffff0000,
328 'right' => 0x0000ffff,
334 'left' => 0xffffffff00000000,
335 'right' => 0x00000000ffffffff,
342 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
344 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
346 private $archArrayElement = FALSE;
348 /***********************
349 * Exception codes.... *
350 ***********************/
352 // @todo Try to clean these constants up
353 const EXCEPTION_IS_NULL_POINTER = 0x001;
354 const EXCEPTION_IS_NO_OBJECT = 0x002;
355 const EXCEPTION_IS_NO_ARRAY = 0x003;
356 const EXCEPTION_MISSING_METHOD = 0x004;
357 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
358 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
359 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
360 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
361 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
362 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
363 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
364 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
365 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
366 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
367 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
368 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
369 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
370 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
371 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
372 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
373 const EXCEPTION_PATH_NOT_FOUND = 0x015;
374 const EXCEPTION_INVALID_PATH_NAME = 0x016;
375 const EXCEPTION_READ_PROTECED_PATH = 0x017;
376 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
377 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
378 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
379 const EXCEPTION_INVALID_RESOURCE = 0x01b;
380 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
381 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
382 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
383 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
384 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
385 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
386 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
387 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
388 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
389 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
390 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
391 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
392 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
393 const EXCEPTION_INVALID_STRING = 0x029;
394 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
395 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
396 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
397 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
398 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
399 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
400 const EXCEPTION_MISSING_ELEMENT = 0x030;
401 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
402 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
403 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
404 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
405 const EXCEPTION_FATAL_ERROR = 0x035;
406 const EXCEPTION_FILE_NOT_FOUND = 0x036;
407 const EXCEPTION_ASSERTION_FAILED = 0x037;
408 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
409 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
410 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
411 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
412 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
413 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
416 * Hexadecimal->Decimal translation array
418 private static $hexdec = array(
438 * Decimal->hexadecimal translation array
440 private static $dechex = array(
460 * Startup time in miliseconds
462 private static $startupTime = 0;
465 * Protected super constructor
467 * @param $className Name of the class
470 protected function __construct ($className) {
472 $this->setRealClass($className);
474 // Set configuration instance if no registry ...
475 if (!$this instanceof Register) {
476 // ... because registries doesn't need to be configured
477 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
480 // Is the startup time set? (0 cannot be TRUE anymore)
481 if (self::$startupTime == 0) {
483 self::$startupTime = microtime(TRUE);
487 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
491 * Destructor for all classes. You should not call this method on your own.
495 public function __destruct () {
496 // Flush any updated entries to the database
497 $this->flushPendingUpdates();
499 // Is this object already destroyed?
500 if ($this->__toString() != 'DestructedObject') {
501 // Destroy all informations about this class but keep some text about it alive
502 $this->setRealClass('DestructedObject');
503 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
504 // Already destructed object
505 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
510 // Do not call this twice
511 trigger_error(__METHOD__ . ': Called twice.');
517 * The __call() method where all non-implemented methods end up
519 * @param $methodName Name of the missing method
520 * @args $args Arguments passed to the method
523 public final function __call ($methodName, $args) {
524 return self::__callStatic($methodName, $args);
528 * The __callStatic() method where all non-implemented static methods end up
530 * @param $methodName Name of the missing method
531 * @args $args Arguments passed to the method
534 public static final function __callStatic ($methodName, $args) {
536 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
538 // Init argument string
541 // Is it NULL, empty or an array?
542 if (is_null($args)) {
544 $argsString = 'NULL';
545 } elseif (is_array($args)) {
549 // Some arguments are there
550 foreach ($args as $arg) {
551 // Add data about the argument
552 $argsString .= gettype($arg) . ':';
555 // Found a NULL argument
556 $argsString .= 'NULL';
557 } elseif (is_string($arg)) {
558 // Add length for strings
559 $argsString .= strlen($arg);
560 } elseif ((is_int($arg)) || (is_float($arg))) {
563 } elseif (is_array($arg)) {
564 // .. or size if array
565 $argsString .= count($arg);
566 } elseif (is_object($arg)) {
568 $reflection = new ReflectionClass($arg);
570 // Is an other object, maybe no __toString() available
571 $argsString .= $reflection->getName();
572 } elseif ($arg === TRUE) {
573 // ... is boolean 'TRUE'
574 $argsString .= 'TRUE';
575 } elseif ($arg === FALSE) {
576 // ... is boolean 'FALSE'
577 $argsString .= 'FALSE';
580 // Comma for next one
585 if (substr($argsString, -2, 1) == ',') {
586 $argsString = substr($argsString, 0, -2);
592 // Invalid arguments!
593 $argsString = '!INVALID:' . gettype($args) . '!';
596 // Output stub message
597 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
598 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
608 * Getter for $realClass
610 * @return $realClass The name of the real class (not BaseFrameworkSystem)
612 public function __toString () {
613 return $this->realClass;
617 * Magic method to catch setting of missing but set class fields/attributes
619 * @param $name Name of the field/attribute
620 * @param $value Value to store
623 public final function __set ($name, $value) {
624 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
627 print_r($value, TRUE)
632 * Magic method to catch getting of missing fields/attributes
634 * @param $name Name of the field/attribute
637 public final function __get ($name) {
638 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
644 * Magic method to catch unsetting of missing fields/attributes
646 * @param $name Name of the field/attribute
649 public final function __unset ($name) {
650 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
656 * Magic method to catch object serialization
658 * @return $unsupported Unsupported method
659 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
661 public final function __sleep () {
662 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
666 * Magic method to catch object deserialization
668 * @return $unsupported Unsupported method
669 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
671 public final function __wakeup () {
672 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
676 * Magic method to catch calls when an object instance is called
678 * @return $unsupported Unsupported method
679 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
681 public final function __invoke () {
682 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
686 * Setter for the real class name
688 * @param $realClass Class name (string)
691 public final function setRealClass ($realClass) {
693 $this->realClass = (string) $realClass;
697 * Setter for database result instance
699 * @param $resultInstance An instance of a database result class
701 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
703 protected final function setResultInstance (SearchableResult $resultInstance) {
704 $this->resultInstance = $resultInstance;
708 * Getter for database result instance
710 * @return $resultInstance An instance of a database result class
712 public final function getResultInstance () {
713 return $this->resultInstance;
717 * Setter for template engine instances
719 * @param $templateInstance An instance of a template engine class
722 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
723 $this->templateInstance = $templateInstance;
727 * Getter for template engine instances
729 * @return $templateInstance An instance of a template engine class
731 protected final function getTemplateInstance () {
732 return $this->templateInstance;
736 * Setter for search instance
738 * @param $searchInstance Searchable criteria instance
741 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
742 $this->searchInstance = $searchInstance;
746 * Getter for search instance
748 * @return $searchInstance Searchable criteria instance
750 public final function getSearchInstance () {
751 return $this->searchInstance;
755 * Setter for update instance
757 * @param $updateInstance An instance of a LocalUpdateCriteria clase
760 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
761 $this->updateInstance = $updateInstance;
765 * Getter for update instance
767 * @return $updateInstance Updateable criteria instance
769 public final function getUpdateInstance () {
770 return $this->updateInstance;
774 * Setter for resolver instance
776 * @param $resolverInstance Instance of a command resolver class
779 public final function setResolverInstance (Resolver $resolverInstance) {
780 $this->resolverInstance = $resolverInstance;
784 * Getter for resolver instance
786 * @return $resolverInstance Instance of a command resolver class
788 public final function getResolverInstance () {
789 return $this->resolverInstance;
793 * Setter for language instance
795 * @param $configInstance The configuration instance which shall
796 * be FrameworkConfiguration
799 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
800 Registry::getRegistry()->addInstance('config', $configInstance);
804 * Getter for configuration instance
806 * @return $configInstance Configuration instance
808 public final function getConfigInstance () {
809 $configInstance = Registry::getRegistry()->getInstance('config');
810 return $configInstance;
814 * Setter for debug instance
816 * @param $debugInstance The instance for debug output class
819 public final function setDebugInstance (DebugMiddleware $debugInstance) {
820 Registry::getRegistry()->addInstance('debug', $debugInstance);
824 * Getter for debug instance
826 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
828 public final function getDebugInstance () {
829 // Get debug instance
830 $debugInstance = Registry::getRegistry()->getInstance('debug');
833 return $debugInstance;
837 * Setter for web output instance
839 * @param $webInstance The instance for web output class
842 public final function setWebOutputInstance (OutputStreamer $webInstance) {
843 Registry::getRegistry()->addInstance('web_output', $webInstance);
847 * Getter for web output instance
849 * @return $webOutputInstance - Instance to class WebOutput
851 public final function getWebOutputInstance () {
852 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
853 return $webOutputInstance;
857 * Setter for database instance
859 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
862 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
863 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
867 * Getter for database layer
869 * @return $databaseInstance The database layer instance
871 public final function getDatabaseInstance () {
873 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
876 return $databaseInstance;
880 * Setter for compressor channel
882 * @param $compressorInstance An instance of CompressorChannel
885 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
886 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
890 * Getter for compressor channel
892 * @return $compressorInstance The compressor channel
894 public final function getCompressorChannel () {
895 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
896 return $compressorInstance;
900 * Protected getter for a manageable application helper class
902 * @return $applicationInstance An instance of a manageable application helper class
904 protected final function getApplicationInstance () {
905 $applicationInstance = Registry::getRegistry()->getInstance('application');
906 return $applicationInstance;
910 * Setter for a manageable application helper class
912 * @param $applicationInstance An instance of a manageable application helper class
915 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
916 Registry::getRegistry()->addInstance('application', $applicationInstance);
920 * Setter for request instance
922 * @param $requestInstance An instance of a Requestable class
925 public final function setRequestInstance (Requestable $requestInstance) {
926 $this->requestInstance = $requestInstance;
930 * Getter for request instance
932 * @return $requestInstance An instance of a Requestable class
934 public final function getRequestInstance () {
935 return $this->requestInstance;
939 * Setter for response instance
941 * @param $responseInstance An instance of a Responseable class
944 public final function setResponseInstance (Responseable $responseInstance) {
945 $this->responseInstance = $responseInstance;
949 * Getter for response instance
951 * @return $responseInstance An instance of a Responseable class
953 public final function getResponseInstance () {
954 return $this->responseInstance;
958 * Private getter for language instance
960 * @return $langInstance An instance to the language sub-system
962 protected final function getLanguageInstance () {
963 $langInstance = Registry::getRegistry()->getInstance('language');
964 return $langInstance;
968 * Setter for language instance
970 * @param $langInstance An instance to the language sub-system
972 * @see LanguageSystem
974 public final function setLanguageInstance (ManageableLanguage $langInstance) {
975 Registry::getRegistry()->addInstance('language', $langInstance);
979 * Private getter for file IO instance
981 * @return $fileIoInstance An instance to the file I/O sub-system
983 protected final function getFileIoInstance () {
984 return $this->fileIoInstance;
988 * Setter for file I/O instance
990 * @param $fileIoInstance An instance to the file I/O sub-system
993 public final function setFileIoInstance (IoHandler $fileIoInstance) {
994 $this->fileIoInstance = $fileIoInstance;
998 * Protected setter for user instance
1000 * @param $userInstance An instance of a user class
1003 protected final function setUserInstance (ManageableAccount $userInstance) {
1004 $this->userInstance = $userInstance;
1008 * Getter for user instance
1010 * @return $userInstance An instance of a user class
1012 public final function getUserInstance () {
1013 return $this->userInstance;
1017 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1019 * @param $controllerInstance An instance of the controller
1022 public final function setControllerInstance (Controller $controllerInstance) {
1023 $this->controllerInstance = $controllerInstance;
1027 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1029 * @return $controllerInstance An instance of the controller
1031 public final function getControllerInstance () {
1032 return $this->controllerInstance;
1036 * Setter for RNG instance
1038 * @param $rngInstance An instance of a random number generator (RNG)
1041 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1042 $this->rngInstance = $rngInstance;
1046 * Getter for RNG instance
1048 * @return $rngInstance An instance of a random number generator (RNG)
1050 public final function getRngInstance () {
1051 return $this->rngInstance;
1055 * Setter for Cryptable instance
1057 * @param $cryptoInstance An instance of a Cryptable class
1060 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1061 $this->cryptoInstance = $cryptoInstance;
1065 * Getter for Cryptable instance
1067 * @return $cryptoInstance An instance of a Cryptable class
1069 public final function getCryptoInstance () {
1070 return $this->cryptoInstance;
1074 * Setter for the list instance
1076 * @param $listInstance A list of Listable
1079 protected final function setListInstance (Listable $listInstance) {
1080 $this->listInstance = $listInstance;
1084 * Getter for the list instance
1086 * @return $listInstance A list of Listable
1088 protected final function getListInstance () {
1089 return $this->listInstance;
1093 * Setter for the menu instance
1095 * @param $menuInstance A RenderableMenu instance
1098 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1099 $this->menuInstance = $menuInstance;
1103 * Getter for the menu instance
1105 * @return $menuInstance A RenderableMenu instance
1107 protected final function getMenuInstance () {
1108 return $this->menuInstance;
1112 * Setter for image instance
1114 * @param $imageInstance An instance of an image
1117 public final function setImageInstance (BaseImage $imageInstance) {
1118 $this->imageInstance = $imageInstance;
1122 * Getter for image instance
1124 * @return $imageInstance An instance of an image
1126 public final function getImageInstance () {
1127 return $this->imageInstance;
1131 * Setter for stacker instance
1133 * @param $stackInstance An instance of an stacker
1136 public final function setStackInstance (Stackable $stackInstance) {
1137 $this->stackInstance = $stackInstance;
1141 * Getter for stacker instance
1143 * @return $stackInstance An instance of an stacker
1145 public final function getStackInstance () {
1146 return $this->stackInstance;
1150 * Setter for compressor instance
1152 * @param $compressorInstance An instance of an compressor
1155 public final function setCompressorInstance (Compressor $compressorInstance) {
1156 $this->compressorInstance = $compressorInstance;
1160 * Getter for compressor instance
1162 * @return $compressorInstance An instance of an compressor
1164 public final function getCompressorInstance () {
1165 return $this->compressorInstance;
1169 * Setter for Parseable instance
1171 * @param $parserInstance An instance of an Parseable
1174 public final function setParserInstance (Parseable $parserInstance) {
1175 $this->parserInstance = $parserInstance;
1179 * Getter for Parseable instance
1181 * @return $parserInstance An instance of an Parseable
1183 public final function getParserInstance () {
1184 return $this->parserInstance;
1188 * Setter for HandleableProtocol instance
1190 * @param $protocolInstance An instance of an HandleableProtocol
1193 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1194 $this->protocolInstance = $protocolInstance;
1198 * Getter for HandleableProtocol instance
1200 * @return $protocolInstance An instance of an HandleableProtocol
1202 public final function getProtocolInstance () {
1203 return $this->protocolInstance;
1207 * Setter for DatabaseWrapper instance
1209 * @param $wrapperInstance An instance of an DatabaseWrapper
1212 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1213 $this->wrapperInstance = $wrapperInstance;
1217 * Getter for DatabaseWrapper instance
1219 * @return $wrapperInstance An instance of an DatabaseWrapper
1221 public final function getWrapperInstance () {
1222 return $this->wrapperInstance;
1226 * Setter for socket resource
1228 * @param $socketResource A valid socket resource
1231 public final function setSocketResource ($socketResource) {
1232 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1233 $this->socketResource = $socketResource;
1237 * Getter for socket resource
1239 * @return $socketResource A valid socket resource
1241 public final function getSocketResource () {
1242 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1243 return $this->socketResource;
1247 * Setter for regular expression
1249 * @param $regularExpression A valid regular expression
1252 public final function setRegularExpression ($regularExpression) {
1253 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1254 $this->regularExpression = $regularExpression;
1258 * Getter for regular expression
1260 * @return $regularExpression A valid regular expression
1262 public final function getRegularExpression () {
1263 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1264 return $this->regularExpression;
1268 * Setter for helper instance
1270 * @param $helperInstance An instance of a helper class
1273 protected final function setHelperInstance (Helper $helperInstance) {
1274 $this->helperInstance = $helperInstance;
1278 * Getter for helper instance
1280 * @return $helperInstance An instance of a helper class
1282 public final function getHelperInstance () {
1283 return $this->helperInstance;
1287 * Setter for a Source instance
1289 * @param $sourceInstance An instance of a Source class
1292 protected final function setSourceInstance (Source $sourceInstance) {
1293 $this->sourceInstance = $sourceInstance;
1297 * Getter for a Source instance
1299 * @return $sourceInstance An instance of a Source class
1301 protected final function getSourceInstance () {
1302 return $this->sourceInstance;
1306 * Setter for a UrlSource instance
1308 * @param $sourceInstance An instance of a UrlSource class
1311 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1312 $this->urlSourceInstance = $urlSourceInstance;
1316 * Getter for a UrlSource instance
1318 * @return $urlSourceInstance An instance of a UrlSource class
1320 protected final function getUrlSourceInstance () {
1321 return $this->urlSourceInstance;
1325 * Getter for a InputStream instance
1327 * @param $inputStreamInstance The InputStream instance
1329 protected final function getInputStreamInstance () {
1330 return $this->inputStreamInstance;
1334 * Setter for a InputStream instance
1336 * @param $inputStreamInstance The InputStream instance
1339 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1340 $this->inputStreamInstance = $inputStreamInstance;
1344 * Getter for a OutputStream instance
1346 * @param $outputStreamInstance The OutputStream instance
1348 protected final function getOutputStreamInstance () {
1349 return $this->outputStreamInstance;
1353 * Setter for a OutputStream instance
1355 * @param $outputStreamInstance The OutputStream instance
1358 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1359 $this->outputStreamInstance = $outputStreamInstance;
1363 * Setter for handler instance
1365 * @param $handlerInstance An instance of a Handleable class
1368 protected final function setHandlerInstance (Handleable $handlerInstance) {
1369 $this->handlerInstance = $handlerInstance;
1373 * Getter for handler instance
1375 * @return $handlerInstance A Networkable instance
1377 protected final function getHandlerInstance () {
1378 return $this->handlerInstance;
1382 * Setter for visitor instance
1384 * @param $visitorInstance A Visitor instance
1387 protected final function setVisitorInstance (Visitor $visitorInstance) {
1388 $this->visitorInstance = $visitorInstance;
1392 * Getter for visitor instance
1394 * @return $visitorInstance A Visitor instance
1396 protected final function getVisitorInstance () {
1397 return $this->visitorInstance;
1401 * Setter for DHT instance
1403 * @param $dhtInstance A Distributable instance
1406 protected final function setDhtInstance (Distributable $dhtInstance) {
1407 $this->dhtInstance = $dhtInstance;
1411 * Getter for DHT instance
1413 * @return $dhtInstance A Distributable instance
1415 protected final function getDhtInstance () {
1416 return $this->dhtInstance;
1420 * Setter for raw package Data
1422 * @param $packageData Raw package Data
1425 public final function setPackageData (array $packageData) {
1426 $this->packageData = $packageData;
1430 * Getter for raw package Data
1432 * @return $packageData Raw package Data
1434 public function getPackageData () {
1435 return $this->packageData;
1440 * Setter for Iterator instance
1442 * @param $iteratorInstance An instance of an Iterator
1445 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1446 $this->iteratorInstance = $iteratorInstance;
1450 * Getter for Iterator instance
1452 * @return $iteratorInstance An instance of an Iterator
1454 public final function getIteratorInstance () {
1455 return $this->iteratorInstance;
1459 * Setter for FilePointer instance
1461 * @param $pointerInstance An instance of an FilePointer class
1464 protected final function setPointerInstance (FilePointer $pointerInstance) {
1465 $this->pointerInstance = $pointerInstance;
1469 * Getter for FilePointer instance
1471 * @return $pointerInstance An instance of an FilePointer class
1473 public final function getPointerInstance () {
1474 return $this->pointerInstance;
1478 * Unsets pointer instance which triggers a call of __destruct() if the
1479 * instance is still there. This is surely not fatal on already "closed"
1480 * file pointer instances.
1482 * I don't want to mess around with above setter by giving it a default
1483 * value NULL as setter should always explicitly only set (existing) object
1484 * instances and NULL is NULL.
1488 protected final function unsetPointerInstance () {
1489 // Simply it to NULL
1490 $this->pointerInstance = NULL;
1494 * Setter for Indexable instance
1496 * @param $indexInstance An instance of an Indexable class
1499 protected final function setIndexInstance (Indexable $indexInstance) {
1500 $this->indexInstance = $indexInstance;
1504 * Getter for Indexable instance
1506 * @return $indexInstance An instance of an Indexable class
1508 public final function getIndexInstance () {
1509 return $this->indexInstance;
1513 * Setter for Block instance
1515 * @param $blockInstance An instance of an Block class
1518 protected final function setBlockInstance (Block $blockInstance) {
1519 $this->blockInstance = $blockInstance;
1523 * Getter for Block instance
1525 * @return $blockInstance An instance of an Block class
1527 public final function getBlockInstance () {
1528 return $this->blockInstance;
1532 * Setter for Minable instance
1534 * @param $minableInstance A Minable instance
1537 protected final function setMinableInstance (Minable $minableInstance) {
1538 $this->minableInstance = $minableInstance;
1542 * Getter for minable instance
1544 * @return $minableInstance A Minable instance
1546 protected final function getMinableInstance () {
1547 return $this->minableInstance;
1551 * Setter for FrameworkDirectory instance
1553 * @param $directoryInstance A FrameworkDirectory instance
1556 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1557 $this->directoryInstance = $directoryInstance;
1561 * Getter for FrameworkDirectory instance
1563 * @return $directoryInstance A FrameworkDirectory instance
1565 protected final function getDirectoryInstance () {
1566 return $this->directoryInstance;
1570 * Setter for listener instance
1572 * @param $listenerInstance A Listenable instance
1575 protected final function setListenerInstance (Listenable $listenerInstance) {
1576 $this->listenerInstance = $listenerInstance;
1580 * Getter for listener instance
1582 * @return $listenerInstance A Listenable instance
1584 protected final function getListenerInstance () {
1585 return $this->listenerInstance;
1589 * Getter for communicator instance
1591 * @return $communicatorInstance An instance of a Communicator class
1593 public final function getCommunicatorInstance () {
1594 return $this->communicatorInstance;
1598 * Setter for communicator instance
1600 * @param $communicatorInstance An instance of a Communicator class
1603 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1604 $this->communicatorInstance = $communicatorInstance;
1608 * Setter for state instance
1610 * @param $stateInstance A Stateable instance
1613 public final function setStateInstance (Stateable $stateInstance) {
1614 $this->stateInstance = $stateInstance;
1618 * Getter for state instance
1620 * @return $stateInstance A Stateable instance
1622 public final function getStateInstance () {
1623 return $this->stateInstance;
1627 * Setter for output instance
1629 * @param $outputInstance The debug output instance
1632 public final function setOutputInstance (OutputStreamer $outputInstance) {
1633 $this->outputInstance = $outputInstance;
1637 * Getter for output instance
1639 * @return $outputInstance The debug output instance
1641 public final function getOutputInstance () {
1642 return $this->outputInstance;
1646 * Setter for command name
1648 * @param $commandName Last validated command name
1651 protected final function setCommandName ($commandName) {
1652 $this->commandName = $commandName;
1656 * Getter for command name
1658 * @return $commandName Last validated command name
1660 protected final function getCommandName () {
1661 return $this->commandName;
1665 * Setter for controller name
1667 * @param $controllerName Last validated controller name
1670 protected final function setControllerName ($controllerName) {
1671 $this->controllerName = $controllerName;
1675 * Getter for controller name
1677 * @return $controllerName Last validated controller name
1679 protected final function getControllerName () {
1680 return $this->controllerName;
1684 * Getter for protocol name
1686 * @return $protocolName Name of used protocol
1688 public final function getProtocolName () {
1689 return $this->protocolName;
1693 * Setter for protocol name
1695 * @param $protocolName Name of used protocol
1698 protected final function setProtocolName ($protocolName) {
1699 $this->protocolName = $protocolName;
1703 * Checks whether an object equals this object. You should overwrite this
1704 * method to implement own equality checks
1706 * @param $objectInstance An instance of a FrameworkInterface object
1707 * @return $equals Whether both objects equals
1709 public function equals (FrameworkInterface $objectInstance) {
1712 $this->__toString() == $objectInstance->__toString()
1714 $this->hashCode() == $objectInstance->hashCode()
1717 // Return the result
1722 * Generates a generic hash code of this class. You should really overwrite
1723 * this method with your own hash code generator code. But keep KISS in mind.
1725 * @return $hashCode A generic hash code respresenting this whole class
1727 public function hashCode () {
1729 return crc32($this->__toString());
1733 * Formats computer generated price values into human-understandable formats
1734 * with thousand and decimal separators.
1736 * @param $value The in computer format value for a price
1737 * @param $currency The currency symbol (use HTML-valid characters!)
1738 * @param $decNum Number of decimals after commata
1739 * @return $price The for the current language formated price string
1740 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1741 * thousands separator
1744 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1745 // Are all required attriutes set?
1746 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1747 // Throw an exception
1748 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1752 $value = (float) $value;
1754 // Reformat the US number
1755 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1757 // Return as string...
1762 * Appends a trailing slash to a string
1764 * @param $str A string (maybe) without trailing slash
1765 * @return $str A string with an auto-appended trailing slash
1767 public final function addMissingTrailingSlash ($str) {
1768 // Is there a trailing slash?
1769 if (substr($str, -1, 1) != '/') {
1773 // Return string with trailing slash
1778 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1779 * application helper instance (ApplicationHelper by default).
1781 * @param $applicationInstance An application helper instance or
1782 * null if we shall use the default
1783 * @return $templateInstance The template engine instance
1784 * @throws NullPointerException If the discovered application
1785 * instance is still null
1787 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1788 // Is the application instance set?
1789 if (is_null($applicationInstance)) {
1790 // Get the current instance
1791 $applicationInstance = $this->getApplicationInstance();
1794 if (is_null($applicationInstance)) {
1795 // Thrown an exception
1796 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1800 // Initialize the template engine
1801 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1803 // Return the prepared instance
1804 return $templateInstance;
1808 * Debugs this instance by putting out it's full content
1810 * @param $message Optional message to show in debug output
1813 public final function debugInstance ($message = '') {
1814 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1815 restore_error_handler();
1820 // Is a message set?
1821 if (!empty($message)) {
1822 // Construct message
1823 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1826 // Generate the output
1827 $content .= sprintf('<pre>%s</pre>',
1830 print_r($this, TRUE)
1836 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>',
1837 $this->__toString(),
1839 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1844 * Replaces control characters with printable output
1846 * @param $str String with control characters
1847 * @return $str Replaced string
1849 protected function replaceControlCharacters ($str) {
1852 chr(13), '[r]', str_replace(
1853 chr(10), '[n]', str_replace(
1863 * Output a partial stub message for the caller method
1865 * @param $message An optional message to display
1868 protected function partialStub ($message = '') {
1869 // Get the backtrace
1870 $backtrace = debug_backtrace();
1872 // Generate the class::method string
1873 $methodName = 'UnknownClass->unknownMethod';
1874 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1875 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1878 // Construct the full message
1879 $stubMessage = sprintf('[%s:] Partial stub!',
1883 // Is the extra message given?
1884 if (!empty($message)) {
1885 // Then add it as well
1886 $stubMessage .= ' Message: ' . $message;
1889 // Debug instance is there?
1890 if (!is_null($this->getDebugInstance())) {
1891 // Output stub message
1892 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1895 trigger_error($stubMessage);
1901 * Outputs a debug backtrace and stops further script execution
1903 * @param $message An optional message to output
1904 * @param $doExit Whether exit the program (TRUE is default)
1907 public function debugBackTrace ($message = '', $doExit = TRUE) {
1908 // Sorry, there is no other way getting this nice backtrace
1909 if (!empty($message)) {
1911 printf('Message: %s<br />' . PHP_EOL, $message);
1915 debug_print_backtrace();
1919 if ($doExit === TRUE) {
1925 * Creates an instance of a debugger instance
1927 * @param $className Name of the class (currently unsupported)
1928 * @param $lineNumber Line number where the call was made
1929 * @return $debugInstance An instance of a debugger class
1930 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1932 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1933 // Is the instance set?
1934 if (!Registry::getRegistry()->instanceExists('debug')) {
1935 // Init debug instance
1936 $debugInstance = NULL;
1940 // Get a debugger instance
1941 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1942 } catch (NullPointerException $e) {
1943 // Didn't work, no instance there
1944 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1947 // Empty string should be ignored and used for testing the middleware
1948 DebugMiddleware::getSelfInstance()->output('');
1950 // Set it in its own class. This will set it in the registry
1951 $debugInstance->setDebugInstance($debugInstance);
1953 // Get instance from registry
1954 $debugInstance = Registry::getRegistry()->getDebugInstance();
1958 return $debugInstance;
1962 * Simple output of a message with line-break
1964 * @param $message Message to output
1967 public function outputLine ($message) {
1969 print($message . PHP_EOL);
1973 * Outputs a debug message whether to debug instance (should be set!) or
1974 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1975 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1977 * @param $message Message we shall send out...
1978 * @param $doPrint Whether print or die here (default: print)
1979 * @paran $stripTags Whether to strip tags (default: FALSE)
1982 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1983 // Set debug instance to NULL
1984 $debugInstance = NULL;
1988 // Get debug instance
1989 $debugInstance = $this->getDebugInstance();
1990 } catch (NullPointerException $e) {
1991 // The debug instance is not set (yet)
1994 // Is the debug instance there?
1995 if (is_object($debugInstance)) {
1996 // Use debug output handler
1997 $debugInstance->output($message, $stripTags);
1999 if ($doPrint === FALSE) {
2000 // Die here if not printed
2004 // Are debug times enabled?
2005 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
2007 $message = $this->getPrintableExecutionTime() . $message;
2011 if ($doPrint === TRUE) {
2013 $this->outputLine($message);
2022 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2024 * @param $str The string, what ever it is needs to be converted
2025 * @return $className Generated class name
2027 public static final function convertToClassName ($str) {
2031 // Convert all dashes in underscores
2032 $str = self::convertDashesToUnderscores($str);
2034 // Now use that underscores to get classname parts for hungarian style
2035 foreach (explode('_', $str) as $strPart) {
2036 // Make the class name part lower case and first upper case
2037 $className .= ucfirst(strtolower($strPart));
2040 // Return class name
2045 * Converts dashes to underscores, e.g. useable for configuration entries
2047 * @param $str The string with maybe dashes inside
2048 * @return $str The converted string with no dashed, but underscores
2050 public static final function convertDashesToUnderscores ($str) {
2052 $str = str_replace('-', '_', $str);
2054 // Return converted string
2059 * Marks up the code by adding e.g. line numbers
2061 * @param $phpCode Unmarked PHP code
2062 * @return $markedCode Marked PHP code
2064 public function markupCode ($phpCode) {
2069 $errorArray = error_get_last();
2071 // Init the code with error message
2072 if (is_array($errorArray)) {
2074 $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>',
2075 basename($errorArray['file']),
2076 $errorArray['line'],
2077 $errorArray['message'],
2082 // Add line number to the code
2083 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2085 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2087 htmlentities($code, ENT_QUOTES)
2096 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2097 * beatiful for web-based front-ends. If null is given a message id
2098 * null_timestamp will be resolved and returned.
2100 * @param $timestamp Timestamp to prepare (filter) for display
2101 * @return $readable A readable timestamp
2103 public function doFilterFormatTimestamp ($timestamp) {
2104 // Default value to return
2107 // Is the timestamp null?
2108 if (is_null($timestamp)) {
2109 // Get a message string
2110 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2112 switch ($this->getLanguageInstance()->getLanguageCode()) {
2113 case 'de': // German format is a bit different to default
2114 // Split the GMT stamp up
2115 $dateTime = explode(' ', $timestamp );
2116 $dateArray = explode('-', $dateTime[0]);
2117 $timeArray = explode(':', $dateTime[1]);
2119 // Construct the timestamp
2120 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2130 default: // Default is pass-through
2131 $readable = $timestamp;
2141 * Filter a given number into a localized number
2143 * @param $value The raw value from e.g. database
2144 * @return $localized Localized value
2146 public function doFilterFormatNumber ($value) {
2147 // Generate it from config and localize dependencies
2148 switch ($this->getLanguageInstance()->getLanguageCode()) {
2149 case 'de': // German format is a bit different to default
2150 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2153 default: // US, etc.
2154 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2163 * "Getter" for databse entry
2165 * @return $entry An array with database entries
2166 * @throws NullPointerException If the database result is not found
2167 * @throws InvalidDatabaseResultException If the database result is invalid
2169 protected final function getDatabaseEntry () {
2170 // Is there an instance?
2171 if (!$this->getResultInstance() instanceof SearchableResult) {
2172 // Throw an exception here
2173 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2177 $this->getResultInstance()->rewind();
2179 // Do we have an entry?
2180 if ($this->getResultInstance()->valid() === FALSE) {
2181 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2182 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2186 $this->getResultInstance()->next();
2189 $entry = $this->getResultInstance()->current();
2196 * Getter for field name
2198 * @param $fieldName Field name which we shall get
2199 * @return $fieldValue Field value from the user
2200 * @throws NullPointerException If the result instance is null
2202 public final function getField ($fieldName) {
2203 // Default field value
2206 // Get result instance
2207 $resultInstance = $this->getResultInstance();
2209 // Is this instance null?
2210 if (is_null($resultInstance)) {
2211 // Then the user instance is no longer valid (expired cookies?)
2212 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2215 // Get current array
2216 $fieldArray = $resultInstance->current();
2217 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2219 // Convert dashes to underscore
2220 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2222 // Does the field exist?
2223 if ($this->isFieldSet($fieldName)) {
2225 $fieldValue = $fieldArray[$fieldName2];
2226 } elseif (defined('DEVELOPER')) {
2227 // Missing field entry, may require debugging
2228 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2230 // Missing field entry, may require debugging
2231 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2239 * Checks if given field is set
2241 * @param $fieldName Field name to check
2242 * @return $isSet Whether the given field name is set
2243 * @throws NullPointerException If the result instance is null
2245 public function isFieldSet ($fieldName) {
2246 // Get result instance
2247 $resultInstance = $this->getResultInstance();
2249 // Is this instance null?
2250 if (is_null($resultInstance)) {
2251 // Then the user instance is no longer valid (expired cookies?)
2252 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2255 // Get current array
2256 $fieldArray = $resultInstance->current();
2257 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2259 // Convert dashes to underscore
2260 $fieldName = self::convertDashesToUnderscores($fieldName);
2263 $isSet = isset($fieldArray[$fieldName]);
2270 * Flushs all pending updates to the database layer
2274 public function flushPendingUpdates () {
2275 // Get result instance
2276 $resultInstance = $this->getResultInstance();
2278 // Do we have data to update?
2279 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2280 // Get wrapper class name config entry
2281 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2283 // Create object instance
2284 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2286 // Yes, then send the whole result to the database layer
2287 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2292 * Outputs a deprecation warning to the developer.
2294 * @param $message The message we shall output to the developer
2296 * @todo Write a logging mechanism for productive mode
2298 public function deprecationWarning ($message) {
2299 // Is developer mode active?
2300 if (defined('DEVELOPER')) {
2301 // Debug instance is there?
2302 if (!is_null($this->getDebugInstance())) {
2303 // Output stub message
2304 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2307 trigger_error($message . "<br />\n");
2311 // @TODO Finish this part!
2312 $this->partialStub('Developer mode inactive. Message:' . $message);
2317 * Checks whether the given PHP extension is loaded
2319 * @param $phpExtension The PHP extension we shall check
2320 * @return $isLoaded Whether the PHP extension is loaded
2322 public final function isPhpExtensionLoaded ($phpExtension) {
2324 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2331 * "Getter" as a time() replacement but with milliseconds. You should use this
2332 * method instead of the encapsulated getimeofday() function.
2334 * @return $milliTime Timestamp with milliseconds
2336 public function getMilliTime () {
2337 // Get the time of day as float
2338 $milliTime = gettimeofday(TRUE);
2345 * Idles (sleeps) for given milliseconds
2347 * @return $hasSlept Whether it goes fine
2349 public function idle ($milliSeconds) {
2350 // Sleep is fine by default
2353 // Idle so long with found function
2354 if (function_exists('time_sleep_until')) {
2355 // Get current time and add idle time
2356 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2358 // New PHP 5.1.0 function found, ignore errors
2359 $hasSlept = @time_sleep_until($sleepUntil);
2362 * My Sun station doesn't have that function even with latest PHP
2365 usleep($milliSeconds * 1000);
2372 * Converts a hexadecimal string, even with negative sign as first string to
2373 * a decimal number using BC functions.
2375 * This work is based on comment #86673 on php.net documentation page at:
2376 * <http://de.php.net/manual/en/function.dechex.php#86673>
2378 * @param $hex Hexadecimal string
2379 * @return $dec Decimal number
2381 protected function hex2dec ($hex) {
2382 // Convert to all lower-case
2383 $hex = strtolower($hex);
2385 // Detect sign (negative/positive numbers)
2387 if (substr($hex, 0, 1) == '-') {
2389 $hex = substr($hex, 1);
2392 // Decode the hexadecimal string into a decimal number
2394 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2395 $factor = self::$hexdec[substr($hex, $i, 1)];
2396 $dec = bcadd($dec, bcmul($factor, $e));
2399 // Return the decimal number
2400 return $sign . $dec;
2404 * Converts even very large decimal numbers, also signed, to a hexadecimal
2407 * This work is based on comment #97756 on php.net documentation page at:
2408 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2410 * @param $dec Decimal number, even with negative sign
2411 * @param $maxLength Optional maximum length of the string
2412 * @return $hex Hexadecimal string
2414 protected function dec2hex ($dec, $maxLength = 0) {
2415 // maxLength can be zero or devideable by 2
2416 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2418 // Detect sign (negative/positive numbers)
2425 // Encode the decimal number into a hexadecimal string
2428 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2430 } while ($dec >= 1);
2433 * Leading zeros are required for hex-decimal "numbers". In some
2434 * situations more leading zeros are wanted, so check for both
2437 if ($maxLength > 0) {
2438 // Prepend more zeros
2439 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2440 } elseif ((strlen($hex) % 2) != 0) {
2441 // Only make string's length dividable by 2
2445 // Return the hexadecimal string
2446 return $sign . $hex;
2450 * Converts a ASCII string (0 to 255) into a decimal number.
2452 * @param $asc The ASCII string to be converted
2453 * @return $dec Decimal number
2455 protected function asc2dec ($asc) {
2456 // Convert it into a hexadecimal number
2457 $hex = bin2hex($asc);
2459 // And back into a decimal number
2460 $dec = $this->hex2dec($hex);
2467 * Converts a decimal number into an ASCII string.
2469 * @param $dec Decimal number
2470 * @return $asc An ASCII string
2472 protected function dec2asc ($dec) {
2473 // First convert the number into a hexadecimal string
2474 $hex = $this->dec2hex($dec);
2476 // Then convert it into the ASCII string
2477 $asc = $this->hex2asc($hex);
2484 * Converts a hexadecimal number into an ASCII string. Negative numbers
2487 * @param $hex Hexadecimal string
2488 * @return $asc An ASCII string
2490 protected function hex2asc ($hex) {
2491 // Check for length, it must be devideable by 2
2492 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2493 assert((strlen($hex) % 2) == 0);
2497 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2498 // Get the decimal number of the chunk
2499 $part = hexdec(substr($hex, $idx, 2));
2501 // Add it to the final string
2505 // Return the final string
2510 * Checks whether the given encoded data was encoded with Base64
2512 * @param $encodedData Encoded data we shall check
2513 * @return $isBase64 Whether the encoded data is Base64
2515 protected function isBase64Encoded ($encodedData) {
2517 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2524 * "Getter" to get response/request type from analysis of the system.
2526 * @return $responseType Analyzed response type
2528 protected static function getResponseTypeFromSystem () {
2529 // Default is console
2530 $responseType = 'console';
2532 // Is 'HTTP_HOST' set?
2533 if (isset($_SERVER['HTTP_HOST'])) {
2535 * Then it is a HTML response/request as RSS and so on may be
2536 * transfered over HTTP as well.
2538 $responseType = 'html';
2542 return $responseType;
2546 * Gets a cache key from Criteria instance
2548 * @param $criteriaInstance An instance of a Criteria class
2549 * @param $onlyKeys Only use these keys for a cache key
2550 * @return $cacheKey A cache key suitable for lookup/storage purposes
2552 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2554 $cacheKey = sprintf('%s@%s',
2555 $this->__toString(),
2556 $criteriaInstance->getCacheKey($onlyKeys)
2560 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2565 * Getter for startup time in miliseconds
2567 * @return $startupTime Startup time in miliseconds
2569 protected function getStartupTime () {
2570 return self::$startupTime;
2574 * "Getter" for a printable currently execution time in nice braces
2576 * @return $executionTime Current execution time in nice braces
2578 protected function getPrintableExecutionTime () {
2579 // Caculate the execution time
2580 $executionTime = microtime(TRUE) - $this->getStartupTime();
2582 // Pack it in nice braces
2583 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2586 return $executionTime;
2590 * Hashes a given string with a simple but stronger hash function (no salt)
2591 * and hex-encode it.
2593 * @param $str The string to be hashed
2594 * @return $hash The hash from string $str
2596 public static final function hash ($str) {
2597 // Hash given string with (better secure) hasher
2598 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2605 * "Getter" for length of hash() output. This will be "cached" to speed up
2608 * @return $length Length of hash() output
2610 public static final function getHashLength () {
2612 if (is_null(self::$hashLength)) {
2613 // No, then hash a string and save its length.
2614 self::$hashLength = strlen(self::hash('abc123'));
2618 return self::$hashLength;
2622 * Checks whether the given number is really a number (only chars 0-9).
2624 * @param $num A string consisting only chars between 0 and 9
2625 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2626 * @param $assertMismatch Whether to assert mismatches
2627 * @return $ret The (hopefully) secured numbered value
2629 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2630 // Filter all numbers out
2631 $ret = preg_replace('/[^0123456789]/', '', $num);
2634 if ($castValue === TRUE) {
2635 // Cast to biggest numeric type
2636 $ret = (double) $ret;
2639 // Assert only if requested
2640 if ($assertMismatch === TRUE) {
2641 // Has the whole value changed?
2642 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2650 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2652 * @param $num A string consisting only chars between 0 and 9
2653 * @param $assertMismatch Whether to assert mismatches
2654 * @return $ret The (hopefully) secured hext-numbered value
2656 public function hexval ($num, $assertMismatch = FALSE) {
2657 // Filter all numbers out
2658 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2660 // Assert only if requested
2661 if ($assertMismatch === TRUE) {
2662 // Has the whole value changed?
2663 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2671 * Checks whether start/end marker are set
2673 * @param $data Data to be checked
2674 * @return $isset Whether start/end marker are set
2676 public final function ifStartEndMarkersSet ($data) {
2678 $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));
2680 // ... and return it
2685 * Determines if an element is set in the generic array
2687 * @param $keyGroup Main group for the key
2688 * @param $subGroup Sub group for the key
2689 * @param $key Key to check
2690 * @param $element Element to check
2691 * @return $isset Whether the given key is set
2693 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2695 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2698 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2704 * Determines if a key is set in the generic array
2706 * @param $keyGroup Main group for the key
2707 * @param $subGroup Sub group for the key
2708 * @param $key Key to check
2709 * @return $isset Whether the given key is set
2711 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2713 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2716 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2724 * Determines if a group is set in the generic array
2726 * @param $keyGroup Main group
2727 * @param $subGroup Sub group
2728 * @return $isset Whether the given group is set
2730 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2732 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2735 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2742 * Getter for sub key group
2744 * @param $keyGroup Main key group
2745 * @param $subGroup Sub key group
2746 * @return $array An array with all array elements
2748 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2750 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2751 // No, then abort here
2752 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2757 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2760 return $this->genericArray[$keyGroup][$subGroup];
2764 * Unsets a given key in generic array
2766 * @param $keyGroup Main group for the key
2767 * @param $subGroup Sub group for the key
2768 * @param $key Key to unset
2771 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2773 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2776 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2780 * Unsets a given element in generic array
2782 * @param $keyGroup Main group for the key
2783 * @param $subGroup Sub group for the key
2784 * @param $key Key to unset
2785 * @param $element Element to unset
2788 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2790 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2793 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2797 * Append a string to a given generic array key
2799 * @param $keyGroup Main group for the key
2800 * @param $subGroup Sub group for the key
2801 * @param $key Key to unset
2802 * @param $value Value to add/append
2805 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2807 //* 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);
2809 // Is it already there?
2810 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2812 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2815 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2820 * Append a string to a given generic array element
2822 * @param $keyGroup Main group for the key
2823 * @param $subGroup Sub group for the key
2824 * @param $key Key to unset
2825 * @param $element Element to check
2826 * @param $value Value to add/append
2829 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2831 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, TRUE) . ',appendGlue=' . $appendGlue);
2833 // Is it already there?
2834 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2836 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2839 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2844 * Sets a string in a given generic array element
2846 * @param $keyGroup Main group for the key
2847 * @param $subGroup Sub group for the key
2848 * @param $key Key to unset
2849 * @param $element Element to check
2850 * @param $value Value to add/append
2853 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2855 //* 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);
2858 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2862 * Initializes given generic array group
2864 * @param $keyGroup Main group for the key
2865 * @param $subGroup Sub group for the key
2866 * @param $key Key to use
2867 * @param $forceInit Optionally force initialization
2870 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2872 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2874 // Is it already set?
2875 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2876 // Already initialized
2877 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2882 $this->genericArray[$keyGroup][$subGroup] = array();
2886 * Initializes given generic array key
2888 * @param $keyGroup Main group for the key
2889 * @param $subGroup Sub group for the key
2890 * @param $key Key to use
2891 * @param $forceInit Optionally force initialization
2894 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2896 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2898 // Is it already set?
2899 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2900 // Already initialized
2901 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2906 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2910 * Initializes given generic array element
2912 * @param $keyGroup Main group for the key
2913 * @param $subGroup Sub group for the key
2914 * @param $key Key to use
2915 * @param $element Element to use
2916 * @param $forceInit Optionally force initialization
2919 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2921 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2923 // Is it already set?
2924 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2925 // Already initialized
2926 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2931 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2935 * Pushes an element to a generic key
2937 * @param $keyGroup Main group for the key
2938 * @param $subGroup Sub group for the key
2939 * @param $key Key to use
2940 * @param $value Value to add/append
2941 * @return $count Number of array elements
2943 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2945 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2948 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2950 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2954 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2957 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2958 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2963 * Pushes an element to a generic array element
2965 * @param $keyGroup Main group for the key
2966 * @param $subGroup Sub group for the key
2967 * @param $key Key to use
2968 * @param $element Element to check
2969 * @param $value Value to add/append
2970 * @return $count Number of array elements
2972 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2974 //* 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));
2977 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2979 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2983 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2986 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2987 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2992 * Pops an element from a generic group
2994 * @param $keyGroup Main group for the key
2995 * @param $subGroup Sub group for the key
2996 * @param $key Key to unset
2997 * @return $value Last "popped" value
2999 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
3001 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3004 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3006 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3011 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
3014 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3015 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3020 * Shifts an element from a generic group
3022 * @param $keyGroup Main group for the key
3023 * @param $subGroup Sub group for the key
3024 * @param $key Key to unset
3025 * @return $value Last "popped" value
3027 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3029 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3032 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3034 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3039 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3042 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3043 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3048 * Count generic array group
3050 * @param $keyGroup Main group for the key
3051 * @return $count Count of given group
3053 protected final function countGenericArray ($keyGroup) {
3055 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3058 if (!isset($this->genericArray[$keyGroup])) {
3060 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3065 $count = count($this->genericArray[$keyGroup]);
3068 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3075 * Count generic array sub group
3077 * @param $keyGroup Main group for the key
3078 * @param $subGroup Sub group for the key
3079 * @return $count Count of given group
3081 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3083 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3086 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3088 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3093 $count = count($this->genericArray[$keyGroup][$subGroup]);
3096 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3103 * Count generic array elements
3105 * @param $keyGroup Main group for the key
3106 * @param $subGroup Sub group for the key
3107 * @para $key Key to count
3108 * @return $count Count of given key
3110 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3112 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3115 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3117 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3119 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3121 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3126 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3129 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3136 * Getter for whole generic group array
3138 * @param $keyGroup Key group to get
3139 * @return $array Whole generic array group
3141 protected final function getGenericArray ($keyGroup) {
3143 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3146 if (!isset($this->genericArray[$keyGroup])) {
3148 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3153 return $this->genericArray[$keyGroup];
3157 * Setter for generic array key
3159 * @param $keyGroup Key group to get
3160 * @param $subGroup Sub group for the key
3161 * @param $key Key to unset
3162 * @param $value Mixed value from generic array element
3165 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3167 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3170 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3174 * Getter for generic array key
3176 * @param $keyGroup Key group to get
3177 * @param $subGroup Sub group for the key
3178 * @param $key Key to unset
3179 * @return $value Mixed value from generic array element
3181 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3183 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3186 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3188 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3193 return $this->genericArray[$keyGroup][$subGroup][$key];
3197 * Sets a value in given generic array key/element
3199 * @param $keyGroup Main group for the key
3200 * @param $subGroup Sub group for the key
3201 * @param $key Key to set
3202 * @param $element Element to set
3203 * @param $value Value to set
3206 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3208 //* 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));
3211 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3215 * Getter for generic array element
3217 * @param $keyGroup Key group to get
3218 * @param $subGroup Sub group for the key
3219 * @param $key Key to look for
3220 * @param $element Element to look for
3221 * @return $value Mixed value from generic array element
3223 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3225 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3228 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3230 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3235 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3239 * Checks if a given sub group is valid (array)
3241 * @param $keyGroup Key group to get
3242 * @param $subGroup Sub group for the key
3243 * @return $isValid Whether given sub group is valid
3245 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3247 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3250 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3257 * Checks if a given key is valid (array)
3259 * @param $keyGroup Key group to get
3260 * @param $subGroup Sub group for the key
3261 * @param $key Key to check
3262 * @return $isValid Whether given sub group is valid
3264 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3266 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3269 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3276 * Initializes the web output instance
3280 protected function initWebOutputInstance () {
3281 // Get application instance
3282 $applicationInstance = Registry::getRegistry()->getInstance('app');
3284 // Is this a response instance?
3285 if ($this instanceof Responseable) {
3286 // Then set it in application instance
3287 $applicationInstance->setResponseInstance($this);
3290 // Init web output instance
3291 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3294 $this->setWebOutputInstance($outputInstance);
3298 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3300 * @param $boolean Boolean value
3301 * @return $translated Translated boolean value
3303 public static final function translateBooleanToYesNo ($boolean) {
3304 // Make sure it is really boolean
3305 assert(is_bool($boolean));
3308 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3310 // ... and return it
3315 * Encodes raw data (almost any type) by "serializing" it and then pack it
3316 * into a "binary format".
3318 * @param $rawData Raw data (almost any type)
3319 * @return $encoded Encoded data
3321 protected function encodeData ($rawData) {
3322 // Make sure no objects or resources pass through
3323 assert(!is_object($rawData));
3324 assert(!is_resource($rawData));
3326 // First "serialize" it (json_encode() is faster than serialize())
3327 $encoded = $this->packString(json_encode($rawData));
3334 * Pack a string into a "binary format". Please execuse me that this is
3335 * widely undocumented. :-(
3337 * @param $str Unpacked string
3338 * @return $packed Packed string
3339 * @todo Improve documentation
3341 protected function packString ($str) {
3343 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3345 // First compress the string (gzcompress is okay)
3346 $str = gzcompress($str);
3351 // And start the "encoding" loop
3352 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3354 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3355 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3357 if (($idx + $i) <= strlen($str)) {
3358 $ord = ord(substr($str, ($idx + $i), 1));
3360 $add = $ord * pow(256, $factor);
3364 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3368 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3369 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3371 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3372 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3378 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3383 * Checks whether the given file/path is in open_basedir(). This does not
3384 * gurantee that the file is actually readable and/or writeable. If you need
3385 * such gurantee then please use isReadableFile() instead.
3387 * @param $filePathName Name of the file/path to be checked
3388 * @return $isReachable Whether it is within open_basedir()
3390 protected static function isReachableFilePath ($filePathName) {
3391 // Is not reachable by default
3392 $isReachable = FALSE;
3394 // Get open_basedir parameter
3395 $openBaseDir = ini_get('open_basedir');
3398 if (!empty($openBaseDir)) {
3399 // Check all entries
3400 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3401 // Check on existence
3402 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3404 $isReachable = TRUE;
3408 // If open_basedir is not set, all is allowed
3409 $isReachable = TRUE;
3413 return $isReachable;
3417 * Checks whether the give file is within open_basedir() (done by
3418 * isReachableFilePath()), is actually a file and is readable.
3420 * @param $fileName Name of the file to be checked
3421 * @return $isReadable Whether the file is readable (and therefor exists)
3423 public static function isReadableFile ($fileName) {
3424 // Default is not readable
3425 $isReadable = FALSE;
3427 // Is within parameters, so check if it is a file and readable
3428 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3435 * Creates a full-qualified file name (FQFN) for given file name by adding
3436 * a configured temporary file path to it.
3438 * @param $fileName Name for temporary file
3439 * @return $fqfn Full-qualified file name
3440 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3441 * @throws FileIoException If the file cannot be written
3443 protected static function createTempPathForFile ($fileName) {
3445 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3447 // Is the path writeable?
3448 if (!is_writable($basePath)) {
3449 // Path is write-protected
3450 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3454 $fqfn = $basePath . '/' . $fileName;
3457 if (!self::isReachableFilePath($fqfn)) {
3459 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3467 * "Getter" for a printable state name
3469 * @return $stateName Name of the node's state in a printable format
3471 public final function getPrintableState () {
3472 // Default is 'null'
3473 $stateName = 'null';
3475 // Get the state instance
3476 $stateInstance = $this->getStateInstance();
3478 // Is it an instance of Stateable?
3479 if ($stateInstance instanceof Stateable) {
3480 // Then use that state name
3481 $stateName = $stateInstance->getStateName();
3489 * Handles socket error for given socket resource and peer data. This method
3490 * validates $socketResource if it is a valid resource (see is_resource())
3491 * but assumes valid data in array $recipientData, except that
3492 * count($recipientData) is always 2.
3494 * @param $method Value of __METHOD__ from calling method
3495 * @param $line Value of __LINE__ from calling method
3496 * @param $socketResource A valid socket resource
3497 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3499 * @throws InvalidSocketException If $socketResource is no socket resource
3500 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3501 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3503 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3504 // This method handles only socket resources
3505 if (!is_resource($socketResource)) {
3506 // No resource, abort here
3507 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3510 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3511 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3512 assert(isset($socketData[0]));
3513 assert(isset($socketData[1]));
3515 // Get error code for first validation (0 is not an error)
3516 $errorCode = socket_last_error($socketResource);
3518 // If the error code is zero, someone called this method without an error
3519 if ($errorCode == 0) {
3520 // No error detected (or previously cleared outside this method)
3521 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3524 // Get handler (method) name
3525 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3527 // Call-back the error handler method
3528 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3530 // Finally clear the error because it has been handled
3531 socket_clear_error($socketResource);