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\Stacker\Stackable;
37 use CoreFramework\Stream\Output\OutputStreamer;
38 use CoreFramework\Template\CompileableTemplate;
39 use CoreFramework\User\ManageableAccount;
40 use CoreFramework\Visitor\Visitor;
41 use CoreFramework\Wrapper\Database\DatabaseWrapper;
48 * The simulator system class is the super class of all other classes. This
49 * class handles saving of games etc.
51 * @author Roland Haeder <webmaster@shipsimu.org>
53 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
54 * @license GNU GPL 3.0 or any newer version
55 * @link http://www.shipsimu.org
57 * This program is free software: you can redistribute it and/or modify
58 * it under the terms of the GNU General Public License as published by
59 * the Free Software Foundation, either version 3 of the License, or
60 * (at your option) any later version.
62 * This program is distributed in the hope that it will be useful,
63 * but WITHOUT ANY WARRANTY; without even the implied warranty of
64 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
65 * GNU General Public License for more details.
67 * You should have received a copy of the GNU General Public License
68 * along with this program. If not, see <http://www.gnu.org/licenses/>.
70 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
72 * Length of output from hash()
74 private static $hashLength = NULL;
79 private $realClass = 'BaseFrameworkSystem';
82 * Instance of a Requestable class
84 private $requestInstance = NULL;
87 * Instance of a Responseable class
89 private $responseInstance = NULL;
92 * Search criteria instance
94 private $searchInstance = NULL;
97 * Update criteria instance
99 private $updateInstance = NULL;
102 * The file I/O instance for the template loader
104 private $fileIoInstance = NULL;
109 private $resolverInstance = NULL;
112 * Template engine instance
114 private $templateInstance = NULL;
117 * Database result instance
119 private $resultInstance = NULL;
122 * Instance for user class
124 private $userInstance = NULL;
127 * A controller instance
129 private $controllerInstance = NULL;
134 private $rngInstance = NULL;
137 * Instance of a crypto helper
139 private $cryptoInstance = NULL;
142 * Instance of an Iterator class
144 private $iteratorInstance = NULL;
147 * Instance of the list
149 private $listInstance = NULL;
154 private $menuInstance = NULL;
157 * Instance of the image
159 private $imageInstance = NULL;
162 * Instance of the stacker
164 private $stackInstance = NULL;
167 * A Compressor instance
169 private $compressorInstance = NULL;
172 * A Parseable instance
174 private $parserInstance = NULL;
177 * A HandleableProtocol instance
179 private $protocolInstance = NULL;
182 * A database wrapper instance
184 private $databaseInstance = NULL;
187 * A helper instance for the form
189 private $helperInstance = NULL;
192 * An instance of a Source class
194 private $sourceInstance = NULL;
197 * An instance of a UrlSource class
199 private $urlSourceInstance = NULL;
202 * An instance of a InputStream class
204 private $inputStreamInstance = NULL;
207 * An instance of a OutputStream class
209 private $outputStreamInstance = NULL;
212 * Networkable handler instance
214 private $handlerInstance = NULL;
217 * Visitor handler instance
219 private $visitorInstance = NULL;
224 private $dhtInstance = NULL;
227 * An instance of a database wrapper class
229 private $wrapperInstance = NULL;
232 * An instance of a file I/O pointer class (not handler)
234 private $pointerInstance = NULL;
237 * An instance of an Indexable class
239 private $indexInstance = NULL;
242 * An instance of a Block class
244 private $blockInstance = NULL;
249 private $minableInstance = NULL;
252 * A FrameworkDirectory instance
254 private $directoryInstance = NULL;
259 private $listenerInstance = NULL;
262 * An instance of a communicator
264 private $communicatorInstance = NULL;
267 * The concrete output instance
269 private $outputInstance = NULL;
274 private $stateInstance = NULL;
277 * Thousands separator
279 private $thousands = '.'; // German
284 private $decimals = ','; // German
289 private $socketResource = FALSE;
292 * Regular expression to use for validation
294 private $regularExpression = '';
299 private $packageData = array();
304 private $genericArray = array();
309 private $commandName = '';
314 private $controllerName = '';
317 * Name of used protocol
319 private $protocolName = 'invalid';
322 * Array with bitmasks and such for pack/unpack methods to support both
323 * 32-bit and 64-bit systems
325 private $packingData = array(
328 'left' => 0xffff0000,
329 'right' => 0x0000ffff,
335 'left' => 0xffffffff00000000,
336 'right' => 0x00000000ffffffff,
343 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
345 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
347 private $archArrayElement = FALSE;
349 /***********************
350 * Exception codes.... *
351 ***********************/
353 // @todo Try to clean these constants up
354 const EXCEPTION_IS_NULL_POINTER = 0x001;
355 const EXCEPTION_IS_NO_OBJECT = 0x002;
356 const EXCEPTION_IS_NO_ARRAY = 0x003;
357 const EXCEPTION_MISSING_METHOD = 0x004;
358 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
359 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
360 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
361 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
362 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
363 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
364 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
365 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
366 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
367 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
368 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
369 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
370 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
371 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
372 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
373 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
374 const EXCEPTION_PATH_NOT_FOUND = 0x015;
375 const EXCEPTION_INVALID_PATH_NAME = 0x016;
376 const EXCEPTION_READ_PROTECED_PATH = 0x017;
377 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
378 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
379 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
380 const EXCEPTION_INVALID_RESOURCE = 0x01b;
381 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
382 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
383 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
384 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
385 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
386 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
387 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
388 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
389 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
390 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
391 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
392 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
393 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
394 const EXCEPTION_INVALID_STRING = 0x029;
395 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
396 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
397 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
398 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
399 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
400 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
401 const EXCEPTION_MISSING_ELEMENT = 0x030;
402 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
403 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
404 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
405 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
406 const EXCEPTION_FATAL_ERROR = 0x035;
407 const EXCEPTION_FILE_NOT_FOUND = 0x036;
408 const EXCEPTION_ASSERTION_FAILED = 0x037;
409 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
410 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
411 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
412 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
413 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
414 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
417 * Hexadecimal->Decimal translation array
419 private static $hexdec = array(
439 * Decimal->hexadecimal translation array
441 private static $dechex = array(
461 * Startup time in miliseconds
463 private static $startupTime = 0;
466 * Protected super constructor
468 * @param $className Name of the class
471 protected function __construct ($className) {
473 $this->setRealClass($className);
475 // Set configuration instance if no registry ...
476 if (!$this instanceof Register) {
477 // ... because registries doesn't need to be configured
478 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
481 // Is the startup time set? (0 cannot be TRUE anymore)
482 if (self::$startupTime == 0) {
484 self::$startupTime = microtime(TRUE);
488 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
492 * Destructor for all classes. You should not call this method on your own.
496 public function __destruct () {
497 // Flush any updated entries to the database
498 $this->flushPendingUpdates();
500 // Is this object already destroyed?
501 if ($this->__toString() != 'DestructedObject') {
502 // Destroy all informations about this class but keep some text about it alive
503 $this->setRealClass('DestructedObject');
504 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
505 // Already destructed object
506 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
511 // Do not call this twice
512 trigger_error(__METHOD__ . ': Called twice.');
518 * The __call() method where all non-implemented methods end up
520 * @param $methodName Name of the missing method
521 * @args $args Arguments passed to the method
524 public final function __call ($methodName, $args) {
525 return self::__callStatic($methodName, $args);
529 * The __callStatic() method where all non-implemented static methods end up
531 * @param $methodName Name of the missing method
532 * @args $args Arguments passed to the method
535 public static final function __callStatic ($methodName, $args) {
537 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
539 // Init argument string
542 // Is it NULL, empty or an array?
543 if (is_null($args)) {
545 $argsString = 'NULL';
546 } elseif (is_array($args)) {
550 // Some arguments are there
551 foreach ($args as $arg) {
552 // Add data about the argument
553 $argsString .= gettype($arg) . ':';
556 // Found a NULL argument
557 $argsString .= 'NULL';
558 } elseif (is_string($arg)) {
559 // Add length for strings
560 $argsString .= strlen($arg);
561 } elseif ((is_int($arg)) || (is_float($arg))) {
564 } elseif (is_array($arg)) {
565 // .. or size if array
566 $argsString .= count($arg);
567 } elseif (is_object($arg)) {
569 $reflection = new ReflectionClass($arg);
571 // Is an other object, maybe no __toString() available
572 $argsString .= $reflection->getName();
573 } elseif ($arg === TRUE) {
574 // ... is boolean 'TRUE'
575 $argsString .= 'TRUE';
576 } elseif ($arg === FALSE) {
577 // ... is boolean 'FALSE'
578 $argsString .= 'FALSE';
581 // Comma for next one
586 if (substr($argsString, -2, 1) == ',') {
587 $argsString = substr($argsString, 0, -2);
593 // Invalid arguments!
594 $argsString = '!INVALID:' . gettype($args) . '!';
597 // Output stub message
598 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
599 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
609 * Getter for $realClass
611 * @return $realClass The name of the real class (not BaseFrameworkSystem)
613 public function __toString () {
614 return $this->realClass;
618 * Magic method to catch setting of missing but set class fields/attributes
620 * @param $name Name of the field/attribute
621 * @param $value Value to store
624 public final function __set ($name, $value) {
625 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
628 print_r($value, TRUE)
633 * Magic method to catch getting of missing fields/attributes
635 * @param $name Name of the field/attribute
638 public final function __get ($name) {
639 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
645 * Magic method to catch unsetting of missing fields/attributes
647 * @param $name Name of the field/attribute
650 public final function __unset ($name) {
651 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
657 * Magic method to catch object serialization
659 * @return $unsupported Unsupported method
660 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
662 public final function __sleep () {
663 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
667 * Magic method to catch object deserialization
669 * @return $unsupported Unsupported method
670 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
672 public final function __wakeup () {
673 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
677 * Magic method to catch calls when an object instance is called
679 * @return $unsupported Unsupported method
680 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
682 public final function __invoke () {
683 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
687 * Setter for the real class name
689 * @param $realClass Class name (string)
692 public final function setRealClass ($realClass) {
694 $this->realClass = (string) $realClass;
698 * Setter for database result instance
700 * @param $resultInstance An instance of a database result class
702 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
704 protected final function setResultInstance (SearchableResult $resultInstance) {
705 $this->resultInstance = $resultInstance;
709 * Getter for database result instance
711 * @return $resultInstance An instance of a database result class
713 public final function getResultInstance () {
714 return $this->resultInstance;
718 * Setter for template engine instances
720 * @param $templateInstance An instance of a template engine class
723 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
724 $this->templateInstance = $templateInstance;
728 * Getter for template engine instances
730 * @return $templateInstance An instance of a template engine class
732 protected final function getTemplateInstance () {
733 return $this->templateInstance;
737 * Setter for search instance
739 * @param $searchInstance Searchable criteria instance
742 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
743 $this->searchInstance = $searchInstance;
747 * Getter for search instance
749 * @return $searchInstance Searchable criteria instance
751 public final function getSearchInstance () {
752 return $this->searchInstance;
756 * Setter for update instance
758 * @param $updateInstance An instance of a LocalUpdateCriteria clase
761 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
762 $this->updateInstance = $updateInstance;
766 * Getter for update instance
768 * @return $updateInstance Updateable criteria instance
770 public final function getUpdateInstance () {
771 return $this->updateInstance;
775 * Setter for resolver instance
777 * @param $resolverInstance Instance of a command resolver class
780 public final function setResolverInstance (Resolver $resolverInstance) {
781 $this->resolverInstance = $resolverInstance;
785 * Getter for resolver instance
787 * @return $resolverInstance Instance of a command resolver class
789 public final function getResolverInstance () {
790 return $this->resolverInstance;
794 * Setter for language instance
796 * @param $configInstance The configuration instance which shall
797 * be FrameworkConfiguration
800 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
801 Registry::getRegistry()->addInstance('config', $configInstance);
805 * Getter for configuration instance
807 * @return $configInstance Configuration instance
809 public final function getConfigInstance () {
810 $configInstance = Registry::getRegistry()->getInstance('config');
811 return $configInstance;
815 * Setter for debug instance
817 * @param $debugInstance The instance for debug output class
820 public final function setDebugInstance (DebugMiddleware $debugInstance) {
821 Registry::getRegistry()->addInstance('debug', $debugInstance);
825 * Getter for debug instance
827 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
829 public final function getDebugInstance () {
830 // Get debug instance
831 $debugInstance = Registry::getRegistry()->getInstance('debug');
834 return $debugInstance;
838 * Setter for web output instance
840 * @param $webInstance The instance for web output class
843 public final function setWebOutputInstance (OutputStreamer $webInstance) {
844 Registry::getRegistry()->addInstance('web_output', $webInstance);
848 * Getter for web output instance
850 * @return $webOutputInstance - Instance to class WebOutput
852 public final function getWebOutputInstance () {
853 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
854 return $webOutputInstance;
858 * Setter for database instance
860 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
863 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
864 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
868 * Getter for database layer
870 * @return $databaseInstance The database layer instance
872 public final function getDatabaseInstance () {
874 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
877 return $databaseInstance;
881 * Setter for compressor channel
883 * @param $compressorInstance An instance of CompressorChannel
886 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
887 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
891 * Getter for compressor channel
893 * @return $compressorInstance The compressor channel
895 public final function getCompressorChannel () {
896 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
897 return $compressorInstance;
901 * Protected getter for a manageable application helper class
903 * @return $applicationInstance An instance of a manageable application helper class
905 protected final function getApplicationInstance () {
906 $applicationInstance = Registry::getRegistry()->getInstance('application');
907 return $applicationInstance;
911 * Setter for a manageable application helper class
913 * @param $applicationInstance An instance of a manageable application helper class
916 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
917 Registry::getRegistry()->addInstance('application', $applicationInstance);
921 * Setter for request instance
923 * @param $requestInstance An instance of a Requestable class
926 public final function setRequestInstance (Requestable $requestInstance) {
927 $this->requestInstance = $requestInstance;
931 * Getter for request instance
933 * @return $requestInstance An instance of a Requestable class
935 public final function getRequestInstance () {
936 return $this->requestInstance;
940 * Setter for response instance
942 * @param $responseInstance An instance of a Responseable class
945 public final function setResponseInstance (Responseable $responseInstance) {
946 $this->responseInstance = $responseInstance;
950 * Getter for response instance
952 * @return $responseInstance An instance of a Responseable class
954 public final function getResponseInstance () {
955 return $this->responseInstance;
959 * Private getter for language instance
961 * @return $langInstance An instance to the language sub-system
963 protected final function getLanguageInstance () {
964 $langInstance = Registry::getRegistry()->getInstance('language');
965 return $langInstance;
969 * Setter for language instance
971 * @param $langInstance An instance to the language sub-system
973 * @see LanguageSystem
975 public final function setLanguageInstance (ManageableLanguage $langInstance) {
976 Registry::getRegistry()->addInstance('language', $langInstance);
980 * Private getter for file IO instance
982 * @return $fileIoInstance An instance to the file I/O sub-system
984 protected final function getFileIoInstance () {
985 return $this->fileIoInstance;
989 * Setter for file I/O instance
991 * @param $fileIoInstance An instance to the file I/O sub-system
994 public final function setFileIoInstance (IoHandler $fileIoInstance) {
995 $this->fileIoInstance = $fileIoInstance;
999 * Protected setter for user instance
1001 * @param $userInstance An instance of a user class
1004 protected final function setUserInstance (ManageableAccount $userInstance) {
1005 $this->userInstance = $userInstance;
1009 * Getter for user instance
1011 * @return $userInstance An instance of a user class
1013 public final function getUserInstance () {
1014 return $this->userInstance;
1018 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1020 * @param $controllerInstance An instance of the controller
1023 public final function setControllerInstance (Controller $controllerInstance) {
1024 $this->controllerInstance = $controllerInstance;
1028 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1030 * @return $controllerInstance An instance of the controller
1032 public final function getControllerInstance () {
1033 return $this->controllerInstance;
1037 * Setter for RNG instance
1039 * @param $rngInstance An instance of a random number generator (RNG)
1042 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1043 $this->rngInstance = $rngInstance;
1047 * Getter for RNG instance
1049 * @return $rngInstance An instance of a random number generator (RNG)
1051 public final function getRngInstance () {
1052 return $this->rngInstance;
1056 * Setter for Cryptable instance
1058 * @param $cryptoInstance An instance of a Cryptable class
1061 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1062 $this->cryptoInstance = $cryptoInstance;
1066 * Getter for Cryptable instance
1068 * @return $cryptoInstance An instance of a Cryptable class
1070 public final function getCryptoInstance () {
1071 return $this->cryptoInstance;
1075 * Setter for the list instance
1077 * @param $listInstance A list of Listable
1080 protected final function setListInstance (Listable $listInstance) {
1081 $this->listInstance = $listInstance;
1085 * Getter for the list instance
1087 * @return $listInstance A list of Listable
1089 protected final function getListInstance () {
1090 return $this->listInstance;
1094 * Setter for the menu instance
1096 * @param $menuInstance A RenderableMenu instance
1099 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1100 $this->menuInstance = $menuInstance;
1104 * Getter for the menu instance
1106 * @return $menuInstance A RenderableMenu instance
1108 protected final function getMenuInstance () {
1109 return $this->menuInstance;
1113 * Setter for image instance
1115 * @param $imageInstance An instance of an image
1118 public final function setImageInstance (BaseImage $imageInstance) {
1119 $this->imageInstance = $imageInstance;
1123 * Getter for image instance
1125 * @return $imageInstance An instance of an image
1127 public final function getImageInstance () {
1128 return $this->imageInstance;
1132 * Setter for stacker instance
1134 * @param $stackInstance An instance of an stacker
1137 public final function setStackInstance (Stackable $stackInstance) {
1138 $this->stackInstance = $stackInstance;
1142 * Getter for stacker instance
1144 * @return $stackInstance An instance of an stacker
1146 public final function getStackInstance () {
1147 return $this->stackInstance;
1151 * Setter for compressor instance
1153 * @param $compressorInstance An instance of an compressor
1156 public final function setCompressorInstance (Compressor $compressorInstance) {
1157 $this->compressorInstance = $compressorInstance;
1161 * Getter for compressor instance
1163 * @return $compressorInstance An instance of an compressor
1165 public final function getCompressorInstance () {
1166 return $this->compressorInstance;
1170 * Setter for Parseable instance
1172 * @param $parserInstance An instance of an Parseable
1175 public final function setParserInstance (Parseable $parserInstance) {
1176 $this->parserInstance = $parserInstance;
1180 * Getter for Parseable instance
1182 * @return $parserInstance An instance of an Parseable
1184 public final function getParserInstance () {
1185 return $this->parserInstance;
1189 * Setter for HandleableProtocol instance
1191 * @param $protocolInstance An instance of an HandleableProtocol
1194 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1195 $this->protocolInstance = $protocolInstance;
1199 * Getter for HandleableProtocol instance
1201 * @return $protocolInstance An instance of an HandleableProtocol
1203 public final function getProtocolInstance () {
1204 return $this->protocolInstance;
1208 * Setter for DatabaseWrapper instance
1210 * @param $wrapperInstance An instance of an DatabaseWrapper
1213 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1214 $this->wrapperInstance = $wrapperInstance;
1218 * Getter for DatabaseWrapper instance
1220 * @return $wrapperInstance An instance of an DatabaseWrapper
1222 public final function getWrapperInstance () {
1223 return $this->wrapperInstance;
1227 * Setter for socket resource
1229 * @param $socketResource A valid socket resource
1232 public final function setSocketResource ($socketResource) {
1233 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1234 $this->socketResource = $socketResource;
1238 * Getter for socket resource
1240 * @return $socketResource A valid socket resource
1242 public final function getSocketResource () {
1243 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1244 return $this->socketResource;
1248 * Setter for regular expression
1250 * @param $regularExpression A valid regular expression
1253 public final function setRegularExpression ($regularExpression) {
1254 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1255 $this->regularExpression = $regularExpression;
1259 * Getter for regular expression
1261 * @return $regularExpression A valid regular expression
1263 public final function getRegularExpression () {
1264 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1265 return $this->regularExpression;
1269 * Setter for helper instance
1271 * @param $helperInstance An instance of a helper class
1274 protected final function setHelperInstance (Helper $helperInstance) {
1275 $this->helperInstance = $helperInstance;
1279 * Getter for helper instance
1281 * @return $helperInstance An instance of a helper class
1283 public final function getHelperInstance () {
1284 return $this->helperInstance;
1288 * Setter for a Source instance
1290 * @param $sourceInstance An instance of a Source class
1293 protected final function setSourceInstance (Source $sourceInstance) {
1294 $this->sourceInstance = $sourceInstance;
1298 * Getter for a Source instance
1300 * @return $sourceInstance An instance of a Source class
1302 protected final function getSourceInstance () {
1303 return $this->sourceInstance;
1307 * Setter for a UrlSource instance
1309 * @param $sourceInstance An instance of a UrlSource class
1312 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1313 $this->urlSourceInstance = $urlSourceInstance;
1317 * Getter for a UrlSource instance
1319 * @return $urlSourceInstance An instance of a UrlSource class
1321 protected final function getUrlSourceInstance () {
1322 return $this->urlSourceInstance;
1326 * Getter for a InputStream instance
1328 * @param $inputStreamInstance The InputStream instance
1330 protected final function getInputStreamInstance () {
1331 return $this->inputStreamInstance;
1335 * Setter for a InputStream instance
1337 * @param $inputStreamInstance The InputStream instance
1340 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1341 $this->inputStreamInstance = $inputStreamInstance;
1345 * Getter for a OutputStream instance
1347 * @param $outputStreamInstance The OutputStream instance
1349 protected final function getOutputStreamInstance () {
1350 return $this->outputStreamInstance;
1354 * Setter for a OutputStream instance
1356 * @param $outputStreamInstance The OutputStream instance
1359 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1360 $this->outputStreamInstance = $outputStreamInstance;
1364 * Setter for handler instance
1366 * @param $handlerInstance An instance of a Handleable class
1369 protected final function setHandlerInstance (Handleable $handlerInstance) {
1370 $this->handlerInstance = $handlerInstance;
1374 * Getter for handler instance
1376 * @return $handlerInstance A Networkable instance
1378 protected final function getHandlerInstance () {
1379 return $this->handlerInstance;
1383 * Setter for visitor instance
1385 * @param $visitorInstance A Visitor instance
1388 protected final function setVisitorInstance (Visitor $visitorInstance) {
1389 $this->visitorInstance = $visitorInstance;
1393 * Getter for visitor instance
1395 * @return $visitorInstance A Visitor instance
1397 protected final function getVisitorInstance () {
1398 return $this->visitorInstance;
1402 * Setter for DHT instance
1404 * @param $dhtInstance A Distributable instance
1407 protected final function setDhtInstance (Distributable $dhtInstance) {
1408 $this->dhtInstance = $dhtInstance;
1412 * Getter for DHT instance
1414 * @return $dhtInstance A Distributable instance
1416 protected final function getDhtInstance () {
1417 return $this->dhtInstance;
1421 * Setter for raw package Data
1423 * @param $packageData Raw package Data
1426 public final function setPackageData (array $packageData) {
1427 $this->packageData = $packageData;
1431 * Getter for raw package Data
1433 * @return $packageData Raw package Data
1435 public function getPackageData () {
1436 return $this->packageData;
1441 * Setter for Iterator instance
1443 * @param $iteratorInstance An instance of an Iterator
1446 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1447 $this->iteratorInstance = $iteratorInstance;
1451 * Getter for Iterator instance
1453 * @return $iteratorInstance An instance of an Iterator
1455 public final function getIteratorInstance () {
1456 return $this->iteratorInstance;
1460 * Setter for FilePointer instance
1462 * @param $pointerInstance An instance of an FilePointer class
1465 protected final function setPointerInstance (FilePointer $pointerInstance) {
1466 $this->pointerInstance = $pointerInstance;
1470 * Getter for FilePointer instance
1472 * @return $pointerInstance An instance of an FilePointer class
1474 public final function getPointerInstance () {
1475 return $this->pointerInstance;
1479 * Unsets pointer instance which triggers a call of __destruct() if the
1480 * instance is still there. This is surely not fatal on already "closed"
1481 * file pointer instances.
1483 * I don't want to mess around with above setter by giving it a default
1484 * value NULL as setter should always explicitly only set (existing) object
1485 * instances and NULL is NULL.
1489 protected final function unsetPointerInstance () {
1490 // Simply it to NULL
1491 $this->pointerInstance = NULL;
1495 * Setter for Indexable instance
1497 * @param $indexInstance An instance of an Indexable class
1500 protected final function setIndexInstance (Indexable $indexInstance) {
1501 $this->indexInstance = $indexInstance;
1505 * Getter for Indexable instance
1507 * @return $indexInstance An instance of an Indexable class
1509 public final function getIndexInstance () {
1510 return $this->indexInstance;
1514 * Setter for Block instance
1516 * @param $blockInstance An instance of an Block class
1519 protected final function setBlockInstance (Block $blockInstance) {
1520 $this->blockInstance = $blockInstance;
1524 * Getter for Block instance
1526 * @return $blockInstance An instance of an Block class
1528 public final function getBlockInstance () {
1529 return $this->blockInstance;
1533 * Setter for Minable instance
1535 * @param $minableInstance A Minable instance
1538 protected final function setMinableInstance (Minable $minableInstance) {
1539 $this->minableInstance = $minableInstance;
1543 * Getter for minable instance
1545 * @return $minableInstance A Minable instance
1547 protected final function getMinableInstance () {
1548 return $this->minableInstance;
1552 * Setter for FrameworkDirectory instance
1554 * @param $directoryInstance A FrameworkDirectory instance
1557 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1558 $this->directoryInstance = $directoryInstance;
1562 * Getter for FrameworkDirectory instance
1564 * @return $directoryInstance A FrameworkDirectory instance
1566 protected final function getDirectoryInstance () {
1567 return $this->directoryInstance;
1571 * Setter for listener instance
1573 * @param $listenerInstance A Listenable instance
1576 protected final function setListenerInstance (Listenable $listenerInstance) {
1577 $this->listenerInstance = $listenerInstance;
1581 * Getter for listener instance
1583 * @return $listenerInstance A Listenable instance
1585 protected final function getListenerInstance () {
1586 return $this->listenerInstance;
1590 * Getter for communicator instance
1592 * @return $communicatorInstance An instance of a Communicator class
1594 public final function getCommunicatorInstance () {
1595 return $this->communicatorInstance;
1599 * Setter for communicator instance
1601 * @param $communicatorInstance An instance of a Communicator class
1604 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1605 $this->communicatorInstance = $communicatorInstance;
1609 * Setter for state instance
1611 * @param $stateInstance A Stateable instance
1614 public final function setStateInstance (Stateable $stateInstance) {
1615 $this->stateInstance = $stateInstance;
1619 * Getter for state instance
1621 * @return $stateInstance A Stateable instance
1623 public final function getStateInstance () {
1624 return $this->stateInstance;
1628 * Setter for output instance
1630 * @param $outputInstance The debug output instance
1633 public final function setOutputInstance (OutputStreamer $outputInstance) {
1634 $this->outputInstance = $outputInstance;
1638 * Getter for output instance
1640 * @return $outputInstance The debug output instance
1642 public final function getOutputInstance () {
1643 return $this->outputInstance;
1647 * Setter for command name
1649 * @param $commandName Last validated command name
1652 protected final function setCommandName ($commandName) {
1653 $this->commandName = $commandName;
1657 * Getter for command name
1659 * @return $commandName Last validated command name
1661 protected final function getCommandName () {
1662 return $this->commandName;
1666 * Setter for controller name
1668 * @param $controllerName Last validated controller name
1671 protected final function setControllerName ($controllerName) {
1672 $this->controllerName = $controllerName;
1676 * Getter for controller name
1678 * @return $controllerName Last validated controller name
1680 protected final function getControllerName () {
1681 return $this->controllerName;
1685 * Getter for protocol name
1687 * @return $protocolName Name of used protocol
1689 public final function getProtocolName () {
1690 return $this->protocolName;
1694 * Setter for protocol name
1696 * @param $protocolName Name of used protocol
1699 protected final function setProtocolName ($protocolName) {
1700 $this->protocolName = $protocolName;
1704 * Checks whether an object equals this object. You should overwrite this
1705 * method to implement own equality checks
1707 * @param $objectInstance An instance of a FrameworkInterface object
1708 * @return $equals Whether both objects equals
1710 public function equals (FrameworkInterface $objectInstance) {
1713 $this->__toString() == $objectInstance->__toString()
1715 $this->hashCode() == $objectInstance->hashCode()
1718 // Return the result
1723 * Generates a generic hash code of this class. You should really overwrite
1724 * this method with your own hash code generator code. But keep KISS in mind.
1726 * @return $hashCode A generic hash code respresenting this whole class
1728 public function hashCode () {
1730 return crc32($this->__toString());
1734 * Formats computer generated price values into human-understandable formats
1735 * with thousand and decimal separators.
1737 * @param $value The in computer format value for a price
1738 * @param $currency The currency symbol (use HTML-valid characters!)
1739 * @param $decNum Number of decimals after commata
1740 * @return $price The for the current language formated price string
1741 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1742 * thousands separator
1745 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1746 // Are all required attriutes set?
1747 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1748 // Throw an exception
1749 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1753 $value = (float) $value;
1755 // Reformat the US number
1756 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1758 // Return as string...
1763 * Appends a trailing slash to a string
1765 * @param $str A string (maybe) without trailing slash
1766 * @return $str A string with an auto-appended trailing slash
1768 public final function addMissingTrailingSlash ($str) {
1769 // Is there a trailing slash?
1770 if (substr($str, -1, 1) != '/') {
1774 // Return string with trailing slash
1779 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1780 * application helper instance (ApplicationHelper by default).
1782 * @param $applicationInstance An application helper instance or
1783 * null if we shall use the default
1784 * @return $templateInstance The template engine instance
1785 * @throws NullPointerException If the discovered application
1786 * instance is still null
1788 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1789 // Is the application instance set?
1790 if (is_null($applicationInstance)) {
1791 // Get the current instance
1792 $applicationInstance = $this->getApplicationInstance();
1795 if (is_null($applicationInstance)) {
1796 // Thrown an exception
1797 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1801 // Initialize the template engine
1802 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1804 // Return the prepared instance
1805 return $templateInstance;
1809 * Debugs this instance by putting out it's full content
1811 * @param $message Optional message to show in debug output
1814 public final function debugInstance ($message = '') {
1815 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1816 restore_error_handler();
1821 // Is a message set?
1822 if (!empty($message)) {
1823 // Construct message
1824 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1827 // Generate the output
1828 $content .= sprintf('<pre>%s</pre>',
1831 print_r($this, TRUE)
1837 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>',
1838 $this->__toString(),
1840 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1845 * Replaces control characters with printable output
1847 * @param $str String with control characters
1848 * @return $str Replaced string
1850 protected function replaceControlCharacters ($str) {
1853 chr(13), '[r]', str_replace(
1854 chr(10), '[n]', str_replace(
1864 * Output a partial stub message for the caller method
1866 * @param $message An optional message to display
1869 protected function partialStub ($message = '') {
1870 // Get the backtrace
1871 $backtrace = debug_backtrace();
1873 // Generate the class::method string
1874 $methodName = 'UnknownClass->unknownMethod';
1875 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1876 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1879 // Construct the full message
1880 $stubMessage = sprintf('[%s:] Partial stub!',
1884 // Is the extra message given?
1885 if (!empty($message)) {
1886 // Then add it as well
1887 $stubMessage .= ' Message: ' . $message;
1890 // Debug instance is there?
1891 if (!is_null($this->getDebugInstance())) {
1892 // Output stub message
1893 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1896 trigger_error($stubMessage);
1902 * Outputs a debug backtrace and stops further script execution
1904 * @param $message An optional message to output
1905 * @param $doExit Whether exit the program (TRUE is default)
1908 public function debugBackTrace ($message = '', $doExit = TRUE) {
1909 // Sorry, there is no other way getting this nice backtrace
1910 if (!empty($message)) {
1912 printf('Message: %s<br />' . PHP_EOL, $message);
1916 debug_print_backtrace();
1920 if ($doExit === TRUE) {
1926 * Creates an instance of a debugger instance
1928 * @param $className Name of the class (currently unsupported)
1929 * @param $lineNumber Line number where the call was made
1930 * @return $debugInstance An instance of a debugger class
1931 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1933 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1934 // Is the instance set?
1935 if (!Registry::getRegistry()->instanceExists('debug')) {
1936 // Init debug instance
1937 $debugInstance = NULL;
1941 // Get a debugger instance
1942 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1943 } catch (NullPointerException $e) {
1944 // Didn't work, no instance there
1945 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1948 // Empty string should be ignored and used for testing the middleware
1949 DebugMiddleware::getSelfInstance()->output('');
1951 // Set it in its own class. This will set it in the registry
1952 $debugInstance->setDebugInstance($debugInstance);
1954 // Get instance from registry
1955 $debugInstance = Registry::getRegistry()->getDebugInstance();
1959 return $debugInstance;
1963 * Simple output of a message with line-break
1965 * @param $message Message to output
1968 public function outputLine ($message) {
1970 print($message . PHP_EOL);
1974 * Outputs a debug message whether to debug instance (should be set!) or
1975 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1976 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1978 * @param $message Message we shall send out...
1979 * @param $doPrint Whether print or die here (default: print)
1980 * @paran $stripTags Whether to strip tags (default: FALSE)
1983 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1984 // Set debug instance to NULL
1985 $debugInstance = NULL;
1989 // Get debug instance
1990 $debugInstance = $this->getDebugInstance();
1991 } catch (NullPointerException $e) {
1992 // The debug instance is not set (yet)
1995 // Is the debug instance there?
1996 if (is_object($debugInstance)) {
1997 // Use debug output handler
1998 $debugInstance->output($message, $stripTags);
2000 if ($doPrint === FALSE) {
2001 // Die here if not printed
2005 // Are debug times enabled?
2006 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
2008 $message = $this->getPrintableExecutionTime() . $message;
2012 if ($doPrint === TRUE) {
2014 $this->outputLine($message);
2023 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2025 * @param $str The string, what ever it is needs to be converted
2026 * @return $className Generated class name
2028 public static final function convertToClassName ($str) {
2032 // Convert all dashes in underscores
2033 $str = self::convertDashesToUnderscores($str);
2035 // Now use that underscores to get classname parts for hungarian style
2036 foreach (explode('_', $str) as $strPart) {
2037 // Make the class name part lower case and first upper case
2038 $className .= ucfirst(strtolower($strPart));
2041 // Return class name
2046 * Converts dashes to underscores, e.g. useable for configuration entries
2048 * @param $str The string with maybe dashes inside
2049 * @return $str The converted string with no dashed, but underscores
2051 public static final function convertDashesToUnderscores ($str) {
2053 $str = str_replace('-', '_', $str);
2055 // Return converted string
2060 * Marks up the code by adding e.g. line numbers
2062 * @param $phpCode Unmarked PHP code
2063 * @return $markedCode Marked PHP code
2065 public function markupCode ($phpCode) {
2070 $errorArray = error_get_last();
2072 // Init the code with error message
2073 if (is_array($errorArray)) {
2075 $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>',
2076 basename($errorArray['file']),
2077 $errorArray['line'],
2078 $errorArray['message'],
2083 // Add line number to the code
2084 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2086 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2088 htmlentities($code, ENT_QUOTES)
2097 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2098 * beatiful for web-based front-ends. If null is given a message id
2099 * null_timestamp will be resolved and returned.
2101 * @param $timestamp Timestamp to prepare (filter) for display
2102 * @return $readable A readable timestamp
2104 public function doFilterFormatTimestamp ($timestamp) {
2105 // Default value to return
2108 // Is the timestamp null?
2109 if (is_null($timestamp)) {
2110 // Get a message string
2111 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2113 switch ($this->getLanguageInstance()->getLanguageCode()) {
2114 case 'de': // German format is a bit different to default
2115 // Split the GMT stamp up
2116 $dateTime = explode(' ', $timestamp );
2117 $dateArray = explode('-', $dateTime[0]);
2118 $timeArray = explode(':', $dateTime[1]);
2120 // Construct the timestamp
2121 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2131 default: // Default is pass-through
2132 $readable = $timestamp;
2142 * Filter a given number into a localized number
2144 * @param $value The raw value from e.g. database
2145 * @return $localized Localized value
2147 public function doFilterFormatNumber ($value) {
2148 // Generate it from config and localize dependencies
2149 switch ($this->getLanguageInstance()->getLanguageCode()) {
2150 case 'de': // German format is a bit different to default
2151 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2154 default: // US, etc.
2155 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2164 * "Getter" for databse entry
2166 * @return $entry An array with database entries
2167 * @throws NullPointerException If the database result is not found
2168 * @throws InvalidDatabaseResultException If the database result is invalid
2170 protected final function getDatabaseEntry () {
2171 // Is there an instance?
2172 if (!$this->getResultInstance() instanceof SearchableResult) {
2173 // Throw an exception here
2174 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2178 $this->getResultInstance()->rewind();
2180 // Do we have an entry?
2181 if ($this->getResultInstance()->valid() === FALSE) {
2182 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2183 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2187 $this->getResultInstance()->next();
2190 $entry = $this->getResultInstance()->current();
2197 * Getter for field name
2199 * @param $fieldName Field name which we shall get
2200 * @return $fieldValue Field value from the user
2201 * @throws NullPointerException If the result instance is null
2203 public final function getField ($fieldName) {
2204 // Default field value
2207 // Get result instance
2208 $resultInstance = $this->getResultInstance();
2210 // Is this instance null?
2211 if (is_null($resultInstance)) {
2212 // Then the user instance is no longer valid (expired cookies?)
2213 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2216 // Get current array
2217 $fieldArray = $resultInstance->current();
2218 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2220 // Convert dashes to underscore
2221 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2223 // Does the field exist?
2224 if ($this->isFieldSet($fieldName)) {
2226 $fieldValue = $fieldArray[$fieldName2];
2227 } elseif (defined('DEVELOPER')) {
2228 // Missing field entry, may require debugging
2229 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2231 // Missing field entry, may require debugging
2232 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2240 * Checks if given field is set
2242 * @param $fieldName Field name to check
2243 * @return $isSet Whether the given field name is set
2244 * @throws NullPointerException If the result instance is null
2246 public function isFieldSet ($fieldName) {
2247 // Get result instance
2248 $resultInstance = $this->getResultInstance();
2250 // Is this instance null?
2251 if (is_null($resultInstance)) {
2252 // Then the user instance is no longer valid (expired cookies?)
2253 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2256 // Get current array
2257 $fieldArray = $resultInstance->current();
2258 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2260 // Convert dashes to underscore
2261 $fieldName = self::convertDashesToUnderscores($fieldName);
2264 $isSet = isset($fieldArray[$fieldName]);
2271 * Flushs all pending updates to the database layer
2275 public function flushPendingUpdates () {
2276 // Get result instance
2277 $resultInstance = $this->getResultInstance();
2279 // Do we have data to update?
2280 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2281 // Get wrapper class name config entry
2282 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2284 // Create object instance
2285 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2287 // Yes, then send the whole result to the database layer
2288 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2293 * Outputs a deprecation warning to the developer.
2295 * @param $message The message we shall output to the developer
2297 * @todo Write a logging mechanism for productive mode
2299 public function deprecationWarning ($message) {
2300 // Is developer mode active?
2301 if (defined('DEVELOPER')) {
2302 // Debug instance is there?
2303 if (!is_null($this->getDebugInstance())) {
2304 // Output stub message
2305 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2308 trigger_error($message . "<br />\n");
2312 // @TODO Finish this part!
2313 $this->partialStub('Developer mode inactive. Message:' . $message);
2318 * Checks whether the given PHP extension is loaded
2320 * @param $phpExtension The PHP extension we shall check
2321 * @return $isLoaded Whether the PHP extension is loaded
2323 public final function isPhpExtensionLoaded ($phpExtension) {
2325 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2332 * "Getter" as a time() replacement but with milliseconds. You should use this
2333 * method instead of the encapsulated getimeofday() function.
2335 * @return $milliTime Timestamp with milliseconds
2337 public function getMilliTime () {
2338 // Get the time of day as float
2339 $milliTime = gettimeofday(TRUE);
2346 * Idles (sleeps) for given milliseconds
2348 * @return $hasSlept Whether it goes fine
2350 public function idle ($milliSeconds) {
2351 // Sleep is fine by default
2354 // Idle so long with found function
2355 if (function_exists('time_sleep_until')) {
2356 // Get current time and add idle time
2357 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2359 // New PHP 5.1.0 function found, ignore errors
2360 $hasSlept = @time_sleep_until($sleepUntil);
2363 * My Sun station doesn't have that function even with latest PHP
2366 usleep($milliSeconds * 1000);
2373 * Converts a hexadecimal string, even with negative sign as first string to
2374 * a decimal number using BC functions.
2376 * This work is based on comment #86673 on php.net documentation page at:
2377 * <http://de.php.net/manual/en/function.dechex.php#86673>
2379 * @param $hex Hexadecimal string
2380 * @return $dec Decimal number
2382 protected function hex2dec ($hex) {
2383 // Convert to all lower-case
2384 $hex = strtolower($hex);
2386 // Detect sign (negative/positive numbers)
2388 if (substr($hex, 0, 1) == '-') {
2390 $hex = substr($hex, 1);
2393 // Decode the hexadecimal string into a decimal number
2395 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2396 $factor = self::$hexdec[substr($hex, $i, 1)];
2397 $dec = bcadd($dec, bcmul($factor, $e));
2400 // Return the decimal number
2401 return $sign . $dec;
2405 * Converts even very large decimal numbers, also signed, to a hexadecimal
2408 * This work is based on comment #97756 on php.net documentation page at:
2409 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2411 * @param $dec Decimal number, even with negative sign
2412 * @param $maxLength Optional maximum length of the string
2413 * @return $hex Hexadecimal string
2415 protected function dec2hex ($dec, $maxLength = 0) {
2416 // maxLength can be zero or devideable by 2
2417 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2419 // Detect sign (negative/positive numbers)
2426 // Encode the decimal number into a hexadecimal string
2429 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2431 } while ($dec >= 1);
2434 * Leading zeros are required for hex-decimal "numbers". In some
2435 * situations more leading zeros are wanted, so check for both
2438 if ($maxLength > 0) {
2439 // Prepend more zeros
2440 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2441 } elseif ((strlen($hex) % 2) != 0) {
2442 // Only make string's length dividable by 2
2446 // Return the hexadecimal string
2447 return $sign . $hex;
2451 * Converts a ASCII string (0 to 255) into a decimal number.
2453 * @param $asc The ASCII string to be converted
2454 * @return $dec Decimal number
2456 protected function asc2dec ($asc) {
2457 // Convert it into a hexadecimal number
2458 $hex = bin2hex($asc);
2460 // And back into a decimal number
2461 $dec = $this->hex2dec($hex);
2468 * Converts a decimal number into an ASCII string.
2470 * @param $dec Decimal number
2471 * @return $asc An ASCII string
2473 protected function dec2asc ($dec) {
2474 // First convert the number into a hexadecimal string
2475 $hex = $this->dec2hex($dec);
2477 // Then convert it into the ASCII string
2478 $asc = $this->hex2asc($hex);
2485 * Converts a hexadecimal number into an ASCII string. Negative numbers
2488 * @param $hex Hexadecimal string
2489 * @return $asc An ASCII string
2491 protected function hex2asc ($hex) {
2492 // Check for length, it must be devideable by 2
2493 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2494 assert((strlen($hex) % 2) == 0);
2498 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2499 // Get the decimal number of the chunk
2500 $part = hexdec(substr($hex, $idx, 2));
2502 // Add it to the final string
2506 // Return the final string
2511 * Checks whether the given encoded data was encoded with Base64
2513 * @param $encodedData Encoded data we shall check
2514 * @return $isBase64 Whether the encoded data is Base64
2516 protected function isBase64Encoded ($encodedData) {
2518 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2525 * "Getter" to get response/request type from analysis of the system.
2527 * @return $responseType Analyzed response type
2529 protected static function getResponseTypeFromSystem () {
2530 // Default is console
2531 $responseType = 'console';
2533 // Is 'HTTP_HOST' set?
2534 if (isset($_SERVER['HTTP_HOST'])) {
2536 * Then it is a HTML response/request as RSS and so on may be
2537 * transfered over HTTP as well.
2539 $responseType = 'html';
2543 return $responseType;
2547 * Gets a cache key from Criteria instance
2549 * @param $criteriaInstance An instance of a Criteria class
2550 * @param $onlyKeys Only use these keys for a cache key
2551 * @return $cacheKey A cache key suitable for lookup/storage purposes
2553 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2555 $cacheKey = sprintf('%s@%s',
2556 $this->__toString(),
2557 $criteriaInstance->getCacheKey($onlyKeys)
2561 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2566 * Getter for startup time in miliseconds
2568 * @return $startupTime Startup time in miliseconds
2570 protected function getStartupTime () {
2571 return self::$startupTime;
2575 * "Getter" for a printable currently execution time in nice braces
2577 * @return $executionTime Current execution time in nice braces
2579 protected function getPrintableExecutionTime () {
2580 // Caculate the execution time
2581 $executionTime = microtime(TRUE) - $this->getStartupTime();
2583 // Pack it in nice braces
2584 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2587 return $executionTime;
2591 * Hashes a given string with a simple but stronger hash function (no salt)
2592 * and hex-encode it.
2594 * @param $str The string to be hashed
2595 * @return $hash The hash from string $str
2597 public static final function hash ($str) {
2598 // Hash given string with (better secure) hasher
2599 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2606 * "Getter" for length of hash() output. This will be "cached" to speed up
2609 * @return $length Length of hash() output
2611 public static final function getHashLength () {
2613 if (is_null(self::$hashLength)) {
2614 // No, then hash a string and save its length.
2615 self::$hashLength = strlen(self::hash('abc123'));
2619 return self::$hashLength;
2623 * Checks whether the given number is really a number (only chars 0-9).
2625 * @param $num A string consisting only chars between 0 and 9
2626 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2627 * @param $assertMismatch Whether to assert mismatches
2628 * @return $ret The (hopefully) secured numbered value
2630 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2631 // Filter all numbers out
2632 $ret = preg_replace('/[^0123456789]/', '', $num);
2635 if ($castValue === TRUE) {
2636 // Cast to biggest numeric type
2637 $ret = (double) $ret;
2640 // Assert only if requested
2641 if ($assertMismatch === TRUE) {
2642 // Has the whole value changed?
2643 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2651 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2653 * @param $num A string consisting only chars between 0 and 9
2654 * @param $assertMismatch Whether to assert mismatches
2655 * @return $ret The (hopefully) secured hext-numbered value
2657 public function hexval ($num, $assertMismatch = FALSE) {
2658 // Filter all numbers out
2659 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2661 // Assert only if requested
2662 if ($assertMismatch === TRUE) {
2663 // Has the whole value changed?
2664 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2672 * Checks whether start/end marker are set
2674 * @param $data Data to be checked
2675 * @return $isset Whether start/end marker are set
2677 public final function ifStartEndMarkersSet ($data) {
2679 $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));
2681 // ... and return it
2686 * Determines if an element is set in the generic array
2688 * @param $keyGroup Main group for the key
2689 * @param $subGroup Sub group for the key
2690 * @param $key Key to check
2691 * @param $element Element to check
2692 * @return $isset Whether the given key is set
2694 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2696 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2699 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2705 * Determines if a key is set in the generic array
2707 * @param $keyGroup Main group for the key
2708 * @param $subGroup Sub group for the key
2709 * @param $key Key to check
2710 * @return $isset Whether the given key is set
2712 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2714 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2717 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2725 * Determines if a group is set in the generic array
2727 * @param $keyGroup Main group
2728 * @param $subGroup Sub group
2729 * @return $isset Whether the given group is set
2731 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2733 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2736 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2743 * Getter for sub key group
2745 * @param $keyGroup Main key group
2746 * @param $subGroup Sub key group
2747 * @return $array An array with all array elements
2749 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2751 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2752 // No, then abort here
2753 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2758 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2761 return $this->genericArray[$keyGroup][$subGroup];
2765 * Unsets a given key in generic array
2767 * @param $keyGroup Main group for the key
2768 * @param $subGroup Sub group for the key
2769 * @param $key Key to unset
2772 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2774 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2777 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2781 * Unsets a given element in generic array
2783 * @param $keyGroup Main group for the key
2784 * @param $subGroup Sub group for the key
2785 * @param $key Key to unset
2786 * @param $element Element to unset
2789 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2791 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2794 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2798 * Append a string to a given generic array key
2800 * @param $keyGroup Main group for the key
2801 * @param $subGroup Sub group for the key
2802 * @param $key Key to unset
2803 * @param $value Value to add/append
2806 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2808 //* 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);
2810 // Is it already there?
2811 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2813 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2816 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2821 * Append a string to a given generic array element
2823 * @param $keyGroup Main group for the key
2824 * @param $subGroup Sub group for the key
2825 * @param $key Key to unset
2826 * @param $element Element to check
2827 * @param $value Value to add/append
2830 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2832 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, TRUE) . ',appendGlue=' . $appendGlue);
2834 // Is it already there?
2835 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2837 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2840 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2845 * Sets a string in a given generic array element
2847 * @param $keyGroup Main group for the key
2848 * @param $subGroup Sub group for the key
2849 * @param $key Key to unset
2850 * @param $element Element to check
2851 * @param $value Value to add/append
2854 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2856 //* 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);
2859 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2863 * Initializes given generic array group
2865 * @param $keyGroup Main group for the key
2866 * @param $subGroup Sub group for the key
2867 * @param $key Key to use
2868 * @param $forceInit Optionally force initialization
2871 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2873 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2875 // Is it already set?
2876 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2877 // Already initialized
2878 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2883 $this->genericArray[$keyGroup][$subGroup] = array();
2887 * Initializes given generic array key
2889 * @param $keyGroup Main group for the key
2890 * @param $subGroup Sub group for the key
2891 * @param $key Key to use
2892 * @param $forceInit Optionally force initialization
2895 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2897 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2899 // Is it already set?
2900 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2901 // Already initialized
2902 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2907 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2911 * Initializes given generic array element
2913 * @param $keyGroup Main group for the key
2914 * @param $subGroup Sub group for the key
2915 * @param $key Key to use
2916 * @param $element Element to use
2917 * @param $forceInit Optionally force initialization
2920 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2922 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2924 // Is it already set?
2925 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2926 // Already initialized
2927 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2932 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2936 * Pushes an element to a generic key
2938 * @param $keyGroup Main group for the key
2939 * @param $subGroup Sub group for the key
2940 * @param $key Key to use
2941 * @param $value Value to add/append
2942 * @return $count Number of array elements
2944 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2946 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2949 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2951 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2955 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2958 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2959 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2964 * Pushes an element to a generic array element
2966 * @param $keyGroup Main group for the key
2967 * @param $subGroup Sub group for the key
2968 * @param $key Key to use
2969 * @param $element Element to check
2970 * @param $value Value to add/append
2971 * @return $count Number of array elements
2973 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2975 //* 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));
2978 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2980 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2984 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2987 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2988 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2993 * Pops an element from a generic group
2995 * @param $keyGroup Main group for the key
2996 * @param $subGroup Sub group for the key
2997 * @param $key Key to unset
2998 * @return $value Last "popped" value
3000 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
3002 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3005 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3007 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3012 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
3015 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3016 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3021 * Shifts an element from a generic group
3023 * @param $keyGroup Main group for the key
3024 * @param $subGroup Sub group for the key
3025 * @param $key Key to unset
3026 * @return $value Last "popped" value
3028 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3030 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3033 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3035 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3040 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3043 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3044 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3049 * Count generic array group
3051 * @param $keyGroup Main group for the key
3052 * @return $count Count of given group
3054 protected final function countGenericArray ($keyGroup) {
3056 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3059 if (!isset($this->genericArray[$keyGroup])) {
3061 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3066 $count = count($this->genericArray[$keyGroup]);
3069 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3076 * Count generic array sub group
3078 * @param $keyGroup Main group for the key
3079 * @param $subGroup Sub group for the key
3080 * @return $count Count of given group
3082 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3084 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3087 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3089 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3094 $count = count($this->genericArray[$keyGroup][$subGroup]);
3097 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3104 * Count generic array elements
3106 * @param $keyGroup Main group for the key
3107 * @param $subGroup Sub group for the key
3108 * @para $key Key to count
3109 * @return $count Count of given key
3111 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3113 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3116 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3118 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3120 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3122 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3127 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3130 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3137 * Getter for whole generic group array
3139 * @param $keyGroup Key group to get
3140 * @return $array Whole generic array group
3142 protected final function getGenericArray ($keyGroup) {
3144 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3147 if (!isset($this->genericArray[$keyGroup])) {
3149 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3154 return $this->genericArray[$keyGroup];
3158 * Setter for generic array key
3160 * @param $keyGroup Key group to get
3161 * @param $subGroup Sub group for the key
3162 * @param $key Key to unset
3163 * @param $value Mixed value from generic array element
3166 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3168 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3171 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3175 * Getter for generic array key
3177 * @param $keyGroup Key group to get
3178 * @param $subGroup Sub group for the key
3179 * @param $key Key to unset
3180 * @return $value Mixed value from generic array element
3182 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3184 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3187 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3189 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3194 return $this->genericArray[$keyGroup][$subGroup][$key];
3198 * Sets a value in given generic array key/element
3200 * @param $keyGroup Main group for the key
3201 * @param $subGroup Sub group for the key
3202 * @param $key Key to set
3203 * @param $element Element to set
3204 * @param $value Value to set
3207 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3209 //* 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));
3212 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3216 * Getter for generic array element
3218 * @param $keyGroup Key group to get
3219 * @param $subGroup Sub group for the key
3220 * @param $key Key to look for
3221 * @param $element Element to look for
3222 * @return $value Mixed value from generic array element
3224 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3226 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3229 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3231 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3236 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3240 * Checks if a given sub group is valid (array)
3242 * @param $keyGroup Key group to get
3243 * @param $subGroup Sub group for the key
3244 * @return $isValid Whether given sub group is valid
3246 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3248 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3251 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3258 * Checks if a given key is valid (array)
3260 * @param $keyGroup Key group to get
3261 * @param $subGroup Sub group for the key
3262 * @param $key Key to check
3263 * @return $isValid Whether given sub group is valid
3265 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3267 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3270 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3277 * Initializes the web output instance
3281 protected function initWebOutputInstance () {
3282 // Get application instance
3283 $applicationInstance = Registry::getRegistry()->getInstance('app');
3285 // Is this a response instance?
3286 if ($this instanceof Responseable) {
3287 // Then set it in application instance
3288 $applicationInstance->setResponseInstance($this);
3291 // Init web output instance
3292 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3295 $this->setWebOutputInstance($outputInstance);
3299 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3301 * @param $boolean Boolean value
3302 * @return $translated Translated boolean value
3304 public static final function translateBooleanToYesNo ($boolean) {
3305 // Make sure it is really boolean
3306 assert(is_bool($boolean));
3309 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3311 // ... and return it
3316 * Encodes raw data (almost any type) by "serializing" it and then pack it
3317 * into a "binary format".
3319 * @param $rawData Raw data (almost any type)
3320 * @return $encoded Encoded data
3322 protected function encodeData ($rawData) {
3323 // Make sure no objects or resources pass through
3324 assert(!is_object($rawData));
3325 assert(!is_resource($rawData));
3327 // First "serialize" it (json_encode() is faster than serialize())
3328 $encoded = $this->packString(json_encode($rawData));
3335 * Pack a string into a "binary format". Please execuse me that this is
3336 * widely undocumented. :-(
3338 * @param $str Unpacked string
3339 * @return $packed Packed string
3340 * @todo Improve documentation
3342 protected function packString ($str) {
3344 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3346 // First compress the string (gzcompress is okay)
3347 $str = gzcompress($str);
3352 // And start the "encoding" loop
3353 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3355 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3356 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3358 if (($idx + $i) <= strlen($str)) {
3359 $ord = ord(substr($str, ($idx + $i), 1));
3361 $add = $ord * pow(256, $factor);
3365 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3369 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3370 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3372 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3373 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3379 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3384 * Checks whether the given file/path is in open_basedir(). This does not
3385 * gurantee that the file is actually readable and/or writeable. If you need
3386 * such gurantee then please use isReadableFile() instead.
3388 * @param $filePathName Name of the file/path to be checked
3389 * @return $isReachable Whether it is within open_basedir()
3391 protected static function isReachableFilePath ($filePathName) {
3392 // Is not reachable by default
3393 $isReachable = FALSE;
3395 // Get open_basedir parameter
3396 $openBaseDir = ini_get('open_basedir');
3399 if (!empty($openBaseDir)) {
3400 // Check all entries
3401 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3402 // Check on existence
3403 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3405 $isReachable = TRUE;
3409 // If open_basedir is not set, all is allowed
3410 $isReachable = TRUE;
3414 return $isReachable;
3418 * Checks whether the give file is within open_basedir() (done by
3419 * isReachableFilePath()), is actually a file and is readable.
3421 * @param $fileName Name of the file to be checked
3422 * @return $isReadable Whether the file is readable (and therefor exists)
3424 public static function isReadableFile ($fileName) {
3425 // Default is not readable
3426 $isReadable = FALSE;
3428 // Is within parameters, so check if it is a file and readable
3429 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3436 * Creates a full-qualified file name (FQFN) for given file name by adding
3437 * a configured temporary file path to it.
3439 * @param $fileName Name for temporary file
3440 * @return $fqfn Full-qualified file name
3441 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3442 * @throws FileIoException If the file cannot be written
3444 protected static function createTempPathForFile ($fileName) {
3446 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3448 // Is the path writeable?
3449 if (!is_writable($basePath)) {
3450 // Path is write-protected
3451 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3455 $fqfn = $basePath . '/' . $fileName;
3458 if (!self::isReachableFilePath($fqfn)) {
3460 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3468 * "Getter" for a printable state name
3470 * @return $stateName Name of the node's state in a printable format
3472 public final function getPrintableState () {
3473 // Default is 'null'
3474 $stateName = 'null';
3476 // Get the state instance
3477 $stateInstance = $this->getStateInstance();
3479 // Is it an instance of Stateable?
3480 if ($stateInstance instanceof Stateable) {
3481 // Then use that state name
3482 $stateName = $stateInstance->getStateName();
3490 * Handles socket error for given socket resource and peer data. This method
3491 * validates $socketResource if it is a valid resource (see is_resource())
3492 * but assumes valid data in array $recipientData, except that
3493 * count($recipientData) is always 2.
3495 * @param $method Value of __METHOD__ from calling method
3496 * @param $line Value of __LINE__ from calling method
3497 * @param $socketResource A valid socket resource
3498 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3500 * @throws InvalidSocketException If $socketResource is no socket resource
3501 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3502 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3504 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3505 // This method handles only socket resources
3506 if (!is_resource($socketResource)) {
3507 // No resource, abort here
3508 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3511 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3512 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3513 assert(isset($socketData[0]));
3514 assert(isset($socketData[1]));
3516 // Get error code for first validation (0 is not an error)
3517 $errorCode = socket_last_error($socketResource);
3519 // If the error code is zero, someone called this method without an error
3520 if ($errorCode == 0) {
3521 // No error detected (or previously cleared outside this method)
3522 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3525 // Get handler (method) name
3526 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3528 // Call-back the error handler method
3529 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3531 // Finally clear the error because it has been handled
3532 socket_clear_error($socketResource);