3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Compressor\Compressor;
7 use CoreFramework\Configuration\FrameworkConfiguration;
8 use CoreFramework\Connection\Database\DatabaseConnection;
9 use CoreFramework\Controller\Controller;
10 use CoreFramework\Criteria\Criteria;
11 use CoreFramework\Criteria\Local\LocalSearchCriteria;
12 use CoreFramework\Criteria\Local\LocalUpdateCriteria;
13 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
14 use CoreFramework\Factory\ObjectFactory;
15 use CoreFramework\Filesystem\FrameworkDirectory;
16 use CoreFramework\Generic\FrameworkInterface;
17 use CoreFramework\Generic\NullPointerException;
18 use CoreFramework\Handler\Stream\IoHandler;
19 use CoreFramework\Loader\ClassLoader;
20 use CoreFramework\Manager\ManageableApplication;
21 use CoreFramework\Middleware\Compressor\CompressorChannel;
22 use CoreFramework\Middleware\Debug\DebugMiddleware;
23 use CoreFramework\Registry\Register;
24 use CoreFramework\Registry\Registry;
25 use CoreFramework\Request\Requestable;
26 use CoreFramework\Resolver\Resolver;
27 use CoreFramework\Result\Database\CachedDatabaseResult;
28 use CoreFramework\Result\Search\SearchableResult;
29 use CoreFramework\Response\Responseable;
30 use CoreFramework\Stream\Output\OutputStreamer;
31 use CoreFramework\Template\CompileableTemplate;
32 use CoreFramework\Wrapper\Database\DatabaseWrapper;
39 * The simulator system class is the super class of all other classes. This
40 * class handles saving of games etc.
42 * @author Roland Haeder <webmaster@shipsimu.org>
44 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
45 * @license GNU GPL 3.0 or any newer version
46 * @link http://www.shipsimu.org
48 * This program is free software: you can redistribute it and/or modify
49 * it under the terms of the GNU General Public License as published by
50 * the Free Software Foundation, either version 3 of the License, or
51 * (at your option) any later version.
53 * This program is distributed in the hope that it will be useful,
54 * but WITHOUT ANY WARRANTY; without even the implied warranty of
55 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
56 * GNU General Public License for more details.
58 * You should have received a copy of the GNU General Public License
59 * along with this program. If not, see <http://www.gnu.org/licenses/>.
61 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
63 * Length of output from hash()
65 private static $hashLength = NULL;
70 private $realClass = 'BaseFrameworkSystem';
73 * Instance of a Requestable class
75 private $requestInstance = NULL;
78 * Instance of a Responseable class
80 private $responseInstance = NULL;
83 * Search criteria instance
85 private $searchInstance = NULL;
88 * Update criteria instance
90 private $updateInstance = NULL;
93 * The file I/O instance for the template loader
95 private $fileIoInstance = NULL;
100 private $resolverInstance = NULL;
103 * Template engine instance
105 private $templateInstance = NULL;
108 * Database result instance
110 private $resultInstance = NULL;
113 * Instance for user class
115 private $userInstance = NULL;
118 * A controller instance
120 private $controllerInstance = NULL;
125 private $rngInstance = NULL;
128 * Instance of a crypto helper
130 private $cryptoInstance = NULL;
133 * Instance of an Iterator class
135 private $iteratorInstance = NULL;
138 * Instance of the list
140 private $listInstance = NULL;
145 private $menuInstance = NULL;
148 * Instance of the image
150 private $imageInstance = NULL;
153 * Instance of the stacker
155 private $stackInstance = NULL;
158 * A Compressor instance
160 private $compressorInstance = NULL;
163 * A Parseable instance
165 private $parserInstance = NULL;
168 * A HandleableProtocol instance
170 private $protocolInstance = NULL;
173 * A database wrapper instance
175 private $databaseInstance = NULL;
178 * A helper instance for the form
180 private $helperInstance = NULL;
183 * An instance of a Source class
185 private $sourceInstance = NULL;
188 * An instance of a UrlSource class
190 private $urlSourceInstance = NULL;
193 * An instance of a InputStream class
195 private $inputStreamInstance = NULL;
198 * An instance of a OutputStream class
200 private $outputStreamInstance = NULL;
203 * Networkable handler instance
205 private $handlerInstance = NULL;
208 * Visitor handler instance
210 private $visitorInstance = NULL;
215 private $dhtInstance = NULL;
218 * An instance of a database wrapper class
220 private $wrapperInstance = NULL;
223 * An instance of a file I/O pointer class (not handler)
225 private $pointerInstance = NULL;
228 * An instance of an Indexable class
230 private $indexInstance = NULL;
233 * An instance of a Block class
235 private $blockInstance = NULL;
240 private $minableInstance = NULL;
243 * A FrameworkDirectory instance
245 private $directoryInstance = NULL;
250 private $listenerInstance = NULL;
253 * An instance of a communicator
255 private $communicatorInstance = NULL;
258 * The concrete output instance
260 private $outputInstance = NULL;
265 private $stateInstance = NULL;
268 * Thousands separator
270 private $thousands = '.'; // German
275 private $decimals = ','; // German
280 private $socketResource = FALSE;
283 * Regular expression to use for validation
285 private $regularExpression = '';
290 private $packageData = array();
295 private $genericArray = array();
300 private $commandName = '';
305 private $controllerName = '';
308 * Name of used protocol
310 private $protocolName = 'invalid';
313 * Array with bitmasks and such for pack/unpack methods to support both
314 * 32-bit and 64-bit systems
316 private $packingData = array(
319 'left' => 0xffff0000,
320 'right' => 0x0000ffff,
326 'left' => 0xffffffff00000000,
327 'right' => 0x00000000ffffffff,
334 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
336 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
338 private $archArrayElement = FALSE;
340 /***********************
341 * Exception codes.... *
342 ***********************/
344 // @todo Try to clean these constants up
345 const EXCEPTION_IS_NULL_POINTER = 0x001;
346 const EXCEPTION_IS_NO_OBJECT = 0x002;
347 const EXCEPTION_IS_NO_ARRAY = 0x003;
348 const EXCEPTION_MISSING_METHOD = 0x004;
349 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
350 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
351 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
352 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
353 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
354 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
355 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
356 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
357 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
358 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
359 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
360 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
361 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
362 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
363 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
364 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
365 const EXCEPTION_PATH_NOT_FOUND = 0x015;
366 const EXCEPTION_INVALID_PATH_NAME = 0x016;
367 const EXCEPTION_READ_PROTECED_PATH = 0x017;
368 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
369 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
370 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
371 const EXCEPTION_INVALID_RESOURCE = 0x01b;
372 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
373 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
374 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
375 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
376 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
377 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
378 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
379 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
380 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
381 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
382 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
383 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
384 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
385 const EXCEPTION_INVALID_STRING = 0x029;
386 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
387 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
388 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
389 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
390 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
391 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
392 const EXCEPTION_MISSING_ELEMENT = 0x030;
393 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
394 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
395 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
396 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
397 const EXCEPTION_FATAL_ERROR = 0x035;
398 const EXCEPTION_FILE_NOT_FOUND = 0x036;
399 const EXCEPTION_ASSERTION_FAILED = 0x037;
400 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
401 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
402 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
403 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
404 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
405 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
408 * Hexadecimal->Decimal translation array
410 private static $hexdec = array(
430 * Decimal->hexadecimal translation array
432 private static $dechex = array(
452 * Startup time in miliseconds
454 private static $startupTime = 0;
457 * Protected super constructor
459 * @param $className Name of the class
462 protected function __construct ($className) {
464 $this->setRealClass($className);
466 // Set configuration instance if no registry ...
467 if (!$this instanceof Register) {
468 // ... because registries doesn't need to be configured
469 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
472 // Is the startup time set? (0 cannot be TRUE anymore)
473 if (self::$startupTime == 0) {
475 self::$startupTime = microtime(TRUE);
479 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
483 * Destructor for all classes. You should not call this method on your own.
487 public function __destruct () {
488 // Flush any updated entries to the database
489 $this->flushPendingUpdates();
491 // Is this object already destroyed?
492 if ($this->__toString() != 'DestructedObject') {
493 // Destroy all informations about this class but keep some text about it alive
494 $this->setRealClass('DestructedObject');
495 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
496 // Already destructed object
497 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
502 // Do not call this twice
503 trigger_error(__METHOD__ . ': Called twice.');
509 * The __call() method where all non-implemented methods end up
511 * @param $methodName Name of the missing method
512 * @args $args Arguments passed to the method
515 public final function __call ($methodName, $args) {
516 return self::__callStatic($methodName, $args);
520 * The __callStatic() method where all non-implemented static methods end up
522 * @param $methodName Name of the missing method
523 * @args $args Arguments passed to the method
526 public static final function __callStatic ($methodName, $args) {
528 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
530 // Init argument string
533 // Is it NULL, empty or an array?
534 if (is_null($args)) {
536 $argsString = 'NULL';
537 } elseif (is_array($args)) {
541 // Some arguments are there
542 foreach ($args as $arg) {
543 // Add data about the argument
544 $argsString .= gettype($arg) . ':';
547 // Found a NULL argument
548 $argsString .= 'NULL';
549 } elseif (is_string($arg)) {
550 // Add length for strings
551 $argsString .= strlen($arg);
552 } elseif ((is_int($arg)) || (is_float($arg))) {
555 } elseif (is_array($arg)) {
556 // .. or size if array
557 $argsString .= count($arg);
558 } elseif (is_object($arg)) {
560 $reflection = new ReflectionClass($arg);
562 // Is an other object, maybe no __toString() available
563 $argsString .= $reflection->getName();
564 } elseif ($arg === TRUE) {
565 // ... is boolean 'TRUE'
566 $argsString .= 'TRUE';
567 } elseif ($arg === FALSE) {
568 // ... is boolean 'FALSE'
569 $argsString .= 'FALSE';
572 // Comma for next one
577 if (substr($argsString, -2, 1) == ',') {
578 $argsString = substr($argsString, 0, -2);
584 // Invalid arguments!
585 $argsString = '!INVALID:' . gettype($args) . '!';
588 // Output stub message
589 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
590 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
600 * Getter for $realClass
602 * @return $realClass The name of the real class (not BaseFrameworkSystem)
604 public function __toString () {
605 return $this->realClass;
609 * Magic method to catch setting of missing but set class fields/attributes
611 * @param $name Name of the field/attribute
612 * @param $value Value to store
615 public final function __set ($name, $value) {
616 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
619 print_r($value, TRUE)
624 * Magic method to catch getting of missing fields/attributes
626 * @param $name Name of the field/attribute
629 public final function __get ($name) {
630 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
636 * Magic method to catch unsetting of missing fields/attributes
638 * @param $name Name of the field/attribute
641 public final function __unset ($name) {
642 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
648 * Magic method to catch object serialization
650 * @return $unsupported Unsupported method
651 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
653 public final function __sleep () {
654 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
658 * Magic method to catch object deserialization
660 * @return $unsupported Unsupported method
661 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
663 public final function __wakeup () {
664 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
668 * Magic method to catch calls when an object instance is called
670 * @return $unsupported Unsupported method
671 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
673 public final function __invoke () {
674 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
678 * Setter for the real class name
680 * @param $realClass Class name (string)
683 public final function setRealClass ($realClass) {
685 $this->realClass = (string) $realClass;
689 * Setter for database result instance
691 * @param $resultInstance An instance of a database result class
693 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
695 protected final function setResultInstance (SearchableResult $resultInstance) {
696 $this->resultInstance = $resultInstance;
700 * Getter for database result instance
702 * @return $resultInstance An instance of a database result class
704 public final function getResultInstance () {
705 return $this->resultInstance;
709 * Setter for template engine instances
711 * @param $templateInstance An instance of a template engine class
714 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
715 $this->templateInstance = $templateInstance;
719 * Getter for template engine instances
721 * @return $templateInstance An instance of a template engine class
723 protected final function getTemplateInstance () {
724 return $this->templateInstance;
728 * Setter for search instance
730 * @param $searchInstance Searchable criteria instance
733 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
734 $this->searchInstance = $searchInstance;
738 * Getter for search instance
740 * @return $searchInstance Searchable criteria instance
742 public final function getSearchInstance () {
743 return $this->searchInstance;
747 * Setter for update instance
749 * @param $updateInstance An instance of a LocalUpdateCriteria clase
752 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
753 $this->updateInstance = $updateInstance;
757 * Getter for update instance
759 * @return $updateInstance Updateable criteria instance
761 public final function getUpdateInstance () {
762 return $this->updateInstance;
766 * Setter for resolver instance
768 * @param $resolverInstance Instance of a command resolver class
771 public final function setResolverInstance (Resolver $resolverInstance) {
772 $this->resolverInstance = $resolverInstance;
776 * Getter for resolver instance
778 * @return $resolverInstance Instance of a command resolver class
780 public final function getResolverInstance () {
781 return $this->resolverInstance;
785 * Setter for language instance
787 * @param $configInstance The configuration instance which shall
788 * be FrameworkConfiguration
791 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
792 Registry::getRegistry()->addInstance('config', $configInstance);
796 * Getter for configuration instance
798 * @return $configInstance Configuration instance
800 public final function getConfigInstance () {
801 $configInstance = Registry::getRegistry()->getInstance('config');
802 return $configInstance;
806 * Setter for debug instance
808 * @param $debugInstance The instance for debug output class
811 public final function setDebugInstance (DebugMiddleware $debugInstance) {
812 Registry::getRegistry()->addInstance('debug', $debugInstance);
816 * Getter for debug instance
818 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
820 public final function getDebugInstance () {
821 // Get debug instance
822 $debugInstance = Registry::getRegistry()->getInstance('debug');
825 return $debugInstance;
829 * Setter for web output instance
831 * @param $webInstance The instance for web output class
834 public final function setWebOutputInstance (OutputStreamer $webInstance) {
835 Registry::getRegistry()->addInstance('web_output', $webInstance);
839 * Getter for web output instance
841 * @return $webOutputInstance - Instance to class WebOutput
843 public final function getWebOutputInstance () {
844 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
845 return $webOutputInstance;
849 * Setter for database instance
851 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
854 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
855 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
859 * Getter for database layer
861 * @return $databaseInstance The database layer instance
863 public final function getDatabaseInstance () {
865 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
868 return $databaseInstance;
872 * Setter for compressor channel
874 * @param $compressorInstance An instance of CompressorChannel
877 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
878 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
882 * Getter for compressor channel
884 * @return $compressorInstance The compressor channel
886 public final function getCompressorChannel () {
887 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
888 return $compressorInstance;
892 * Protected getter for a manageable application helper class
894 * @return $applicationInstance An instance of a manageable application helper class
896 protected final function getApplicationInstance () {
897 $applicationInstance = Registry::getRegistry()->getInstance('application');
898 return $applicationInstance;
902 * Setter for a manageable application helper class
904 * @param $applicationInstance An instance of a manageable application helper class
907 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
908 Registry::getRegistry()->addInstance('application', $applicationInstance);
912 * Setter for request instance
914 * @param $requestInstance An instance of a Requestable class
917 public final function setRequestInstance (Requestable $requestInstance) {
918 $this->requestInstance = $requestInstance;
922 * Getter for request instance
924 * @return $requestInstance An instance of a Requestable class
926 public final function getRequestInstance () {
927 return $this->requestInstance;
931 * Setter for response instance
933 * @param $responseInstance An instance of a Responseable class
936 public final function setResponseInstance (Responseable $responseInstance) {
937 $this->responseInstance = $responseInstance;
941 * Getter for response instance
943 * @return $responseInstance An instance of a Responseable class
945 public final function getResponseInstance () {
946 return $this->responseInstance;
950 * Private getter for language instance
952 * @return $langInstance An instance to the language sub-system
954 protected final function getLanguageInstance () {
955 $langInstance = Registry::getRegistry()->getInstance('language');
956 return $langInstance;
960 * Setter for language instance
962 * @param $langInstance An instance to the language sub-system
964 * @see LanguageSystem
966 public final function setLanguageInstance (ManageableLanguage $langInstance) {
967 Registry::getRegistry()->addInstance('language', $langInstance);
971 * Private getter for file IO instance
973 * @return $fileIoInstance An instance to the file I/O sub-system
975 protected final function getFileIoInstance () {
976 return $this->fileIoInstance;
980 * Setter for file I/O instance
982 * @param $fileIoInstance An instance to the file I/O sub-system
985 public final function setFileIoInstance (IoHandler $fileIoInstance) {
986 $this->fileIoInstance = $fileIoInstance;
990 * Protected setter for user instance
992 * @param $userInstance An instance of a user class
995 protected final function setUserInstance (ManageableAccount $userInstance) {
996 $this->userInstance = $userInstance;
1000 * Getter for user instance
1002 * @return $userInstance An instance of a user class
1004 public final function getUserInstance () {
1005 return $this->userInstance;
1009 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1011 * @param $controllerInstance An instance of the controller
1014 public final function setControllerInstance (Controller $controllerInstance) {
1015 $this->controllerInstance = $controllerInstance;
1019 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1021 * @return $controllerInstance An instance of the controller
1023 public final function getControllerInstance () {
1024 return $this->controllerInstance;
1028 * Setter for RNG instance
1030 * @param $rngInstance An instance of a random number generator (RNG)
1033 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1034 $this->rngInstance = $rngInstance;
1038 * Getter for RNG instance
1040 * @return $rngInstance An instance of a random number generator (RNG)
1042 public final function getRngInstance () {
1043 return $this->rngInstance;
1047 * Setter for Cryptable instance
1049 * @param $cryptoInstance An instance of a Cryptable class
1052 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1053 $this->cryptoInstance = $cryptoInstance;
1057 * Getter for Cryptable instance
1059 * @return $cryptoInstance An instance of a Cryptable class
1061 public final function getCryptoInstance () {
1062 return $this->cryptoInstance;
1066 * Setter for the list instance
1068 * @param $listInstance A list of Listable
1071 protected final function setListInstance (Listable $listInstance) {
1072 $this->listInstance = $listInstance;
1076 * Getter for the list instance
1078 * @return $listInstance A list of Listable
1080 protected final function getListInstance () {
1081 return $this->listInstance;
1085 * Setter for the menu instance
1087 * @param $menuInstance A RenderableMenu instance
1090 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1091 $this->menuInstance = $menuInstance;
1095 * Getter for the menu instance
1097 * @return $menuInstance A RenderableMenu instance
1099 protected final function getMenuInstance () {
1100 return $this->menuInstance;
1104 * Setter for image instance
1106 * @param $imageInstance An instance of an image
1109 public final function setImageInstance (BaseImage $imageInstance) {
1110 $this->imageInstance = $imageInstance;
1114 * Getter for image instance
1116 * @return $imageInstance An instance of an image
1118 public final function getImageInstance () {
1119 return $this->imageInstance;
1123 * Setter for stacker instance
1125 * @param $stackInstance An instance of an stacker
1128 public final function setStackInstance (Stackable $stackInstance) {
1129 $this->stackInstance = $stackInstance;
1133 * Getter for stacker instance
1135 * @return $stackInstance An instance of an stacker
1137 public final function getStackInstance () {
1138 return $this->stackInstance;
1142 * Setter for compressor instance
1144 * @param $compressorInstance An instance of an compressor
1147 public final function setCompressorInstance (Compressor $compressorInstance) {
1148 $this->compressorInstance = $compressorInstance;
1152 * Getter for compressor instance
1154 * @return $compressorInstance An instance of an compressor
1156 public final function getCompressorInstance () {
1157 return $this->compressorInstance;
1161 * Setter for Parseable instance
1163 * @param $parserInstance An instance of an Parseable
1166 public final function setParserInstance (Parseable $parserInstance) {
1167 $this->parserInstance = $parserInstance;
1171 * Getter for Parseable instance
1173 * @return $parserInstance An instance of an Parseable
1175 public final function getParserInstance () {
1176 return $this->parserInstance;
1180 * Setter for HandleableProtocol instance
1182 * @param $protocolInstance An instance of an HandleableProtocol
1185 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1186 $this->protocolInstance = $protocolInstance;
1190 * Getter for HandleableProtocol instance
1192 * @return $protocolInstance An instance of an HandleableProtocol
1194 public final function getProtocolInstance () {
1195 return $this->protocolInstance;
1199 * Setter for DatabaseWrapper instance
1201 * @param $wrapperInstance An instance of an DatabaseWrapper
1204 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1205 $this->wrapperInstance = $wrapperInstance;
1209 * Getter for DatabaseWrapper instance
1211 * @return $wrapperInstance An instance of an DatabaseWrapper
1213 public final function getWrapperInstance () {
1214 return $this->wrapperInstance;
1218 * Setter for socket resource
1220 * @param $socketResource A valid socket resource
1223 public final function setSocketResource ($socketResource) {
1224 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1225 $this->socketResource = $socketResource;
1229 * Getter for socket resource
1231 * @return $socketResource A valid socket resource
1233 public final function getSocketResource () {
1234 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1235 return $this->socketResource;
1239 * Setter for regular expression
1241 * @param $regularExpression A valid regular expression
1244 public final function setRegularExpression ($regularExpression) {
1245 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1246 $this->regularExpression = $regularExpression;
1250 * Getter for regular expression
1252 * @return $regularExpression A valid regular expression
1254 public final function getRegularExpression () {
1255 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1256 return $this->regularExpression;
1260 * Setter for helper instance
1262 * @param $helperInstance An instance of a helper class
1265 protected final function setHelperInstance (Helper $helperInstance) {
1266 $this->helperInstance = $helperInstance;
1270 * Getter for helper instance
1272 * @return $helperInstance An instance of a helper class
1274 public final function getHelperInstance () {
1275 return $this->helperInstance;
1279 * Setter for a Source instance
1281 * @param $sourceInstance An instance of a Source class
1284 protected final function setSourceInstance (Source $sourceInstance) {
1285 $this->sourceInstance = $sourceInstance;
1289 * Getter for a Source instance
1291 * @return $sourceInstance An instance of a Source class
1293 protected final function getSourceInstance () {
1294 return $this->sourceInstance;
1298 * Setter for a UrlSource instance
1300 * @param $sourceInstance An instance of a UrlSource class
1303 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1304 $this->urlSourceInstance = $urlSourceInstance;
1308 * Getter for a UrlSource instance
1310 * @return $urlSourceInstance An instance of a UrlSource class
1312 protected final function getUrlSourceInstance () {
1313 return $this->urlSourceInstance;
1317 * Getter for a InputStream instance
1319 * @param $inputStreamInstance The InputStream instance
1321 protected final function getInputStreamInstance () {
1322 return $this->inputStreamInstance;
1326 * Setter for a InputStream instance
1328 * @param $inputStreamInstance The InputStream instance
1331 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1332 $this->inputStreamInstance = $inputStreamInstance;
1336 * Getter for a OutputStream instance
1338 * @param $outputStreamInstance The OutputStream instance
1340 protected final function getOutputStreamInstance () {
1341 return $this->outputStreamInstance;
1345 * Setter for a OutputStream instance
1347 * @param $outputStreamInstance The OutputStream instance
1350 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1351 $this->outputStreamInstance = $outputStreamInstance;
1355 * Setter for handler instance
1357 * @param $handlerInstance An instance of a Handleable class
1360 protected final function setHandlerInstance (Handleable $handlerInstance) {
1361 $this->handlerInstance = $handlerInstance;
1365 * Getter for handler instance
1367 * @return $handlerInstance A Networkable instance
1369 protected final function getHandlerInstance () {
1370 return $this->handlerInstance;
1374 * Setter for visitor instance
1376 * @param $visitorInstance A Visitor instance
1379 protected final function setVisitorInstance (Visitor $visitorInstance) {
1380 $this->visitorInstance = $visitorInstance;
1384 * Getter for visitor instance
1386 * @return $visitorInstance A Visitor instance
1388 protected final function getVisitorInstance () {
1389 return $this->visitorInstance;
1393 * Setter for DHT instance
1395 * @param $dhtInstance A Distributable instance
1398 protected final function setDhtInstance (Distributable $dhtInstance) {
1399 $this->dhtInstance = $dhtInstance;
1403 * Getter for DHT instance
1405 * @return $dhtInstance A Distributable instance
1407 protected final function getDhtInstance () {
1408 return $this->dhtInstance;
1412 * Setter for raw package Data
1414 * @param $packageData Raw package Data
1417 public final function setPackageData (array $packageData) {
1418 $this->packageData = $packageData;
1422 * Getter for raw package Data
1424 * @return $packageData Raw package Data
1426 public function getPackageData () {
1427 return $this->packageData;
1432 * Setter for Iterator instance
1434 * @param $iteratorInstance An instance of an Iterator
1437 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1438 $this->iteratorInstance = $iteratorInstance;
1442 * Getter for Iterator instance
1444 * @return $iteratorInstance An instance of an Iterator
1446 public final function getIteratorInstance () {
1447 return $this->iteratorInstance;
1451 * Setter for FilePointer instance
1453 * @param $pointerInstance An instance of an FilePointer class
1456 protected final function setPointerInstance (FilePointer $pointerInstance) {
1457 $this->pointerInstance = $pointerInstance;
1461 * Getter for FilePointer instance
1463 * @return $pointerInstance An instance of an FilePointer class
1465 public final function getPointerInstance () {
1466 return $this->pointerInstance;
1470 * Unsets pointer instance which triggers a call of __destruct() if the
1471 * instance is still there. This is surely not fatal on already "closed"
1472 * file pointer instances.
1474 * I don't want to mess around with above setter by giving it a default
1475 * value NULL as setter should always explicitly only set (existing) object
1476 * instances and NULL is NULL.
1480 protected final function unsetPointerInstance () {
1481 // Simply it to NULL
1482 $this->pointerInstance = NULL;
1486 * Setter for Indexable instance
1488 * @param $indexInstance An instance of an Indexable class
1491 protected final function setIndexInstance (Indexable $indexInstance) {
1492 $this->indexInstance = $indexInstance;
1496 * Getter for Indexable instance
1498 * @return $indexInstance An instance of an Indexable class
1500 public final function getIndexInstance () {
1501 return $this->indexInstance;
1505 * Setter for Block instance
1507 * @param $blockInstance An instance of an Block class
1510 protected final function setBlockInstance (Block $blockInstance) {
1511 $this->blockInstance = $blockInstance;
1515 * Getter for Block instance
1517 * @return $blockInstance An instance of an Block class
1519 public final function getBlockInstance () {
1520 return $this->blockInstance;
1524 * Setter for Minable instance
1526 * @param $minableInstance A Minable instance
1529 protected final function setMinableInstance (Minable $minableInstance) {
1530 $this->minableInstance = $minableInstance;
1534 * Getter for minable instance
1536 * @return $minableInstance A Minable instance
1538 protected final function getMinableInstance () {
1539 return $this->minableInstance;
1543 * Setter for FrameworkDirectory instance
1545 * @param $directoryInstance A FrameworkDirectory instance
1548 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1549 $this->directoryInstance = $directoryInstance;
1553 * Getter for FrameworkDirectory instance
1555 * @return $directoryInstance A FrameworkDirectory instance
1557 protected final function getDirectoryInstance () {
1558 return $this->directoryInstance;
1562 * Setter for listener instance
1564 * @param $listenerInstance A Listenable instance
1567 protected final function setListenerInstance (Listenable $listenerInstance) {
1568 $this->listenerInstance = $listenerInstance;
1572 * Getter for listener instance
1574 * @return $listenerInstance A Listenable instance
1576 protected final function getListenerInstance () {
1577 return $this->listenerInstance;
1581 * Getter for communicator instance
1583 * @return $communicatorInstance An instance of a Communicator class
1585 public final function getCommunicatorInstance () {
1586 return $this->communicatorInstance;
1590 * Setter for communicator instance
1592 * @param $communicatorInstance An instance of a Communicator class
1595 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1596 $this->communicatorInstance = $communicatorInstance;
1600 * Setter for state instance
1602 * @param $stateInstance A Stateable instance
1605 public final function setStateInstance (Stateable $stateInstance) {
1606 $this->stateInstance = $stateInstance;
1610 * Getter for state instance
1612 * @return $stateInstance A Stateable instance
1614 public final function getStateInstance () {
1615 return $this->stateInstance;
1619 * Setter for output instance
1621 * @param $outputInstance The debug output instance
1624 public final function setOutputInstance (OutputStreamer $outputInstance) {
1625 $this->outputInstance = $outputInstance;
1629 * Getter for output instance
1631 * @return $outputInstance The debug output instance
1633 public final function getOutputInstance () {
1634 return $this->outputInstance;
1638 * Setter for command name
1640 * @param $commandName Last validated command name
1643 protected final function setCommandName ($commandName) {
1644 $this->commandName = $commandName;
1648 * Getter for command name
1650 * @return $commandName Last validated command name
1652 protected final function getCommandName () {
1653 return $this->commandName;
1657 * Setter for controller name
1659 * @param $controllerName Last validated controller name
1662 protected final function setControllerName ($controllerName) {
1663 $this->controllerName = $controllerName;
1667 * Getter for controller name
1669 * @return $controllerName Last validated controller name
1671 protected final function getControllerName () {
1672 return $this->controllerName;
1676 * Getter for protocol name
1678 * @return $protocolName Name of used protocol
1680 public final function getProtocolName () {
1681 return $this->protocolName;
1685 * Setter for protocol name
1687 * @param $protocolName Name of used protocol
1690 protected final function setProtocolName ($protocolName) {
1691 $this->protocolName = $protocolName;
1695 * Checks whether an object equals this object. You should overwrite this
1696 * method to implement own equality checks
1698 * @param $objectInstance An instance of a FrameworkInterface object
1699 * @return $equals Whether both objects equals
1701 public function equals (FrameworkInterface $objectInstance) {
1704 $this->__toString() == $objectInstance->__toString()
1706 $this->hashCode() == $objectInstance->hashCode()
1709 // Return the result
1714 * Generates a generic hash code of this class. You should really overwrite
1715 * this method with your own hash code generator code. But keep KISS in mind.
1717 * @return $hashCode A generic hash code respresenting this whole class
1719 public function hashCode () {
1721 return crc32($this->__toString());
1725 * Formats computer generated price values into human-understandable formats
1726 * with thousand and decimal separators.
1728 * @param $value The in computer format value for a price
1729 * @param $currency The currency symbol (use HTML-valid characters!)
1730 * @param $decNum Number of decimals after commata
1731 * @return $price The for the current language formated price string
1732 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1733 * thousands separator
1736 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1737 // Are all required attriutes set?
1738 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1739 // Throw an exception
1740 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1744 $value = (float) $value;
1746 // Reformat the US number
1747 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1749 // Return as string...
1754 * Appends a trailing slash to a string
1756 * @param $str A string (maybe) without trailing slash
1757 * @return $str A string with an auto-appended trailing slash
1759 public final function addMissingTrailingSlash ($str) {
1760 // Is there a trailing slash?
1761 if (substr($str, -1, 1) != '/') {
1765 // Return string with trailing slash
1770 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1771 * application helper instance (ApplicationHelper by default).
1773 * @param $applicationInstance An application helper instance or
1774 * null if we shall use the default
1775 * @return $templateInstance The template engine instance
1776 * @throws NullPointerException If the discovered application
1777 * instance is still null
1779 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1780 // Is the application instance set?
1781 if (is_null($applicationInstance)) {
1782 // Get the current instance
1783 $applicationInstance = $this->getApplicationInstance();
1786 if (is_null($applicationInstance)) {
1787 // Thrown an exception
1788 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1792 // Initialize the template engine
1793 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1795 // Return the prepared instance
1796 return $templateInstance;
1800 * Debugs this instance by putting out it's full content
1802 * @param $message Optional message to show in debug output
1805 public final function debugInstance ($message = '') {
1806 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1807 restore_error_handler();
1812 // Is a message set?
1813 if (!empty($message)) {
1814 // Construct message
1815 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1818 // Generate the output
1819 $content .= sprintf('<pre>%s</pre>',
1822 print_r($this, TRUE)
1828 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>',
1829 $this->__toString(),
1831 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1836 * Replaces control characters with printable output
1838 * @param $str String with control characters
1839 * @return $str Replaced string
1841 protected function replaceControlCharacters ($str) {
1844 chr(13), '[r]', str_replace(
1845 chr(10), '[n]', str_replace(
1855 * Output a partial stub message for the caller method
1857 * @param $message An optional message to display
1860 protected function partialStub ($message = '') {
1861 // Get the backtrace
1862 $backtrace = debug_backtrace();
1864 // Generate the class::method string
1865 $methodName = 'UnknownClass->unknownMethod';
1866 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1867 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1870 // Construct the full message
1871 $stubMessage = sprintf('[%s:] Partial stub!',
1875 // Is the extra message given?
1876 if (!empty($message)) {
1877 // Then add it as well
1878 $stubMessage .= ' Message: ' . $message;
1881 // Debug instance is there?
1882 if (!is_null($this->getDebugInstance())) {
1883 // Output stub message
1884 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1887 trigger_error($stubMessage);
1893 * Outputs a debug backtrace and stops further script execution
1895 * @param $message An optional message to output
1896 * @param $doExit Whether exit the program (TRUE is default)
1899 public function debugBackTrace ($message = '', $doExit = TRUE) {
1900 // Sorry, there is no other way getting this nice backtrace
1901 if (!empty($message)) {
1903 printf('Message: %s<br />' . PHP_EOL, $message);
1907 debug_print_backtrace();
1911 if ($doExit === TRUE) {
1917 * Creates an instance of a debugger instance
1919 * @param $className Name of the class (currently unsupported)
1920 * @param $lineNumber Line number where the call was made
1921 * @return $debugInstance An instance of a debugger class
1922 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1924 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1925 // Is the instance set?
1926 if (!Registry::getRegistry()->instanceExists('debug')) {
1927 // Init debug instance
1928 $debugInstance = NULL;
1932 // Get a debugger instance
1933 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1934 } catch (NullPointerException $e) {
1935 // Didn't work, no instance there
1936 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1939 // Empty string should be ignored and used for testing the middleware
1940 DebugMiddleware::getSelfInstance()->output('');
1942 // Set it in its own class. This will set it in the registry
1943 $debugInstance->setDebugInstance($debugInstance);
1945 // Get instance from registry
1946 $debugInstance = Registry::getRegistry()->getDebugInstance();
1950 return $debugInstance;
1954 * Simple output of a message with line-break
1956 * @param $message Message to output
1959 public function outputLine ($message) {
1961 print($message . PHP_EOL);
1965 * Outputs a debug message whether to debug instance (should be set!) or
1966 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1967 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1969 * @param $message Message we shall send out...
1970 * @param $doPrint Whether print or die here (default: print)
1971 * @paran $stripTags Whether to strip tags (default: FALSE)
1974 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1975 // Set debug instance to NULL
1976 $debugInstance = NULL;
1980 // Get debug instance
1981 $debugInstance = $this->getDebugInstance();
1982 } catch (NullPointerException $e) {
1983 // The debug instance is not set (yet)
1986 // Is the debug instance there?
1987 if (is_object($debugInstance)) {
1988 // Use debug output handler
1989 $debugInstance->output($message, $stripTags);
1991 if ($doPrint === FALSE) {
1992 // Die here if not printed
1996 // Are debug times enabled?
1997 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1999 $message = $this->getPrintableExecutionTime() . $message;
2003 if ($doPrint === TRUE) {
2005 $this->outputLine($message);
2014 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2016 * @param $str The string, what ever it is needs to be converted
2017 * @return $className Generated class name
2019 public static final function convertToClassName ($str) {
2023 // Convert all dashes in underscores
2024 $str = self::convertDashesToUnderscores($str);
2026 // Now use that underscores to get classname parts for hungarian style
2027 foreach (explode('_', $str) as $strPart) {
2028 // Make the class name part lower case and first upper case
2029 $className .= ucfirst(strtolower($strPart));
2032 // Return class name
2037 * Converts dashes to underscores, e.g. useable for configuration entries
2039 * @param $str The string with maybe dashes inside
2040 * @return $str The converted string with no dashed, but underscores
2042 public static final function convertDashesToUnderscores ($str) {
2044 $str = str_replace('-', '_', $str);
2046 // Return converted string
2051 * Marks up the code by adding e.g. line numbers
2053 * @param $phpCode Unmarked PHP code
2054 * @return $markedCode Marked PHP code
2056 public function markupCode ($phpCode) {
2061 $errorArray = error_get_last();
2063 // Init the code with error message
2064 if (is_array($errorArray)) {
2066 $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>',
2067 basename($errorArray['file']),
2068 $errorArray['line'],
2069 $errorArray['message'],
2074 // Add line number to the code
2075 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2077 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2079 htmlentities($code, ENT_QUOTES)
2088 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2089 * beatiful for web-based front-ends. If null is given a message id
2090 * null_timestamp will be resolved and returned.
2092 * @param $timestamp Timestamp to prepare (filter) for display
2093 * @return $readable A readable timestamp
2095 public function doFilterFormatTimestamp ($timestamp) {
2096 // Default value to return
2099 // Is the timestamp null?
2100 if (is_null($timestamp)) {
2101 // Get a message string
2102 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2104 switch ($this->getLanguageInstance()->getLanguageCode()) {
2105 case 'de': // German format is a bit different to default
2106 // Split the GMT stamp up
2107 $dateTime = explode(' ', $timestamp );
2108 $dateArray = explode('-', $dateTime[0]);
2109 $timeArray = explode(':', $dateTime[1]);
2111 // Construct the timestamp
2112 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2122 default: // Default is pass-through
2123 $readable = $timestamp;
2133 * Filter a given number into a localized number
2135 * @param $value The raw value from e.g. database
2136 * @return $localized Localized value
2138 public function doFilterFormatNumber ($value) {
2139 // Generate it from config and localize dependencies
2140 switch ($this->getLanguageInstance()->getLanguageCode()) {
2141 case 'de': // German format is a bit different to default
2142 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2145 default: // US, etc.
2146 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2155 * "Getter" for databse entry
2157 * @return $entry An array with database entries
2158 * @throws NullPointerException If the database result is not found
2159 * @throws InvalidDatabaseResultException If the database result is invalid
2161 protected final function getDatabaseEntry () {
2162 // Is there an instance?
2163 if (!$this->getResultInstance() instanceof SearchableResult) {
2164 // Throw an exception here
2165 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2169 $this->getResultInstance()->rewind();
2171 // Do we have an entry?
2172 if ($this->getResultInstance()->valid() === FALSE) {
2173 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2174 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2178 $this->getResultInstance()->next();
2181 $entry = $this->getResultInstance()->current();
2188 * Getter for field name
2190 * @param $fieldName Field name which we shall get
2191 * @return $fieldValue Field value from the user
2192 * @throws NullPointerException If the result instance is null
2194 public final function getField ($fieldName) {
2195 // Default field value
2198 // Get result instance
2199 $resultInstance = $this->getResultInstance();
2201 // Is this instance null?
2202 if (is_null($resultInstance)) {
2203 // Then the user instance is no longer valid (expired cookies?)
2204 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2207 // Get current array
2208 $fieldArray = $resultInstance->current();
2209 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2211 // Convert dashes to underscore
2212 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2214 // Does the field exist?
2215 if ($this->isFieldSet($fieldName)) {
2217 $fieldValue = $fieldArray[$fieldName2];
2218 } elseif (defined('DEVELOPER')) {
2219 // Missing field entry, may require debugging
2220 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2222 // Missing field entry, may require debugging
2223 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2231 * Checks if given field is set
2233 * @param $fieldName Field name to check
2234 * @return $isSet Whether the given field name is set
2235 * @throws NullPointerException If the result instance is null
2237 public function isFieldSet ($fieldName) {
2238 // Get result instance
2239 $resultInstance = $this->getResultInstance();
2241 // Is this instance null?
2242 if (is_null($resultInstance)) {
2243 // Then the user instance is no longer valid (expired cookies?)
2244 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2247 // Get current array
2248 $fieldArray = $resultInstance->current();
2249 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2251 // Convert dashes to underscore
2252 $fieldName = self::convertDashesToUnderscores($fieldName);
2255 $isSet = isset($fieldArray[$fieldName]);
2262 * Flushs all pending updates to the database layer
2266 public function flushPendingUpdates () {
2267 // Get result instance
2268 $resultInstance = $this->getResultInstance();
2270 // Do we have data to update?
2271 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2272 // Get wrapper class name config entry
2273 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2275 // Create object instance
2276 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2278 // Yes, then send the whole result to the database layer
2279 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2284 * Outputs a deprecation warning to the developer.
2286 * @param $message The message we shall output to the developer
2288 * @todo Write a logging mechanism for productive mode
2290 public function deprecationWarning ($message) {
2291 // Is developer mode active?
2292 if (defined('DEVELOPER')) {
2293 // Debug instance is there?
2294 if (!is_null($this->getDebugInstance())) {
2295 // Output stub message
2296 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2299 trigger_error($message . "<br />\n");
2303 // @TODO Finish this part!
2304 $this->partialStub('Developer mode inactive. Message:' . $message);
2309 * Checks whether the given PHP extension is loaded
2311 * @param $phpExtension The PHP extension we shall check
2312 * @return $isLoaded Whether the PHP extension is loaded
2314 public final function isPhpExtensionLoaded ($phpExtension) {
2316 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2323 * "Getter" as a time() replacement but with milliseconds. You should use this
2324 * method instead of the encapsulated getimeofday() function.
2326 * @return $milliTime Timestamp with milliseconds
2328 public function getMilliTime () {
2329 // Get the time of day as float
2330 $milliTime = gettimeofday(TRUE);
2337 * Idles (sleeps) for given milliseconds
2339 * @return $hasSlept Whether it goes fine
2341 public function idle ($milliSeconds) {
2342 // Sleep is fine by default
2345 // Idle so long with found function
2346 if (function_exists('time_sleep_until')) {
2347 // Get current time and add idle time
2348 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2350 // New PHP 5.1.0 function found, ignore errors
2351 $hasSlept = @time_sleep_until($sleepUntil);
2354 * My Sun station doesn't have that function even with latest PHP
2357 usleep($milliSeconds * 1000);
2364 * Converts a hexadecimal string, even with negative sign as first string to
2365 * a decimal number using BC functions.
2367 * This work is based on comment #86673 on php.net documentation page at:
2368 * <http://de.php.net/manual/en/function.dechex.php#86673>
2370 * @param $hex Hexadecimal string
2371 * @return $dec Decimal number
2373 protected function hex2dec ($hex) {
2374 // Convert to all lower-case
2375 $hex = strtolower($hex);
2377 // Detect sign (negative/positive numbers)
2379 if (substr($hex, 0, 1) == '-') {
2381 $hex = substr($hex, 1);
2384 // Decode the hexadecimal string into a decimal number
2386 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2387 $factor = self::$hexdec[substr($hex, $i, 1)];
2388 $dec = bcadd($dec, bcmul($factor, $e));
2391 // Return the decimal number
2392 return $sign . $dec;
2396 * Converts even very large decimal numbers, also signed, to a hexadecimal
2399 * This work is based on comment #97756 on php.net documentation page at:
2400 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2402 * @param $dec Decimal number, even with negative sign
2403 * @param $maxLength Optional maximum length of the string
2404 * @return $hex Hexadecimal string
2406 protected function dec2hex ($dec, $maxLength = 0) {
2407 // maxLength can be zero or devideable by 2
2408 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2410 // Detect sign (negative/positive numbers)
2417 // Encode the decimal number into a hexadecimal string
2420 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2422 } while ($dec >= 1);
2425 * Leading zeros are required for hex-decimal "numbers". In some
2426 * situations more leading zeros are wanted, so check for both
2429 if ($maxLength > 0) {
2430 // Prepend more zeros
2431 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2432 } elseif ((strlen($hex) % 2) != 0) {
2433 // Only make string's length dividable by 2
2437 // Return the hexadecimal string
2438 return $sign . $hex;
2442 * Converts a ASCII string (0 to 255) into a decimal number.
2444 * @param $asc The ASCII string to be converted
2445 * @return $dec Decimal number
2447 protected function asc2dec ($asc) {
2448 // Convert it into a hexadecimal number
2449 $hex = bin2hex($asc);
2451 // And back into a decimal number
2452 $dec = $this->hex2dec($hex);
2459 * Converts a decimal number into an ASCII string.
2461 * @param $dec Decimal number
2462 * @return $asc An ASCII string
2464 protected function dec2asc ($dec) {
2465 // First convert the number into a hexadecimal string
2466 $hex = $this->dec2hex($dec);
2468 // Then convert it into the ASCII string
2469 $asc = $this->hex2asc($hex);
2476 * Converts a hexadecimal number into an ASCII string. Negative numbers
2479 * @param $hex Hexadecimal string
2480 * @return $asc An ASCII string
2482 protected function hex2asc ($hex) {
2483 // Check for length, it must be devideable by 2
2484 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2485 assert((strlen($hex) % 2) == 0);
2489 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2490 // Get the decimal number of the chunk
2491 $part = hexdec(substr($hex, $idx, 2));
2493 // Add it to the final string
2497 // Return the final string
2502 * Checks whether the given encoded data was encoded with Base64
2504 * @param $encodedData Encoded data we shall check
2505 * @return $isBase64 Whether the encoded data is Base64
2507 protected function isBase64Encoded ($encodedData) {
2509 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2516 * "Getter" to get response/request type from analysis of the system.
2518 * @return $responseType Analyzed response type
2520 protected static function getResponseTypeFromSystem () {
2521 // Default is console
2522 $responseType = 'console';
2524 // Is 'HTTP_HOST' set?
2525 if (isset($_SERVER['HTTP_HOST'])) {
2527 * Then it is a HTML response/request as RSS and so on may be
2528 * transfered over HTTP as well.
2530 $responseType = 'html';
2534 return $responseType;
2538 * Gets a cache key from Criteria instance
2540 * @param $criteriaInstance An instance of a Criteria class
2541 * @param $onlyKeys Only use these keys for a cache key
2542 * @return $cacheKey A cache key suitable for lookup/storage purposes
2544 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2546 $cacheKey = sprintf('%s@%s',
2547 $this->__toString(),
2548 $criteriaInstance->getCacheKey($onlyKeys)
2552 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2557 * Getter for startup time in miliseconds
2559 * @return $startupTime Startup time in miliseconds
2561 protected function getStartupTime () {
2562 return self::$startupTime;
2566 * "Getter" for a printable currently execution time in nice braces
2568 * @return $executionTime Current execution time in nice braces
2570 protected function getPrintableExecutionTime () {
2571 // Caculate the execution time
2572 $executionTime = microtime(TRUE) - $this->getStartupTime();
2574 // Pack it in nice braces
2575 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2578 return $executionTime;
2582 * Hashes a given string with a simple but stronger hash function (no salt)
2583 * and hex-encode it.
2585 * @param $str The string to be hashed
2586 * @return $hash The hash from string $str
2588 public static final function hash ($str) {
2589 // Hash given string with (better secure) hasher
2590 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2597 * "Getter" for length of hash() output. This will be "cached" to speed up
2600 * @return $length Length of hash() output
2602 public static final function getHashLength () {
2604 if (is_null(self::$hashLength)) {
2605 // No, then hash a string and save its length.
2606 self::$hashLength = strlen(self::hash('abc123'));
2610 return self::$hashLength;
2614 * Checks whether the given number is really a number (only chars 0-9).
2616 * @param $num A string consisting only chars between 0 and 9
2617 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2618 * @param $assertMismatch Whether to assert mismatches
2619 * @return $ret The (hopefully) secured numbered value
2621 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2622 // Filter all numbers out
2623 $ret = preg_replace('/[^0123456789]/', '', $num);
2626 if ($castValue === TRUE) {
2627 // Cast to biggest numeric type
2628 $ret = (double) $ret;
2631 // Assert only if requested
2632 if ($assertMismatch === TRUE) {
2633 // Has the whole value changed?
2634 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2642 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2644 * @param $num A string consisting only chars between 0 and 9
2645 * @param $assertMismatch Whether to assert mismatches
2646 * @return $ret The (hopefully) secured hext-numbered value
2648 public function hexval ($num, $assertMismatch = FALSE) {
2649 // Filter all numbers out
2650 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2652 // Assert only if requested
2653 if ($assertMismatch === TRUE) {
2654 // Has the whole value changed?
2655 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2663 * Checks whether start/end marker are set
2665 * @param $data Data to be checked
2666 * @return $isset Whether start/end marker are set
2668 public final function ifStartEndMarkersSet ($data) {
2670 $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));
2672 // ... and return it
2677 * Determines if an element is set in the generic array
2679 * @param $keyGroup Main group for the key
2680 * @param $subGroup Sub group for the key
2681 * @param $key Key to check
2682 * @param $element Element to check
2683 * @return $isset Whether the given key is set
2685 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2687 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2690 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2696 * Determines if a key is set in the generic array
2698 * @param $keyGroup Main group for the key
2699 * @param $subGroup Sub group for the key
2700 * @param $key Key to check
2701 * @return $isset Whether the given key is set
2703 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2705 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2708 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2716 * Determines if a group is set in the generic array
2718 * @param $keyGroup Main group
2719 * @param $subGroup Sub group
2720 * @return $isset Whether the given group is set
2722 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2724 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2727 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2734 * Getter for sub key group
2736 * @param $keyGroup Main key group
2737 * @param $subGroup Sub key group
2738 * @return $array An array with all array elements
2740 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2742 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2743 // No, then abort here
2744 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2749 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2752 return $this->genericArray[$keyGroup][$subGroup];
2756 * Unsets a given key in generic array
2758 * @param $keyGroup Main group for the key
2759 * @param $subGroup Sub group for the key
2760 * @param $key Key to unset
2763 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2765 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2768 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2772 * Unsets a given element in generic array
2774 * @param $keyGroup Main group for the key
2775 * @param $subGroup Sub group for the key
2776 * @param $key Key to unset
2777 * @param $element Element to unset
2780 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2782 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2785 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2789 * Append a string to a given generic array key
2791 * @param $keyGroup Main group for the key
2792 * @param $subGroup Sub group for the key
2793 * @param $key Key to unset
2794 * @param $value Value to add/append
2797 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2799 //* 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);
2801 // Is it already there?
2802 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2804 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2807 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2812 * Append a string to a given generic array element
2814 * @param $keyGroup Main group for the key
2815 * @param $subGroup Sub group for the key
2816 * @param $key Key to unset
2817 * @param $element Element to check
2818 * @param $value Value to add/append
2821 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2823 //* 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);
2825 // Is it already there?
2826 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2828 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2831 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2836 * Sets a string in a given generic array element
2838 * @param $keyGroup Main group for the key
2839 * @param $subGroup Sub group for the key
2840 * @param $key Key to unset
2841 * @param $element Element to check
2842 * @param $value Value to add/append
2845 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2847 //* 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);
2850 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2854 * Initializes given generic array group
2856 * @param $keyGroup Main group for the key
2857 * @param $subGroup Sub group for the key
2858 * @param $key Key to use
2859 * @param $forceInit Optionally force initialization
2862 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2864 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2866 // Is it already set?
2867 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2868 // Already initialized
2869 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2874 $this->genericArray[$keyGroup][$subGroup] = array();
2878 * Initializes given generic array key
2880 * @param $keyGroup Main group for the key
2881 * @param $subGroup Sub group for the key
2882 * @param $key Key to use
2883 * @param $forceInit Optionally force initialization
2886 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2888 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2890 // Is it already set?
2891 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2892 // Already initialized
2893 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2898 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2902 * Initializes given generic array element
2904 * @param $keyGroup Main group for the key
2905 * @param $subGroup Sub group for the key
2906 * @param $key Key to use
2907 * @param $element Element to use
2908 * @param $forceInit Optionally force initialization
2911 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2913 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2915 // Is it already set?
2916 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2917 // Already initialized
2918 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2923 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2927 * Pushes an element to a generic key
2929 * @param $keyGroup Main group for the key
2930 * @param $subGroup Sub group for the key
2931 * @param $key Key to use
2932 * @param $value Value to add/append
2933 * @return $count Number of array elements
2935 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2937 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2940 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2942 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2946 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2949 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2950 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2955 * Pushes an element to a generic array element
2957 * @param $keyGroup Main group for the key
2958 * @param $subGroup Sub group for the key
2959 * @param $key Key to use
2960 * @param $element Element to check
2961 * @param $value Value to add/append
2962 * @return $count Number of array elements
2964 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2966 //* 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));
2969 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2971 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2975 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2978 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2979 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2984 * Pops an element from a generic group
2986 * @param $keyGroup Main group for the key
2987 * @param $subGroup Sub group for the key
2988 * @param $key Key to unset
2989 * @return $value Last "popped" value
2991 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2993 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2996 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2998 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3003 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
3006 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3007 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3012 * Shifts an element from a generic group
3014 * @param $keyGroup Main group for the key
3015 * @param $subGroup Sub group for the key
3016 * @param $key Key to unset
3017 * @return $value Last "popped" value
3019 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3021 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3024 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3026 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3031 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3034 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3035 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3040 * Count generic array group
3042 * @param $keyGroup Main group for the key
3043 * @return $count Count of given group
3045 protected final function countGenericArray ($keyGroup) {
3047 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3050 if (!isset($this->genericArray[$keyGroup])) {
3052 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3057 $count = count($this->genericArray[$keyGroup]);
3060 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3067 * Count generic array sub group
3069 * @param $keyGroup Main group for the key
3070 * @param $subGroup Sub group for the key
3071 * @return $count Count of given group
3073 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3075 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3078 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3080 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3085 $count = count($this->genericArray[$keyGroup][$subGroup]);
3088 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3095 * Count generic array elements
3097 * @param $keyGroup Main group for the key
3098 * @param $subGroup Sub group for the key
3099 * @para $key Key to count
3100 * @return $count Count of given key
3102 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3104 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3107 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3109 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3111 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3113 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3118 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3121 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3128 * Getter for whole generic group array
3130 * @param $keyGroup Key group to get
3131 * @return $array Whole generic array group
3133 protected final function getGenericArray ($keyGroup) {
3135 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3138 if (!isset($this->genericArray[$keyGroup])) {
3140 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3145 return $this->genericArray[$keyGroup];
3149 * Setter for generic array key
3151 * @param $keyGroup Key group to get
3152 * @param $subGroup Sub group for the key
3153 * @param $key Key to unset
3154 * @param $value Mixed value from generic array element
3157 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3159 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3162 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3166 * Getter for generic array key
3168 * @param $keyGroup Key group to get
3169 * @param $subGroup Sub group for the key
3170 * @param $key Key to unset
3171 * @return $value Mixed value from generic array element
3173 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3175 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3178 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3180 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3185 return $this->genericArray[$keyGroup][$subGroup][$key];
3189 * Sets a value in given generic array key/element
3191 * @param $keyGroup Main group for the key
3192 * @param $subGroup Sub group for the key
3193 * @param $key Key to set
3194 * @param $element Element to set
3195 * @param $value Value to set
3198 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3200 //* 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));
3203 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3207 * Getter for generic array element
3209 * @param $keyGroup Key group to get
3210 * @param $subGroup Sub group for the key
3211 * @param $key Key to look for
3212 * @param $element Element to look for
3213 * @return $value Mixed value from generic array element
3215 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3217 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3220 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3222 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3227 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3231 * Checks if a given sub group is valid (array)
3233 * @param $keyGroup Key group to get
3234 * @param $subGroup Sub group for the key
3235 * @return $isValid Whether given sub group is valid
3237 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3239 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3242 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3249 * Checks if a given key is valid (array)
3251 * @param $keyGroup Key group to get
3252 * @param $subGroup Sub group for the key
3253 * @param $key Key to check
3254 * @return $isValid Whether given sub group is valid
3256 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3258 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3261 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3268 * Initializes the web output instance
3272 protected function initWebOutputInstance () {
3273 // Get application instance
3274 $applicationInstance = Registry::getRegistry()->getInstance('app');
3276 // Is this a response instance?
3277 if ($this instanceof Responseable) {
3278 // Then set it in application instance
3279 $applicationInstance->setResponseInstance($this);
3282 // Init web output instance
3283 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3286 $this->setWebOutputInstance($outputInstance);
3290 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3292 * @param $boolean Boolean value
3293 * @return $translated Translated boolean value
3295 public static final function translateBooleanToYesNo ($boolean) {
3296 // Make sure it is really boolean
3297 assert(is_bool($boolean));
3300 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3302 // ... and return it
3307 * Encodes raw data (almost any type) by "serializing" it and then pack it
3308 * into a "binary format".
3310 * @param $rawData Raw data (almost any type)
3311 * @return $encoded Encoded data
3313 protected function encodeData ($rawData) {
3314 // Make sure no objects or resources pass through
3315 assert(!is_object($rawData));
3316 assert(!is_resource($rawData));
3318 // First "serialize" it (json_encode() is faster than serialize())
3319 $encoded = $this->packString(json_encode($rawData));
3326 * Pack a string into a "binary format". Please execuse me that this is
3327 * widely undocumented. :-(
3329 * @param $str Unpacked string
3330 * @return $packed Packed string
3331 * @todo Improve documentation
3333 protected function packString ($str) {
3335 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3337 // First compress the string (gzcompress is okay)
3338 $str = gzcompress($str);
3343 // And start the "encoding" loop
3344 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3346 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3347 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3349 if (($idx + $i) <= strlen($str)) {
3350 $ord = ord(substr($str, ($idx + $i), 1));
3352 $add = $ord * pow(256, $factor);
3356 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3360 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3361 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3363 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3364 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3370 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3375 * Checks whether the given file/path is in open_basedir(). This does not
3376 * gurantee that the file is actually readable and/or writeable. If you need
3377 * such gurantee then please use isReadableFile() instead.
3379 * @param $filePathName Name of the file/path to be checked
3380 * @return $isReachable Whether it is within open_basedir()
3382 protected static function isReachableFilePath ($filePathName) {
3383 // Is not reachable by default
3384 $isReachable = FALSE;
3386 // Get open_basedir parameter
3387 $openBaseDir = ini_get('open_basedir');
3390 if (!empty($openBaseDir)) {
3391 // Check all entries
3392 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3393 // Check on existence
3394 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3396 $isReachable = TRUE;
3400 // If open_basedir is not set, all is allowed
3401 $isReachable = TRUE;
3405 return $isReachable;
3409 * Checks whether the give file is within open_basedir() (done by
3410 * isReachableFilePath()), is actually a file and is readable.
3412 * @param $fileName Name of the file to be checked
3413 * @return $isReadable Whether the file is readable (and therefor exists)
3415 public static function isReadableFile ($fileName) {
3416 // Default is not readable
3417 $isReadable = FALSE;
3419 // Is within parameters, so check if it is a file and readable
3420 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3427 * Creates a full-qualified file name (FQFN) for given file name by adding
3428 * a configured temporary file path to it.
3430 * @param $fileName Name for temporary file
3431 * @return $fqfn Full-qualified file name
3432 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3433 * @throws FileIoException If the file cannot be written
3435 protected static function createTempPathForFile ($fileName) {
3437 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3439 // Is the path writeable?
3440 if (!is_writable($basePath)) {
3441 // Path is write-protected
3442 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3446 $fqfn = $basePath . '/' . $fileName;
3449 if (!self::isReachableFilePath($fqfn)) {
3451 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3459 * "Getter" for a printable state name
3461 * @return $stateName Name of the node's state in a printable format
3463 public final function getPrintableState () {
3464 // Default is 'null'
3465 $stateName = 'null';
3467 // Get the state instance
3468 $stateInstance = $this->getStateInstance();
3470 // Is it an instance of Stateable?
3471 if ($stateInstance instanceof Stateable) {
3472 // Then use that state name
3473 $stateName = $stateInstance->getStateName();
3481 * Handles socket error for given socket resource and peer data. This method
3482 * validates $socketResource if it is a valid resource (see is_resource())
3483 * but assumes valid data in array $recipientData, except that
3484 * count($recipientData) is always 2.
3486 * @param $method Value of __METHOD__ from calling method
3487 * @param $line Value of __LINE__ from calling method
3488 * @param $socketResource A valid socket resource
3489 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3491 * @throws InvalidSocketException If $socketResource is no socket resource
3492 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3493 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3495 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3496 // This method handles only socket resources
3497 if (!is_resource($socketResource)) {
3498 // No resource, abort here
3499 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3502 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3503 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3504 assert(isset($socketData[0]));
3505 assert(isset($socketData[1]));
3507 // Get error code for first validation (0 is not an error)
3508 $errorCode = socket_last_error($socketResource);
3510 // If the error code is zero, someone called this method without an error
3511 if ($errorCode == 0) {
3512 // No error detected (or previously cleared outside this method)
3513 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3516 // Get handler (method) name
3517 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3519 // Call-back the error handler method
3520 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3522 // Finally clear the error because it has been handled
3523 socket_clear_error($socketResource);