3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Compressor\Compressor;
7 use CoreFramework\Configuration\FrameworkConfiguration;
8 use CoreFramework\Connection\Database\DatabaseConnection;
9 use CoreFramework\Controller\Controller;
10 use CoreFramework\Criteria\Criteria;
11 use CoreFramework\Criteria\Local\LocalSearchCriteria;
12 use CoreFramework\Criteria\Local\LocalUpdateCriteria;
13 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
14 use CoreFramework\Factory\ObjectFactory;
15 use CoreFramework\Filesystem\Block;
16 use CoreFramework\Filesystem\FilePointer;
17 use CoreFramework\Filesystem\FrameworkDirectory;
18 use CoreFramework\Generic\FrameworkInterface;
19 use CoreFramework\Generic\NullPointerException;
20 use CoreFramework\Handler\Stream\IoHandler;
21 use CoreFramework\Lists\Listable;
22 use CoreFramework\Loader\ClassLoader;
23 use CoreFramework\Manager\ManageableApplication;
24 use CoreFramework\Middleware\Compressor\CompressorChannel;
25 use CoreFramework\Middleware\Debug\DebugMiddleware;
26 use CoreFramework\Parser\Parseable;
27 use CoreFramework\Registry\Register;
28 use CoreFramework\Registry\Registry;
29 use CoreFramework\Request\Requestable;
30 use CoreFramework\Resolver\Resolver;
31 use CoreFramework\Result\Database\CachedDatabaseResult;
32 use CoreFramework\Result\Search\SearchableResult;
33 use CoreFramework\Response\Responseable;
34 use CoreFramework\Stream\Output\OutputStreamer;
35 use CoreFramework\Template\CompileableTemplate;
36 use CoreFramework\User\ManageableAccount;
37 use CoreFramework\Wrapper\Database\DatabaseWrapper;
44 * The simulator system class is the super class of all other classes. This
45 * class handles saving of games etc.
47 * @author Roland Haeder <webmaster@shipsimu.org>
49 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
50 * @license GNU GPL 3.0 or any newer version
51 * @link http://www.shipsimu.org
53 * This program is free software: you can redistribute it and/or modify
54 * it under the terms of the GNU General Public License as published by
55 * the Free Software Foundation, either version 3 of the License, or
56 * (at your option) any later version.
58 * This program is distributed in the hope that it will be useful,
59 * but WITHOUT ANY WARRANTY; without even the implied warranty of
60 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
61 * GNU General Public License for more details.
63 * You should have received a copy of the GNU General Public License
64 * along with this program. If not, see <http://www.gnu.org/licenses/>.
66 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
68 * Length of output from hash()
70 private static $hashLength = NULL;
75 private $realClass = 'BaseFrameworkSystem';
78 * Instance of a Requestable class
80 private $requestInstance = NULL;
83 * Instance of a Responseable class
85 private $responseInstance = NULL;
88 * Search criteria instance
90 private $searchInstance = NULL;
93 * Update criteria instance
95 private $updateInstance = NULL;
98 * The file I/O instance for the template loader
100 private $fileIoInstance = NULL;
105 private $resolverInstance = NULL;
108 * Template engine instance
110 private $templateInstance = NULL;
113 * Database result instance
115 private $resultInstance = NULL;
118 * Instance for user class
120 private $userInstance = NULL;
123 * A controller instance
125 private $controllerInstance = NULL;
130 private $rngInstance = NULL;
133 * Instance of a crypto helper
135 private $cryptoInstance = NULL;
138 * Instance of an Iterator class
140 private $iteratorInstance = NULL;
143 * Instance of the list
145 private $listInstance = NULL;
150 private $menuInstance = NULL;
153 * Instance of the image
155 private $imageInstance = NULL;
158 * Instance of the stacker
160 private $stackInstance = NULL;
163 * A Compressor instance
165 private $compressorInstance = NULL;
168 * A Parseable instance
170 private $parserInstance = NULL;
173 * A HandleableProtocol instance
175 private $protocolInstance = NULL;
178 * A database wrapper instance
180 private $databaseInstance = NULL;
183 * A helper instance for the form
185 private $helperInstance = NULL;
188 * An instance of a Source class
190 private $sourceInstance = NULL;
193 * An instance of a UrlSource class
195 private $urlSourceInstance = NULL;
198 * An instance of a InputStream class
200 private $inputStreamInstance = NULL;
203 * An instance of a OutputStream class
205 private $outputStreamInstance = NULL;
208 * Networkable handler instance
210 private $handlerInstance = NULL;
213 * Visitor handler instance
215 private $visitorInstance = NULL;
220 private $dhtInstance = NULL;
223 * An instance of a database wrapper class
225 private $wrapperInstance = NULL;
228 * An instance of a file I/O pointer class (not handler)
230 private $pointerInstance = NULL;
233 * An instance of an Indexable class
235 private $indexInstance = NULL;
238 * An instance of a Block class
240 private $blockInstance = NULL;
245 private $minableInstance = NULL;
248 * A FrameworkDirectory instance
250 private $directoryInstance = NULL;
255 private $listenerInstance = NULL;
258 * An instance of a communicator
260 private $communicatorInstance = NULL;
263 * The concrete output instance
265 private $outputInstance = NULL;
270 private $stateInstance = NULL;
273 * Thousands separator
275 private $thousands = '.'; // German
280 private $decimals = ','; // German
285 private $socketResource = FALSE;
288 * Regular expression to use for validation
290 private $regularExpression = '';
295 private $packageData = array();
300 private $genericArray = array();
305 private $commandName = '';
310 private $controllerName = '';
313 * Name of used protocol
315 private $protocolName = 'invalid';
318 * Array with bitmasks and such for pack/unpack methods to support both
319 * 32-bit and 64-bit systems
321 private $packingData = array(
324 'left' => 0xffff0000,
325 'right' => 0x0000ffff,
331 'left' => 0xffffffff00000000,
332 'right' => 0x00000000ffffffff,
339 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
341 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
343 private $archArrayElement = FALSE;
345 /***********************
346 * Exception codes.... *
347 ***********************/
349 // @todo Try to clean these constants up
350 const EXCEPTION_IS_NULL_POINTER = 0x001;
351 const EXCEPTION_IS_NO_OBJECT = 0x002;
352 const EXCEPTION_IS_NO_ARRAY = 0x003;
353 const EXCEPTION_MISSING_METHOD = 0x004;
354 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
355 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
356 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
357 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
358 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
359 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
360 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
361 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
362 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
363 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
364 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
365 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
366 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
367 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
368 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
369 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
370 const EXCEPTION_PATH_NOT_FOUND = 0x015;
371 const EXCEPTION_INVALID_PATH_NAME = 0x016;
372 const EXCEPTION_READ_PROTECED_PATH = 0x017;
373 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
374 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
375 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
376 const EXCEPTION_INVALID_RESOURCE = 0x01b;
377 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
378 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
379 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
380 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
381 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
382 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
383 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
384 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
385 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
386 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
387 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
388 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
389 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
390 const EXCEPTION_INVALID_STRING = 0x029;
391 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
392 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
393 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
394 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
395 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
396 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
397 const EXCEPTION_MISSING_ELEMENT = 0x030;
398 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
399 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
400 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
401 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
402 const EXCEPTION_FATAL_ERROR = 0x035;
403 const EXCEPTION_FILE_NOT_FOUND = 0x036;
404 const EXCEPTION_ASSERTION_FAILED = 0x037;
405 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
406 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
407 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
408 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
409 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
410 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
413 * Hexadecimal->Decimal translation array
415 private static $hexdec = array(
435 * Decimal->hexadecimal translation array
437 private static $dechex = array(
457 * Startup time in miliseconds
459 private static $startupTime = 0;
462 * Protected super constructor
464 * @param $className Name of the class
467 protected function __construct ($className) {
469 $this->setRealClass($className);
471 // Set configuration instance if no registry ...
472 if (!$this instanceof Register) {
473 // ... because registries doesn't need to be configured
474 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
477 // Is the startup time set? (0 cannot be TRUE anymore)
478 if (self::$startupTime == 0) {
480 self::$startupTime = microtime(TRUE);
484 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
488 * Destructor for all classes. You should not call this method on your own.
492 public function __destruct () {
493 // Flush any updated entries to the database
494 $this->flushPendingUpdates();
496 // Is this object already destroyed?
497 if ($this->__toString() != 'DestructedObject') {
498 // Destroy all informations about this class but keep some text about it alive
499 $this->setRealClass('DestructedObject');
500 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
501 // Already destructed object
502 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
507 // Do not call this twice
508 trigger_error(__METHOD__ . ': Called twice.');
514 * The __call() method where all non-implemented methods end up
516 * @param $methodName Name of the missing method
517 * @args $args Arguments passed to the method
520 public final function __call ($methodName, $args) {
521 return self::__callStatic($methodName, $args);
525 * The __callStatic() method where all non-implemented static methods end up
527 * @param $methodName Name of the missing method
528 * @args $args Arguments passed to the method
531 public static final function __callStatic ($methodName, $args) {
533 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
535 // Init argument string
538 // Is it NULL, empty or an array?
539 if (is_null($args)) {
541 $argsString = 'NULL';
542 } elseif (is_array($args)) {
546 // Some arguments are there
547 foreach ($args as $arg) {
548 // Add data about the argument
549 $argsString .= gettype($arg) . ':';
552 // Found a NULL argument
553 $argsString .= 'NULL';
554 } elseif (is_string($arg)) {
555 // Add length for strings
556 $argsString .= strlen($arg);
557 } elseif ((is_int($arg)) || (is_float($arg))) {
560 } elseif (is_array($arg)) {
561 // .. or size if array
562 $argsString .= count($arg);
563 } elseif (is_object($arg)) {
565 $reflection = new ReflectionClass($arg);
567 // Is an other object, maybe no __toString() available
568 $argsString .= $reflection->getName();
569 } elseif ($arg === TRUE) {
570 // ... is boolean 'TRUE'
571 $argsString .= 'TRUE';
572 } elseif ($arg === FALSE) {
573 // ... is boolean 'FALSE'
574 $argsString .= 'FALSE';
577 // Comma for next one
582 if (substr($argsString, -2, 1) == ',') {
583 $argsString = substr($argsString, 0, -2);
589 // Invalid arguments!
590 $argsString = '!INVALID:' . gettype($args) . '!';
593 // Output stub message
594 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
595 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
605 * Getter for $realClass
607 * @return $realClass The name of the real class (not BaseFrameworkSystem)
609 public function __toString () {
610 return $this->realClass;
614 * Magic method to catch setting of missing but set class fields/attributes
616 * @param $name Name of the field/attribute
617 * @param $value Value to store
620 public final function __set ($name, $value) {
621 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
624 print_r($value, TRUE)
629 * Magic method to catch getting of missing fields/attributes
631 * @param $name Name of the field/attribute
634 public final function __get ($name) {
635 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
641 * Magic method to catch unsetting of missing fields/attributes
643 * @param $name Name of the field/attribute
646 public final function __unset ($name) {
647 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
653 * Magic method to catch object serialization
655 * @return $unsupported Unsupported method
656 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
658 public final function __sleep () {
659 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
663 * Magic method to catch object deserialization
665 * @return $unsupported Unsupported method
666 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
668 public final function __wakeup () {
669 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
673 * Magic method to catch calls when an object instance is called
675 * @return $unsupported Unsupported method
676 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
678 public final function __invoke () {
679 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
683 * Setter for the real class name
685 * @param $realClass Class name (string)
688 public final function setRealClass ($realClass) {
690 $this->realClass = (string) $realClass;
694 * Setter for database result instance
696 * @param $resultInstance An instance of a database result class
698 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
700 protected final function setResultInstance (SearchableResult $resultInstance) {
701 $this->resultInstance = $resultInstance;
705 * Getter for database result instance
707 * @return $resultInstance An instance of a database result class
709 public final function getResultInstance () {
710 return $this->resultInstance;
714 * Setter for template engine instances
716 * @param $templateInstance An instance of a template engine class
719 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
720 $this->templateInstance = $templateInstance;
724 * Getter for template engine instances
726 * @return $templateInstance An instance of a template engine class
728 protected final function getTemplateInstance () {
729 return $this->templateInstance;
733 * Setter for search instance
735 * @param $searchInstance Searchable criteria instance
738 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
739 $this->searchInstance = $searchInstance;
743 * Getter for search instance
745 * @return $searchInstance Searchable criteria instance
747 public final function getSearchInstance () {
748 return $this->searchInstance;
752 * Setter for update instance
754 * @param $updateInstance An instance of a LocalUpdateCriteria clase
757 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
758 $this->updateInstance = $updateInstance;
762 * Getter for update instance
764 * @return $updateInstance Updateable criteria instance
766 public final function getUpdateInstance () {
767 return $this->updateInstance;
771 * Setter for resolver instance
773 * @param $resolverInstance Instance of a command resolver class
776 public final function setResolverInstance (Resolver $resolverInstance) {
777 $this->resolverInstance = $resolverInstance;
781 * Getter for resolver instance
783 * @return $resolverInstance Instance of a command resolver class
785 public final function getResolverInstance () {
786 return $this->resolverInstance;
790 * Setter for language instance
792 * @param $configInstance The configuration instance which shall
793 * be FrameworkConfiguration
796 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
797 Registry::getRegistry()->addInstance('config', $configInstance);
801 * Getter for configuration instance
803 * @return $configInstance Configuration instance
805 public final function getConfigInstance () {
806 $configInstance = Registry::getRegistry()->getInstance('config');
807 return $configInstance;
811 * Setter for debug instance
813 * @param $debugInstance The instance for debug output class
816 public final function setDebugInstance (DebugMiddleware $debugInstance) {
817 Registry::getRegistry()->addInstance('debug', $debugInstance);
821 * Getter for debug instance
823 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
825 public final function getDebugInstance () {
826 // Get debug instance
827 $debugInstance = Registry::getRegistry()->getInstance('debug');
830 return $debugInstance;
834 * Setter for web output instance
836 * @param $webInstance The instance for web output class
839 public final function setWebOutputInstance (OutputStreamer $webInstance) {
840 Registry::getRegistry()->addInstance('web_output', $webInstance);
844 * Getter for web output instance
846 * @return $webOutputInstance - Instance to class WebOutput
848 public final function getWebOutputInstance () {
849 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
850 return $webOutputInstance;
854 * Setter for database instance
856 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
859 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
860 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
864 * Getter for database layer
866 * @return $databaseInstance The database layer instance
868 public final function getDatabaseInstance () {
870 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
873 return $databaseInstance;
877 * Setter for compressor channel
879 * @param $compressorInstance An instance of CompressorChannel
882 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
883 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
887 * Getter for compressor channel
889 * @return $compressorInstance The compressor channel
891 public final function getCompressorChannel () {
892 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
893 return $compressorInstance;
897 * Protected getter for a manageable application helper class
899 * @return $applicationInstance An instance of a manageable application helper class
901 protected final function getApplicationInstance () {
902 $applicationInstance = Registry::getRegistry()->getInstance('application');
903 return $applicationInstance;
907 * Setter for a manageable application helper class
909 * @param $applicationInstance An instance of a manageable application helper class
912 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
913 Registry::getRegistry()->addInstance('application', $applicationInstance);
917 * Setter for request instance
919 * @param $requestInstance An instance of a Requestable class
922 public final function setRequestInstance (Requestable $requestInstance) {
923 $this->requestInstance = $requestInstance;
927 * Getter for request instance
929 * @return $requestInstance An instance of a Requestable class
931 public final function getRequestInstance () {
932 return $this->requestInstance;
936 * Setter for response instance
938 * @param $responseInstance An instance of a Responseable class
941 public final function setResponseInstance (Responseable $responseInstance) {
942 $this->responseInstance = $responseInstance;
946 * Getter for response instance
948 * @return $responseInstance An instance of a Responseable class
950 public final function getResponseInstance () {
951 return $this->responseInstance;
955 * Private getter for language instance
957 * @return $langInstance An instance to the language sub-system
959 protected final function getLanguageInstance () {
960 $langInstance = Registry::getRegistry()->getInstance('language');
961 return $langInstance;
965 * Setter for language instance
967 * @param $langInstance An instance to the language sub-system
969 * @see LanguageSystem
971 public final function setLanguageInstance (ManageableLanguage $langInstance) {
972 Registry::getRegistry()->addInstance('language', $langInstance);
976 * Private getter for file IO instance
978 * @return $fileIoInstance An instance to the file I/O sub-system
980 protected final function getFileIoInstance () {
981 return $this->fileIoInstance;
985 * Setter for file I/O instance
987 * @param $fileIoInstance An instance to the file I/O sub-system
990 public final function setFileIoInstance (IoHandler $fileIoInstance) {
991 $this->fileIoInstance = $fileIoInstance;
995 * Protected setter for user instance
997 * @param $userInstance An instance of a user class
1000 protected final function setUserInstance (ManageableAccount $userInstance) {
1001 $this->userInstance = $userInstance;
1005 * Getter for user instance
1007 * @return $userInstance An instance of a user class
1009 public final function getUserInstance () {
1010 return $this->userInstance;
1014 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1016 * @param $controllerInstance An instance of the controller
1019 public final function setControllerInstance (Controller $controllerInstance) {
1020 $this->controllerInstance = $controllerInstance;
1024 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1026 * @return $controllerInstance An instance of the controller
1028 public final function getControllerInstance () {
1029 return $this->controllerInstance;
1033 * Setter for RNG instance
1035 * @param $rngInstance An instance of a random number generator (RNG)
1038 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1039 $this->rngInstance = $rngInstance;
1043 * Getter for RNG instance
1045 * @return $rngInstance An instance of a random number generator (RNG)
1047 public final function getRngInstance () {
1048 return $this->rngInstance;
1052 * Setter for Cryptable instance
1054 * @param $cryptoInstance An instance of a Cryptable class
1057 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1058 $this->cryptoInstance = $cryptoInstance;
1062 * Getter for Cryptable instance
1064 * @return $cryptoInstance An instance of a Cryptable class
1066 public final function getCryptoInstance () {
1067 return $this->cryptoInstance;
1071 * Setter for the list instance
1073 * @param $listInstance A list of Listable
1076 protected final function setListInstance (Listable $listInstance) {
1077 $this->listInstance = $listInstance;
1081 * Getter for the list instance
1083 * @return $listInstance A list of Listable
1085 protected final function getListInstance () {
1086 return $this->listInstance;
1090 * Setter for the menu instance
1092 * @param $menuInstance A RenderableMenu instance
1095 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1096 $this->menuInstance = $menuInstance;
1100 * Getter for the menu instance
1102 * @return $menuInstance A RenderableMenu instance
1104 protected final function getMenuInstance () {
1105 return $this->menuInstance;
1109 * Setter for image instance
1111 * @param $imageInstance An instance of an image
1114 public final function setImageInstance (BaseImage $imageInstance) {
1115 $this->imageInstance = $imageInstance;
1119 * Getter for image instance
1121 * @return $imageInstance An instance of an image
1123 public final function getImageInstance () {
1124 return $this->imageInstance;
1128 * Setter for stacker instance
1130 * @param $stackInstance An instance of an stacker
1133 public final function setStackInstance (Stackable $stackInstance) {
1134 $this->stackInstance = $stackInstance;
1138 * Getter for stacker instance
1140 * @return $stackInstance An instance of an stacker
1142 public final function getStackInstance () {
1143 return $this->stackInstance;
1147 * Setter for compressor instance
1149 * @param $compressorInstance An instance of an compressor
1152 public final function setCompressorInstance (Compressor $compressorInstance) {
1153 $this->compressorInstance = $compressorInstance;
1157 * Getter for compressor instance
1159 * @return $compressorInstance An instance of an compressor
1161 public final function getCompressorInstance () {
1162 return $this->compressorInstance;
1166 * Setter for Parseable instance
1168 * @param $parserInstance An instance of an Parseable
1171 public final function setParserInstance (Parseable $parserInstance) {
1172 $this->parserInstance = $parserInstance;
1176 * Getter for Parseable instance
1178 * @return $parserInstance An instance of an Parseable
1180 public final function getParserInstance () {
1181 return $this->parserInstance;
1185 * Setter for HandleableProtocol instance
1187 * @param $protocolInstance An instance of an HandleableProtocol
1190 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1191 $this->protocolInstance = $protocolInstance;
1195 * Getter for HandleableProtocol instance
1197 * @return $protocolInstance An instance of an HandleableProtocol
1199 public final function getProtocolInstance () {
1200 return $this->protocolInstance;
1204 * Setter for DatabaseWrapper instance
1206 * @param $wrapperInstance An instance of an DatabaseWrapper
1209 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1210 $this->wrapperInstance = $wrapperInstance;
1214 * Getter for DatabaseWrapper instance
1216 * @return $wrapperInstance An instance of an DatabaseWrapper
1218 public final function getWrapperInstance () {
1219 return $this->wrapperInstance;
1223 * Setter for socket resource
1225 * @param $socketResource A valid socket resource
1228 public final function setSocketResource ($socketResource) {
1229 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1230 $this->socketResource = $socketResource;
1234 * Getter for socket resource
1236 * @return $socketResource A valid socket resource
1238 public final function getSocketResource () {
1239 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1240 return $this->socketResource;
1244 * Setter for regular expression
1246 * @param $regularExpression A valid regular expression
1249 public final function setRegularExpression ($regularExpression) {
1250 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1251 $this->regularExpression = $regularExpression;
1255 * Getter for regular expression
1257 * @return $regularExpression A valid regular expression
1259 public final function getRegularExpression () {
1260 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1261 return $this->regularExpression;
1265 * Setter for helper instance
1267 * @param $helperInstance An instance of a helper class
1270 protected final function setHelperInstance (Helper $helperInstance) {
1271 $this->helperInstance = $helperInstance;
1275 * Getter for helper instance
1277 * @return $helperInstance An instance of a helper class
1279 public final function getHelperInstance () {
1280 return $this->helperInstance;
1284 * Setter for a Source instance
1286 * @param $sourceInstance An instance of a Source class
1289 protected final function setSourceInstance (Source $sourceInstance) {
1290 $this->sourceInstance = $sourceInstance;
1294 * Getter for a Source instance
1296 * @return $sourceInstance An instance of a Source class
1298 protected final function getSourceInstance () {
1299 return $this->sourceInstance;
1303 * Setter for a UrlSource instance
1305 * @param $sourceInstance An instance of a UrlSource class
1308 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1309 $this->urlSourceInstance = $urlSourceInstance;
1313 * Getter for a UrlSource instance
1315 * @return $urlSourceInstance An instance of a UrlSource class
1317 protected final function getUrlSourceInstance () {
1318 return $this->urlSourceInstance;
1322 * Getter for a InputStream instance
1324 * @param $inputStreamInstance The InputStream instance
1326 protected final function getInputStreamInstance () {
1327 return $this->inputStreamInstance;
1331 * Setter for a InputStream instance
1333 * @param $inputStreamInstance The InputStream instance
1336 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1337 $this->inputStreamInstance = $inputStreamInstance;
1341 * Getter for a OutputStream instance
1343 * @param $outputStreamInstance The OutputStream instance
1345 protected final function getOutputStreamInstance () {
1346 return $this->outputStreamInstance;
1350 * Setter for a OutputStream instance
1352 * @param $outputStreamInstance The OutputStream instance
1355 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1356 $this->outputStreamInstance = $outputStreamInstance;
1360 * Setter for handler instance
1362 * @param $handlerInstance An instance of a Handleable class
1365 protected final function setHandlerInstance (Handleable $handlerInstance) {
1366 $this->handlerInstance = $handlerInstance;
1370 * Getter for handler instance
1372 * @return $handlerInstance A Networkable instance
1374 protected final function getHandlerInstance () {
1375 return $this->handlerInstance;
1379 * Setter for visitor instance
1381 * @param $visitorInstance A Visitor instance
1384 protected final function setVisitorInstance (Visitor $visitorInstance) {
1385 $this->visitorInstance = $visitorInstance;
1389 * Getter for visitor instance
1391 * @return $visitorInstance A Visitor instance
1393 protected final function getVisitorInstance () {
1394 return $this->visitorInstance;
1398 * Setter for DHT instance
1400 * @param $dhtInstance A Distributable instance
1403 protected final function setDhtInstance (Distributable $dhtInstance) {
1404 $this->dhtInstance = $dhtInstance;
1408 * Getter for DHT instance
1410 * @return $dhtInstance A Distributable instance
1412 protected final function getDhtInstance () {
1413 return $this->dhtInstance;
1417 * Setter for raw package Data
1419 * @param $packageData Raw package Data
1422 public final function setPackageData (array $packageData) {
1423 $this->packageData = $packageData;
1427 * Getter for raw package Data
1429 * @return $packageData Raw package Data
1431 public function getPackageData () {
1432 return $this->packageData;
1437 * Setter for Iterator instance
1439 * @param $iteratorInstance An instance of an Iterator
1442 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1443 $this->iteratorInstance = $iteratorInstance;
1447 * Getter for Iterator instance
1449 * @return $iteratorInstance An instance of an Iterator
1451 public final function getIteratorInstance () {
1452 return $this->iteratorInstance;
1456 * Setter for FilePointer instance
1458 * @param $pointerInstance An instance of an FilePointer class
1461 protected final function setPointerInstance (FilePointer $pointerInstance) {
1462 $this->pointerInstance = $pointerInstance;
1466 * Getter for FilePointer instance
1468 * @return $pointerInstance An instance of an FilePointer class
1470 public final function getPointerInstance () {
1471 return $this->pointerInstance;
1475 * Unsets pointer instance which triggers a call of __destruct() if the
1476 * instance is still there. This is surely not fatal on already "closed"
1477 * file pointer instances.
1479 * I don't want to mess around with above setter by giving it a default
1480 * value NULL as setter should always explicitly only set (existing) object
1481 * instances and NULL is NULL.
1485 protected final function unsetPointerInstance () {
1486 // Simply it to NULL
1487 $this->pointerInstance = NULL;
1491 * Setter for Indexable instance
1493 * @param $indexInstance An instance of an Indexable class
1496 protected final function setIndexInstance (Indexable $indexInstance) {
1497 $this->indexInstance = $indexInstance;
1501 * Getter for Indexable instance
1503 * @return $indexInstance An instance of an Indexable class
1505 public final function getIndexInstance () {
1506 return $this->indexInstance;
1510 * Setter for Block instance
1512 * @param $blockInstance An instance of an Block class
1515 protected final function setBlockInstance (Block $blockInstance) {
1516 $this->blockInstance = $blockInstance;
1520 * Getter for Block instance
1522 * @return $blockInstance An instance of an Block class
1524 public final function getBlockInstance () {
1525 return $this->blockInstance;
1529 * Setter for Minable instance
1531 * @param $minableInstance A Minable instance
1534 protected final function setMinableInstance (Minable $minableInstance) {
1535 $this->minableInstance = $minableInstance;
1539 * Getter for minable instance
1541 * @return $minableInstance A Minable instance
1543 protected final function getMinableInstance () {
1544 return $this->minableInstance;
1548 * Setter for FrameworkDirectory instance
1550 * @param $directoryInstance A FrameworkDirectory instance
1553 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1554 $this->directoryInstance = $directoryInstance;
1558 * Getter for FrameworkDirectory instance
1560 * @return $directoryInstance A FrameworkDirectory instance
1562 protected final function getDirectoryInstance () {
1563 return $this->directoryInstance;
1567 * Setter for listener instance
1569 * @param $listenerInstance A Listenable instance
1572 protected final function setListenerInstance (Listenable $listenerInstance) {
1573 $this->listenerInstance = $listenerInstance;
1577 * Getter for listener instance
1579 * @return $listenerInstance A Listenable instance
1581 protected final function getListenerInstance () {
1582 return $this->listenerInstance;
1586 * Getter for communicator instance
1588 * @return $communicatorInstance An instance of a Communicator class
1590 public final function getCommunicatorInstance () {
1591 return $this->communicatorInstance;
1595 * Setter for communicator instance
1597 * @param $communicatorInstance An instance of a Communicator class
1600 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1601 $this->communicatorInstance = $communicatorInstance;
1605 * Setter for state instance
1607 * @param $stateInstance A Stateable instance
1610 public final function setStateInstance (Stateable $stateInstance) {
1611 $this->stateInstance = $stateInstance;
1615 * Getter for state instance
1617 * @return $stateInstance A Stateable instance
1619 public final function getStateInstance () {
1620 return $this->stateInstance;
1624 * Setter for output instance
1626 * @param $outputInstance The debug output instance
1629 public final function setOutputInstance (OutputStreamer $outputInstance) {
1630 $this->outputInstance = $outputInstance;
1634 * Getter for output instance
1636 * @return $outputInstance The debug output instance
1638 public final function getOutputInstance () {
1639 return $this->outputInstance;
1643 * Setter for command name
1645 * @param $commandName Last validated command name
1648 protected final function setCommandName ($commandName) {
1649 $this->commandName = $commandName;
1653 * Getter for command name
1655 * @return $commandName Last validated command name
1657 protected final function getCommandName () {
1658 return $this->commandName;
1662 * Setter for controller name
1664 * @param $controllerName Last validated controller name
1667 protected final function setControllerName ($controllerName) {
1668 $this->controllerName = $controllerName;
1672 * Getter for controller name
1674 * @return $controllerName Last validated controller name
1676 protected final function getControllerName () {
1677 return $this->controllerName;
1681 * Getter for protocol name
1683 * @return $protocolName Name of used protocol
1685 public final function getProtocolName () {
1686 return $this->protocolName;
1690 * Setter for protocol name
1692 * @param $protocolName Name of used protocol
1695 protected final function setProtocolName ($protocolName) {
1696 $this->protocolName = $protocolName;
1700 * Checks whether an object equals this object. You should overwrite this
1701 * method to implement own equality checks
1703 * @param $objectInstance An instance of a FrameworkInterface object
1704 * @return $equals Whether both objects equals
1706 public function equals (FrameworkInterface $objectInstance) {
1709 $this->__toString() == $objectInstance->__toString()
1711 $this->hashCode() == $objectInstance->hashCode()
1714 // Return the result
1719 * Generates a generic hash code of this class. You should really overwrite
1720 * this method with your own hash code generator code. But keep KISS in mind.
1722 * @return $hashCode A generic hash code respresenting this whole class
1724 public function hashCode () {
1726 return crc32($this->__toString());
1730 * Formats computer generated price values into human-understandable formats
1731 * with thousand and decimal separators.
1733 * @param $value The in computer format value for a price
1734 * @param $currency The currency symbol (use HTML-valid characters!)
1735 * @param $decNum Number of decimals after commata
1736 * @return $price The for the current language formated price string
1737 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1738 * thousands separator
1741 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1742 // Are all required attriutes set?
1743 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1744 // Throw an exception
1745 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1749 $value = (float) $value;
1751 // Reformat the US number
1752 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1754 // Return as string...
1759 * Appends a trailing slash to a string
1761 * @param $str A string (maybe) without trailing slash
1762 * @return $str A string with an auto-appended trailing slash
1764 public final function addMissingTrailingSlash ($str) {
1765 // Is there a trailing slash?
1766 if (substr($str, -1, 1) != '/') {
1770 // Return string with trailing slash
1775 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1776 * application helper instance (ApplicationHelper by default).
1778 * @param $applicationInstance An application helper instance or
1779 * null if we shall use the default
1780 * @return $templateInstance The template engine instance
1781 * @throws NullPointerException If the discovered application
1782 * instance is still null
1784 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1785 // Is the application instance set?
1786 if (is_null($applicationInstance)) {
1787 // Get the current instance
1788 $applicationInstance = $this->getApplicationInstance();
1791 if (is_null($applicationInstance)) {
1792 // Thrown an exception
1793 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1797 // Initialize the template engine
1798 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1800 // Return the prepared instance
1801 return $templateInstance;
1805 * Debugs this instance by putting out it's full content
1807 * @param $message Optional message to show in debug output
1810 public final function debugInstance ($message = '') {
1811 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1812 restore_error_handler();
1817 // Is a message set?
1818 if (!empty($message)) {
1819 // Construct message
1820 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1823 // Generate the output
1824 $content .= sprintf('<pre>%s</pre>',
1827 print_r($this, TRUE)
1833 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>',
1834 $this->__toString(),
1836 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1841 * Replaces control characters with printable output
1843 * @param $str String with control characters
1844 * @return $str Replaced string
1846 protected function replaceControlCharacters ($str) {
1849 chr(13), '[r]', str_replace(
1850 chr(10), '[n]', str_replace(
1860 * Output a partial stub message for the caller method
1862 * @param $message An optional message to display
1865 protected function partialStub ($message = '') {
1866 // Get the backtrace
1867 $backtrace = debug_backtrace();
1869 // Generate the class::method string
1870 $methodName = 'UnknownClass->unknownMethod';
1871 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1872 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1875 // Construct the full message
1876 $stubMessage = sprintf('[%s:] Partial stub!',
1880 // Is the extra message given?
1881 if (!empty($message)) {
1882 // Then add it as well
1883 $stubMessage .= ' Message: ' . $message;
1886 // Debug instance is there?
1887 if (!is_null($this->getDebugInstance())) {
1888 // Output stub message
1889 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1892 trigger_error($stubMessage);
1898 * Outputs a debug backtrace and stops further script execution
1900 * @param $message An optional message to output
1901 * @param $doExit Whether exit the program (TRUE is default)
1904 public function debugBackTrace ($message = '', $doExit = TRUE) {
1905 // Sorry, there is no other way getting this nice backtrace
1906 if (!empty($message)) {
1908 printf('Message: %s<br />' . PHP_EOL, $message);
1912 debug_print_backtrace();
1916 if ($doExit === TRUE) {
1922 * Creates an instance of a debugger instance
1924 * @param $className Name of the class (currently unsupported)
1925 * @param $lineNumber Line number where the call was made
1926 * @return $debugInstance An instance of a debugger class
1927 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1929 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1930 // Is the instance set?
1931 if (!Registry::getRegistry()->instanceExists('debug')) {
1932 // Init debug instance
1933 $debugInstance = NULL;
1937 // Get a debugger instance
1938 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1939 } catch (NullPointerException $e) {
1940 // Didn't work, no instance there
1941 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1944 // Empty string should be ignored and used for testing the middleware
1945 DebugMiddleware::getSelfInstance()->output('');
1947 // Set it in its own class. This will set it in the registry
1948 $debugInstance->setDebugInstance($debugInstance);
1950 // Get instance from registry
1951 $debugInstance = Registry::getRegistry()->getDebugInstance();
1955 return $debugInstance;
1959 * Simple output of a message with line-break
1961 * @param $message Message to output
1964 public function outputLine ($message) {
1966 print($message . PHP_EOL);
1970 * Outputs a debug message whether to debug instance (should be set!) or
1971 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1972 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1974 * @param $message Message we shall send out...
1975 * @param $doPrint Whether print or die here (default: print)
1976 * @paran $stripTags Whether to strip tags (default: FALSE)
1979 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1980 // Set debug instance to NULL
1981 $debugInstance = NULL;
1985 // Get debug instance
1986 $debugInstance = $this->getDebugInstance();
1987 } catch (NullPointerException $e) {
1988 // The debug instance is not set (yet)
1991 // Is the debug instance there?
1992 if (is_object($debugInstance)) {
1993 // Use debug output handler
1994 $debugInstance->output($message, $stripTags);
1996 if ($doPrint === FALSE) {
1997 // Die here if not printed
2001 // Are debug times enabled?
2002 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
2004 $message = $this->getPrintableExecutionTime() . $message;
2008 if ($doPrint === TRUE) {
2010 $this->outputLine($message);
2019 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2021 * @param $str The string, what ever it is needs to be converted
2022 * @return $className Generated class name
2024 public static final function convertToClassName ($str) {
2028 // Convert all dashes in underscores
2029 $str = self::convertDashesToUnderscores($str);
2031 // Now use that underscores to get classname parts for hungarian style
2032 foreach (explode('_', $str) as $strPart) {
2033 // Make the class name part lower case and first upper case
2034 $className .= ucfirst(strtolower($strPart));
2037 // Return class name
2042 * Converts dashes to underscores, e.g. useable for configuration entries
2044 * @param $str The string with maybe dashes inside
2045 * @return $str The converted string with no dashed, but underscores
2047 public static final function convertDashesToUnderscores ($str) {
2049 $str = str_replace('-', '_', $str);
2051 // Return converted string
2056 * Marks up the code by adding e.g. line numbers
2058 * @param $phpCode Unmarked PHP code
2059 * @return $markedCode Marked PHP code
2061 public function markupCode ($phpCode) {
2066 $errorArray = error_get_last();
2068 // Init the code with error message
2069 if (is_array($errorArray)) {
2071 $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>',
2072 basename($errorArray['file']),
2073 $errorArray['line'],
2074 $errorArray['message'],
2079 // Add line number to the code
2080 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2082 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2084 htmlentities($code, ENT_QUOTES)
2093 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2094 * beatiful for web-based front-ends. If null is given a message id
2095 * null_timestamp will be resolved and returned.
2097 * @param $timestamp Timestamp to prepare (filter) for display
2098 * @return $readable A readable timestamp
2100 public function doFilterFormatTimestamp ($timestamp) {
2101 // Default value to return
2104 // Is the timestamp null?
2105 if (is_null($timestamp)) {
2106 // Get a message string
2107 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2109 switch ($this->getLanguageInstance()->getLanguageCode()) {
2110 case 'de': // German format is a bit different to default
2111 // Split the GMT stamp up
2112 $dateTime = explode(' ', $timestamp );
2113 $dateArray = explode('-', $dateTime[0]);
2114 $timeArray = explode(':', $dateTime[1]);
2116 // Construct the timestamp
2117 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2127 default: // Default is pass-through
2128 $readable = $timestamp;
2138 * Filter a given number into a localized number
2140 * @param $value The raw value from e.g. database
2141 * @return $localized Localized value
2143 public function doFilterFormatNumber ($value) {
2144 // Generate it from config and localize dependencies
2145 switch ($this->getLanguageInstance()->getLanguageCode()) {
2146 case 'de': // German format is a bit different to default
2147 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2150 default: // US, etc.
2151 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2160 * "Getter" for databse entry
2162 * @return $entry An array with database entries
2163 * @throws NullPointerException If the database result is not found
2164 * @throws InvalidDatabaseResultException If the database result is invalid
2166 protected final function getDatabaseEntry () {
2167 // Is there an instance?
2168 if (!$this->getResultInstance() instanceof SearchableResult) {
2169 // Throw an exception here
2170 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2174 $this->getResultInstance()->rewind();
2176 // Do we have an entry?
2177 if ($this->getResultInstance()->valid() === FALSE) {
2178 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2179 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2183 $this->getResultInstance()->next();
2186 $entry = $this->getResultInstance()->current();
2193 * Getter for field name
2195 * @param $fieldName Field name which we shall get
2196 * @return $fieldValue Field value from the user
2197 * @throws NullPointerException If the result instance is null
2199 public final function getField ($fieldName) {
2200 // Default field value
2203 // Get result instance
2204 $resultInstance = $this->getResultInstance();
2206 // Is this instance null?
2207 if (is_null($resultInstance)) {
2208 // Then the user instance is no longer valid (expired cookies?)
2209 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2212 // Get current array
2213 $fieldArray = $resultInstance->current();
2214 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2216 // Convert dashes to underscore
2217 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2219 // Does the field exist?
2220 if ($this->isFieldSet($fieldName)) {
2222 $fieldValue = $fieldArray[$fieldName2];
2223 } elseif (defined('DEVELOPER')) {
2224 // Missing field entry, may require debugging
2225 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2227 // Missing field entry, may require debugging
2228 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2236 * Checks if given field is set
2238 * @param $fieldName Field name to check
2239 * @return $isSet Whether the given field name is set
2240 * @throws NullPointerException If the result instance is null
2242 public function isFieldSet ($fieldName) {
2243 // Get result instance
2244 $resultInstance = $this->getResultInstance();
2246 // Is this instance null?
2247 if (is_null($resultInstance)) {
2248 // Then the user instance is no longer valid (expired cookies?)
2249 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2252 // Get current array
2253 $fieldArray = $resultInstance->current();
2254 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2256 // Convert dashes to underscore
2257 $fieldName = self::convertDashesToUnderscores($fieldName);
2260 $isSet = isset($fieldArray[$fieldName]);
2267 * Flushs all pending updates to the database layer
2271 public function flushPendingUpdates () {
2272 // Get result instance
2273 $resultInstance = $this->getResultInstance();
2275 // Do we have data to update?
2276 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2277 // Get wrapper class name config entry
2278 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2280 // Create object instance
2281 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2283 // Yes, then send the whole result to the database layer
2284 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2289 * Outputs a deprecation warning to the developer.
2291 * @param $message The message we shall output to the developer
2293 * @todo Write a logging mechanism for productive mode
2295 public function deprecationWarning ($message) {
2296 // Is developer mode active?
2297 if (defined('DEVELOPER')) {
2298 // Debug instance is there?
2299 if (!is_null($this->getDebugInstance())) {
2300 // Output stub message
2301 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2304 trigger_error($message . "<br />\n");
2308 // @TODO Finish this part!
2309 $this->partialStub('Developer mode inactive. Message:' . $message);
2314 * Checks whether the given PHP extension is loaded
2316 * @param $phpExtension The PHP extension we shall check
2317 * @return $isLoaded Whether the PHP extension is loaded
2319 public final function isPhpExtensionLoaded ($phpExtension) {
2321 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2328 * "Getter" as a time() replacement but with milliseconds. You should use this
2329 * method instead of the encapsulated getimeofday() function.
2331 * @return $milliTime Timestamp with milliseconds
2333 public function getMilliTime () {
2334 // Get the time of day as float
2335 $milliTime = gettimeofday(TRUE);
2342 * Idles (sleeps) for given milliseconds
2344 * @return $hasSlept Whether it goes fine
2346 public function idle ($milliSeconds) {
2347 // Sleep is fine by default
2350 // Idle so long with found function
2351 if (function_exists('time_sleep_until')) {
2352 // Get current time and add idle time
2353 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2355 // New PHP 5.1.0 function found, ignore errors
2356 $hasSlept = @time_sleep_until($sleepUntil);
2359 * My Sun station doesn't have that function even with latest PHP
2362 usleep($milliSeconds * 1000);
2369 * Converts a hexadecimal string, even with negative sign as first string to
2370 * a decimal number using BC functions.
2372 * This work is based on comment #86673 on php.net documentation page at:
2373 * <http://de.php.net/manual/en/function.dechex.php#86673>
2375 * @param $hex Hexadecimal string
2376 * @return $dec Decimal number
2378 protected function hex2dec ($hex) {
2379 // Convert to all lower-case
2380 $hex = strtolower($hex);
2382 // Detect sign (negative/positive numbers)
2384 if (substr($hex, 0, 1) == '-') {
2386 $hex = substr($hex, 1);
2389 // Decode the hexadecimal string into a decimal number
2391 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2392 $factor = self::$hexdec[substr($hex, $i, 1)];
2393 $dec = bcadd($dec, bcmul($factor, $e));
2396 // Return the decimal number
2397 return $sign . $dec;
2401 * Converts even very large decimal numbers, also signed, to a hexadecimal
2404 * This work is based on comment #97756 on php.net documentation page at:
2405 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2407 * @param $dec Decimal number, even with negative sign
2408 * @param $maxLength Optional maximum length of the string
2409 * @return $hex Hexadecimal string
2411 protected function dec2hex ($dec, $maxLength = 0) {
2412 // maxLength can be zero or devideable by 2
2413 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2415 // Detect sign (negative/positive numbers)
2422 // Encode the decimal number into a hexadecimal string
2425 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2427 } while ($dec >= 1);
2430 * Leading zeros are required for hex-decimal "numbers". In some
2431 * situations more leading zeros are wanted, so check for both
2434 if ($maxLength > 0) {
2435 // Prepend more zeros
2436 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2437 } elseif ((strlen($hex) % 2) != 0) {
2438 // Only make string's length dividable by 2
2442 // Return the hexadecimal string
2443 return $sign . $hex;
2447 * Converts a ASCII string (0 to 255) into a decimal number.
2449 * @param $asc The ASCII string to be converted
2450 * @return $dec Decimal number
2452 protected function asc2dec ($asc) {
2453 // Convert it into a hexadecimal number
2454 $hex = bin2hex($asc);
2456 // And back into a decimal number
2457 $dec = $this->hex2dec($hex);
2464 * Converts a decimal number into an ASCII string.
2466 * @param $dec Decimal number
2467 * @return $asc An ASCII string
2469 protected function dec2asc ($dec) {
2470 // First convert the number into a hexadecimal string
2471 $hex = $this->dec2hex($dec);
2473 // Then convert it into the ASCII string
2474 $asc = $this->hex2asc($hex);
2481 * Converts a hexadecimal number into an ASCII string. Negative numbers
2484 * @param $hex Hexadecimal string
2485 * @return $asc An ASCII string
2487 protected function hex2asc ($hex) {
2488 // Check for length, it must be devideable by 2
2489 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2490 assert((strlen($hex) % 2) == 0);
2494 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2495 // Get the decimal number of the chunk
2496 $part = hexdec(substr($hex, $idx, 2));
2498 // Add it to the final string
2502 // Return the final string
2507 * Checks whether the given encoded data was encoded with Base64
2509 * @param $encodedData Encoded data we shall check
2510 * @return $isBase64 Whether the encoded data is Base64
2512 protected function isBase64Encoded ($encodedData) {
2514 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2521 * "Getter" to get response/request type from analysis of the system.
2523 * @return $responseType Analyzed response type
2525 protected static function getResponseTypeFromSystem () {
2526 // Default is console
2527 $responseType = 'console';
2529 // Is 'HTTP_HOST' set?
2530 if (isset($_SERVER['HTTP_HOST'])) {
2532 * Then it is a HTML response/request as RSS and so on may be
2533 * transfered over HTTP as well.
2535 $responseType = 'html';
2539 return $responseType;
2543 * Gets a cache key from Criteria instance
2545 * @param $criteriaInstance An instance of a Criteria class
2546 * @param $onlyKeys Only use these keys for a cache key
2547 * @return $cacheKey A cache key suitable for lookup/storage purposes
2549 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2551 $cacheKey = sprintf('%s@%s',
2552 $this->__toString(),
2553 $criteriaInstance->getCacheKey($onlyKeys)
2557 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2562 * Getter for startup time in miliseconds
2564 * @return $startupTime Startup time in miliseconds
2566 protected function getStartupTime () {
2567 return self::$startupTime;
2571 * "Getter" for a printable currently execution time in nice braces
2573 * @return $executionTime Current execution time in nice braces
2575 protected function getPrintableExecutionTime () {
2576 // Caculate the execution time
2577 $executionTime = microtime(TRUE) - $this->getStartupTime();
2579 // Pack it in nice braces
2580 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2583 return $executionTime;
2587 * Hashes a given string with a simple but stronger hash function (no salt)
2588 * and hex-encode it.
2590 * @param $str The string to be hashed
2591 * @return $hash The hash from string $str
2593 public static final function hash ($str) {
2594 // Hash given string with (better secure) hasher
2595 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2602 * "Getter" for length of hash() output. This will be "cached" to speed up
2605 * @return $length Length of hash() output
2607 public static final function getHashLength () {
2609 if (is_null(self::$hashLength)) {
2610 // No, then hash a string and save its length.
2611 self::$hashLength = strlen(self::hash('abc123'));
2615 return self::$hashLength;
2619 * Checks whether the given number is really a number (only chars 0-9).
2621 * @param $num A string consisting only chars between 0 and 9
2622 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2623 * @param $assertMismatch Whether to assert mismatches
2624 * @return $ret The (hopefully) secured numbered value
2626 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2627 // Filter all numbers out
2628 $ret = preg_replace('/[^0123456789]/', '', $num);
2631 if ($castValue === TRUE) {
2632 // Cast to biggest numeric type
2633 $ret = (double) $ret;
2636 // Assert only if requested
2637 if ($assertMismatch === TRUE) {
2638 // Has the whole value changed?
2639 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2647 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2649 * @param $num A string consisting only chars between 0 and 9
2650 * @param $assertMismatch Whether to assert mismatches
2651 * @return $ret The (hopefully) secured hext-numbered value
2653 public function hexval ($num, $assertMismatch = FALSE) {
2654 // Filter all numbers out
2655 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2657 // Assert only if requested
2658 if ($assertMismatch === TRUE) {
2659 // Has the whole value changed?
2660 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2668 * Checks whether start/end marker are set
2670 * @param $data Data to be checked
2671 * @return $isset Whether start/end marker are set
2673 public final function ifStartEndMarkersSet ($data) {
2675 $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));
2677 // ... and return it
2682 * Determines if an element is set in the generic array
2684 * @param $keyGroup Main group for the key
2685 * @param $subGroup Sub group for the key
2686 * @param $key Key to check
2687 * @param $element Element to check
2688 * @return $isset Whether the given key is set
2690 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2692 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2695 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2701 * Determines if a key is set in the generic array
2703 * @param $keyGroup Main group for the key
2704 * @param $subGroup Sub group for the key
2705 * @param $key Key to check
2706 * @return $isset Whether the given key is set
2708 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2710 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2713 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2721 * Determines if a group is set in the generic array
2723 * @param $keyGroup Main group
2724 * @param $subGroup Sub group
2725 * @return $isset Whether the given group is set
2727 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2729 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2732 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2739 * Getter for sub key group
2741 * @param $keyGroup Main key group
2742 * @param $subGroup Sub key group
2743 * @return $array An array with all array elements
2745 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2747 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2748 // No, then abort here
2749 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2754 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2757 return $this->genericArray[$keyGroup][$subGroup];
2761 * Unsets a given key in generic array
2763 * @param $keyGroup Main group for the key
2764 * @param $subGroup Sub group for the key
2765 * @param $key Key to unset
2768 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2770 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2773 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2777 * Unsets a given element in generic array
2779 * @param $keyGroup Main group for the key
2780 * @param $subGroup Sub group for the key
2781 * @param $key Key to unset
2782 * @param $element Element to unset
2785 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2787 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2790 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2794 * Append a string to a given generic array key
2796 * @param $keyGroup Main group for the key
2797 * @param $subGroup Sub group for the key
2798 * @param $key Key to unset
2799 * @param $value Value to add/append
2802 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2804 //* 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);
2806 // Is it already there?
2807 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2809 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2812 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2817 * Append a string to a given generic array element
2819 * @param $keyGroup Main group for the key
2820 * @param $subGroup Sub group for the key
2821 * @param $key Key to unset
2822 * @param $element Element to check
2823 * @param $value Value to add/append
2826 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2828 //* 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);
2830 // Is it already there?
2831 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2833 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2836 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2841 * Sets a string in a given generic array element
2843 * @param $keyGroup Main group for the key
2844 * @param $subGroup Sub group for the key
2845 * @param $key Key to unset
2846 * @param $element Element to check
2847 * @param $value Value to add/append
2850 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2852 //* 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);
2855 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2859 * Initializes given generic array group
2861 * @param $keyGroup Main group for the key
2862 * @param $subGroup Sub group for the key
2863 * @param $key Key to use
2864 * @param $forceInit Optionally force initialization
2867 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2869 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2871 // Is it already set?
2872 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2873 // Already initialized
2874 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2879 $this->genericArray[$keyGroup][$subGroup] = array();
2883 * Initializes given generic array key
2885 * @param $keyGroup Main group for the key
2886 * @param $subGroup Sub group for the key
2887 * @param $key Key to use
2888 * @param $forceInit Optionally force initialization
2891 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2893 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2895 // Is it already set?
2896 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2897 // Already initialized
2898 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2903 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2907 * Initializes given generic array element
2909 * @param $keyGroup Main group for the key
2910 * @param $subGroup Sub group for the key
2911 * @param $key Key to use
2912 * @param $element Element to use
2913 * @param $forceInit Optionally force initialization
2916 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2918 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2920 // Is it already set?
2921 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2922 // Already initialized
2923 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2928 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2932 * Pushes an element to a generic key
2934 * @param $keyGroup Main group for the key
2935 * @param $subGroup Sub group for the key
2936 * @param $key Key to use
2937 * @param $value Value to add/append
2938 * @return $count Number of array elements
2940 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2942 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2945 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2947 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2951 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2954 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2955 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2960 * Pushes an element to a generic array element
2962 * @param $keyGroup Main group for the key
2963 * @param $subGroup Sub group for the key
2964 * @param $key Key to use
2965 * @param $element Element to check
2966 * @param $value Value to add/append
2967 * @return $count Number of array elements
2969 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2971 //* 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));
2974 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2976 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2980 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2983 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2984 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2989 * Pops an element from a generic group
2991 * @param $keyGroup Main group for the key
2992 * @param $subGroup Sub group for the key
2993 * @param $key Key to unset
2994 * @return $value Last "popped" value
2996 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2998 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3001 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3003 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3008 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
3011 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3012 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3017 * Shifts an element from a generic group
3019 * @param $keyGroup Main group for the key
3020 * @param $subGroup Sub group for the key
3021 * @param $key Key to unset
3022 * @return $value Last "popped" value
3024 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3026 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3029 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3031 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3036 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3039 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3040 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3045 * Count generic array group
3047 * @param $keyGroup Main group for the key
3048 * @return $count Count of given group
3050 protected final function countGenericArray ($keyGroup) {
3052 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3055 if (!isset($this->genericArray[$keyGroup])) {
3057 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3062 $count = count($this->genericArray[$keyGroup]);
3065 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3072 * Count generic array sub group
3074 * @param $keyGroup Main group for the key
3075 * @param $subGroup Sub group for the key
3076 * @return $count Count of given group
3078 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3080 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3083 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3085 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3090 $count = count($this->genericArray[$keyGroup][$subGroup]);
3093 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3100 * Count generic array elements
3102 * @param $keyGroup Main group for the key
3103 * @param $subGroup Sub group for the key
3104 * @para $key Key to count
3105 * @return $count Count of given key
3107 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3109 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3112 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3114 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3116 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3118 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3123 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3126 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3133 * Getter for whole generic group array
3135 * @param $keyGroup Key group to get
3136 * @return $array Whole generic array group
3138 protected final function getGenericArray ($keyGroup) {
3140 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3143 if (!isset($this->genericArray[$keyGroup])) {
3145 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3150 return $this->genericArray[$keyGroup];
3154 * Setter for generic array key
3156 * @param $keyGroup Key group to get
3157 * @param $subGroup Sub group for the key
3158 * @param $key Key to unset
3159 * @param $value Mixed value from generic array element
3162 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3164 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3167 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3171 * Getter for generic array key
3173 * @param $keyGroup Key group to get
3174 * @param $subGroup Sub group for the key
3175 * @param $key Key to unset
3176 * @return $value Mixed value from generic array element
3178 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3180 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3183 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3185 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3190 return $this->genericArray[$keyGroup][$subGroup][$key];
3194 * Sets a value in given generic array key/element
3196 * @param $keyGroup Main group for the key
3197 * @param $subGroup Sub group for the key
3198 * @param $key Key to set
3199 * @param $element Element to set
3200 * @param $value Value to set
3203 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3205 //* 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));
3208 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3212 * Getter for generic array element
3214 * @param $keyGroup Key group to get
3215 * @param $subGroup Sub group for the key
3216 * @param $key Key to look for
3217 * @param $element Element to look for
3218 * @return $value Mixed value from generic array element
3220 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3222 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3225 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3227 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3232 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3236 * Checks if a given sub group is valid (array)
3238 * @param $keyGroup Key group to get
3239 * @param $subGroup Sub group for the key
3240 * @return $isValid Whether given sub group is valid
3242 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3244 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3247 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3254 * Checks if a given key is valid (array)
3256 * @param $keyGroup Key group to get
3257 * @param $subGroup Sub group for the key
3258 * @param $key Key to check
3259 * @return $isValid Whether given sub group is valid
3261 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3263 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3266 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3273 * Initializes the web output instance
3277 protected function initWebOutputInstance () {
3278 // Get application instance
3279 $applicationInstance = Registry::getRegistry()->getInstance('app');
3281 // Is this a response instance?
3282 if ($this instanceof Responseable) {
3283 // Then set it in application instance
3284 $applicationInstance->setResponseInstance($this);
3287 // Init web output instance
3288 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3291 $this->setWebOutputInstance($outputInstance);
3295 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3297 * @param $boolean Boolean value
3298 * @return $translated Translated boolean value
3300 public static final function translateBooleanToYesNo ($boolean) {
3301 // Make sure it is really boolean
3302 assert(is_bool($boolean));
3305 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3307 // ... and return it
3312 * Encodes raw data (almost any type) by "serializing" it and then pack it
3313 * into a "binary format".
3315 * @param $rawData Raw data (almost any type)
3316 * @return $encoded Encoded data
3318 protected function encodeData ($rawData) {
3319 // Make sure no objects or resources pass through
3320 assert(!is_object($rawData));
3321 assert(!is_resource($rawData));
3323 // First "serialize" it (json_encode() is faster than serialize())
3324 $encoded = $this->packString(json_encode($rawData));
3331 * Pack a string into a "binary format". Please execuse me that this is
3332 * widely undocumented. :-(
3334 * @param $str Unpacked string
3335 * @return $packed Packed string
3336 * @todo Improve documentation
3338 protected function packString ($str) {
3340 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3342 // First compress the string (gzcompress is okay)
3343 $str = gzcompress($str);
3348 // And start the "encoding" loop
3349 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3351 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3352 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3354 if (($idx + $i) <= strlen($str)) {
3355 $ord = ord(substr($str, ($idx + $i), 1));
3357 $add = $ord * pow(256, $factor);
3361 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3365 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3366 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3368 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3369 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3375 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3380 * Checks whether the given file/path is in open_basedir(). This does not
3381 * gurantee that the file is actually readable and/or writeable. If you need
3382 * such gurantee then please use isReadableFile() instead.
3384 * @param $filePathName Name of the file/path to be checked
3385 * @return $isReachable Whether it is within open_basedir()
3387 protected static function isReachableFilePath ($filePathName) {
3388 // Is not reachable by default
3389 $isReachable = FALSE;
3391 // Get open_basedir parameter
3392 $openBaseDir = ini_get('open_basedir');
3395 if (!empty($openBaseDir)) {
3396 // Check all entries
3397 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3398 // Check on existence
3399 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3401 $isReachable = TRUE;
3405 // If open_basedir is not set, all is allowed
3406 $isReachable = TRUE;
3410 return $isReachable;
3414 * Checks whether the give file is within open_basedir() (done by
3415 * isReachableFilePath()), is actually a file and is readable.
3417 * @param $fileName Name of the file to be checked
3418 * @return $isReadable Whether the file is readable (and therefor exists)
3420 public static function isReadableFile ($fileName) {
3421 // Default is not readable
3422 $isReadable = FALSE;
3424 // Is within parameters, so check if it is a file and readable
3425 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3432 * Creates a full-qualified file name (FQFN) for given file name by adding
3433 * a configured temporary file path to it.
3435 * @param $fileName Name for temporary file
3436 * @return $fqfn Full-qualified file name
3437 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3438 * @throws FileIoException If the file cannot be written
3440 protected static function createTempPathForFile ($fileName) {
3442 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3444 // Is the path writeable?
3445 if (!is_writable($basePath)) {
3446 // Path is write-protected
3447 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3451 $fqfn = $basePath . '/' . $fileName;
3454 if (!self::isReachableFilePath($fqfn)) {
3456 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3464 * "Getter" for a printable state name
3466 * @return $stateName Name of the node's state in a printable format
3468 public final function getPrintableState () {
3469 // Default is 'null'
3470 $stateName = 'null';
3472 // Get the state instance
3473 $stateInstance = $this->getStateInstance();
3475 // Is it an instance of Stateable?
3476 if ($stateInstance instanceof Stateable) {
3477 // Then use that state name
3478 $stateName = $stateInstance->getStateName();
3486 * Handles socket error for given socket resource and peer data. This method
3487 * validates $socketResource if it is a valid resource (see is_resource())
3488 * but assumes valid data in array $recipientData, except that
3489 * count($recipientData) is always 2.
3491 * @param $method Value of __METHOD__ from calling method
3492 * @param $line Value of __LINE__ from calling method
3493 * @param $socketResource A valid socket resource
3494 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3496 * @throws InvalidSocketException If $socketResource is no socket resource
3497 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3498 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3500 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3501 // This method handles only socket resources
3502 if (!is_resource($socketResource)) {
3503 // No resource, abort here
3504 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3507 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3508 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3509 assert(isset($socketData[0]));
3510 assert(isset($socketData[1]));
3512 // Get error code for first validation (0 is not an error)
3513 $errorCode = socket_last_error($socketResource);
3515 // If the error code is zero, someone called this method without an error
3516 if ($errorCode == 0) {
3517 // No error detected (or previously cleared outside this method)
3518 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3521 // Get handler (method) name
3522 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3524 // Call-back the error handler method
3525 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3527 // Finally clear the error because it has been handled
3528 socket_clear_error($socketResource);