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\Factory\Database\Wrapper\DatabaseWrapperFactory;
13 use CoreFramework\Factory\ObjectFactory;
14 use CoreFramework\Filesystem\FrameworkDirectory;
15 use CoreFramework\Generic\FrameworkInterface;
16 use CoreFramework\Generic\NullPointerException;
17 use CoreFramework\Handler\Stream\IoHandler;
18 use CoreFramework\Loader\ClassLoader;
19 use CoreFramework\Manager\ManageableApplication;
20 use CoreFramework\Middleware\Compressor\CompressorChannel;
21 use CoreFramework\Middleware\Debug\DebugMiddleware;
22 use CoreFramework\Registry\Register;
23 use CoreFramework\Registry\Registry;
24 use CoreFramework\Request\Requestable;
25 use CoreFramework\Resolver\Resolver;
26 use CoreFramework\Result\Database\CachedDatabaseResult;
27 use CoreFramework\Result\Search\SearchableResult;
28 use CoreFramework\Response\Responseable;
29 use CoreFramework\Stream\Output\OutputStreamer;
30 use CoreFramework\Template\CompileableTemplate;
36 * The simulator system class is the super class of all other classes. This
37 * class handles saving of games etc.
39 * @author Roland Haeder <webmaster@shipsimu.org>
41 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
42 * @license GNU GPL 3.0 or any newer version
43 * @link http://www.shipsimu.org
45 * This program is free software: you can redistribute it and/or modify
46 * it under the terms of the GNU General Public License as published by
47 * the Free Software Foundation, either version 3 of the License, or
48 * (at your option) any later version.
50 * This program is distributed in the hope that it will be useful,
51 * but WITHOUT ANY WARRANTY; without even the implied warranty of
52 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
53 * GNU General Public License for more details.
55 * You should have received a copy of the GNU General Public License
56 * along with this program. If not, see <http://www.gnu.org/licenses/>.
58 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
60 * Length of output from hash()
62 private static $hashLength = NULL;
67 private $realClass = 'BaseFrameworkSystem';
70 * Instance of a Requestable class
72 private $requestInstance = NULL;
75 * Instance of a Responseable class
77 private $responseInstance = NULL;
80 * Search criteria instance
82 private $searchInstance = NULL;
85 * Update criteria instance
87 private $updateInstance = NULL;
90 * The file I/O instance for the template loader
92 private $fileIoInstance = NULL;
97 private $resolverInstance = NULL;
100 * Template engine instance
102 private $templateInstance = NULL;
105 * Database result instance
107 private $resultInstance = NULL;
110 * Instance for user class
112 private $userInstance = NULL;
115 * A controller instance
117 private $controllerInstance = NULL;
122 private $rngInstance = NULL;
125 * Instance of a crypto helper
127 private $cryptoInstance = NULL;
130 * Instance of an Iterator class
132 private $iteratorInstance = NULL;
135 * Instance of the list
137 private $listInstance = NULL;
142 private $menuInstance = NULL;
145 * Instance of the image
147 private $imageInstance = NULL;
150 * Instance of the stacker
152 private $stackInstance = NULL;
155 * A Compressor instance
157 private $compressorInstance = NULL;
160 * A Parseable instance
162 private $parserInstance = NULL;
165 * A HandleableProtocol instance
167 private $protocolInstance = NULL;
170 * A database wrapper instance
172 private $databaseInstance = NULL;
175 * A helper instance for the form
177 private $helperInstance = NULL;
180 * An instance of a Source class
182 private $sourceInstance = NULL;
185 * An instance of a UrlSource class
187 private $urlSourceInstance = NULL;
190 * An instance of a InputStream class
192 private $inputStreamInstance = NULL;
195 * An instance of a OutputStream class
197 private $outputStreamInstance = NULL;
200 * Networkable handler instance
202 private $handlerInstance = NULL;
205 * Visitor handler instance
207 private $visitorInstance = NULL;
212 private $dhtInstance = NULL;
215 * An instance of a database wrapper class
217 private $wrapperInstance = NULL;
220 * An instance of a file I/O pointer class (not handler)
222 private $pointerInstance = NULL;
225 * An instance of an Indexable class
227 private $indexInstance = NULL;
230 * An instance of a Block class
232 private $blockInstance = NULL;
237 private $minableInstance = NULL;
240 * A FrameworkDirectory instance
242 private $directoryInstance = NULL;
247 private $listenerInstance = NULL;
250 * An instance of a communicator
252 private $communicatorInstance = NULL;
255 * The concrete output instance
257 private $outputInstance = NULL;
262 private $stateInstance = NULL;
265 * Thousands separator
267 private $thousands = '.'; // German
272 private $decimals = ','; // German
277 private $socketResource = FALSE;
280 * Regular expression to use for validation
282 private $regularExpression = '';
287 private $packageData = array();
292 private $genericArray = array();
297 private $commandName = '';
302 private $controllerName = '';
305 * Name of used protocol
307 private $protocolName = 'invalid';
310 * Array with bitmasks and such for pack/unpack methods to support both
311 * 32-bit and 64-bit systems
313 private $packingData = array(
316 'left' => 0xffff0000,
317 'right' => 0x0000ffff,
323 'left' => 0xffffffff00000000,
324 'right' => 0x00000000ffffffff,
331 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
333 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
335 private $archArrayElement = FALSE;
337 /***********************
338 * Exception codes.... *
339 ***********************/
341 // @todo Try to clean these constants up
342 const EXCEPTION_IS_NULL_POINTER = 0x001;
343 const EXCEPTION_IS_NO_OBJECT = 0x002;
344 const EXCEPTION_IS_NO_ARRAY = 0x003;
345 const EXCEPTION_MISSING_METHOD = 0x004;
346 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
347 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
348 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
349 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
350 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
351 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
352 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
353 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
354 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
355 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
356 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
357 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
358 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
359 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
360 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
361 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
362 const EXCEPTION_PATH_NOT_FOUND = 0x015;
363 const EXCEPTION_INVALID_PATH_NAME = 0x016;
364 const EXCEPTION_READ_PROTECED_PATH = 0x017;
365 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
366 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
367 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
368 const EXCEPTION_INVALID_RESOURCE = 0x01b;
369 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
370 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
371 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
372 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
373 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
374 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
375 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
376 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
377 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
378 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
379 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
380 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
381 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
382 const EXCEPTION_INVALID_STRING = 0x029;
383 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
384 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
385 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
386 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
387 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
388 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
389 const EXCEPTION_MISSING_ELEMENT = 0x030;
390 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
391 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
392 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
393 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
394 const EXCEPTION_FATAL_ERROR = 0x035;
395 const EXCEPTION_FILE_NOT_FOUND = 0x036;
396 const EXCEPTION_ASSERTION_FAILED = 0x037;
397 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
398 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
399 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
400 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
401 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
402 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
405 * Hexadecimal->Decimal translation array
407 private static $hexdec = array(
427 * Decimal->hexadecimal translation array
429 private static $dechex = array(
449 * Startup time in miliseconds
451 private static $startupTime = 0;
454 * Protected super constructor
456 * @param $className Name of the class
459 protected function __construct ($className) {
461 $this->setRealClass($className);
463 // Set configuration instance if no registry ...
464 if (!$this instanceof Register) {
465 // ... because registries doesn't need to be configured
466 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
469 // Is the startup time set? (0 cannot be TRUE anymore)
470 if (self::$startupTime == 0) {
472 self::$startupTime = microtime(TRUE);
476 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
480 * Destructor for all classes. You should not call this method on your own.
484 public function __destruct () {
485 // Flush any updated entries to the database
486 $this->flushPendingUpdates();
488 // Is this object already destroyed?
489 if ($this->__toString() != 'DestructedObject') {
490 // Destroy all informations about this class but keep some text about it alive
491 $this->setRealClass('DestructedObject');
492 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
493 // Already destructed object
494 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
499 // Do not call this twice
500 trigger_error(__METHOD__ . ': Called twice.');
506 * The __call() method where all non-implemented methods end up
508 * @param $methodName Name of the missing method
509 * @args $args Arguments passed to the method
512 public final function __call ($methodName, $args) {
513 return self::__callStatic($methodName, $args);
517 * The __callStatic() method where all non-implemented static methods end up
519 * @param $methodName Name of the missing method
520 * @args $args Arguments passed to the method
523 public static final function __callStatic ($methodName, $args) {
525 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
527 // Init argument string
530 // Is it NULL, empty or an array?
531 if (is_null($args)) {
533 $argsString = 'NULL';
534 } elseif (is_array($args)) {
538 // Some arguments are there
539 foreach ($args as $arg) {
540 // Add data about the argument
541 $argsString .= gettype($arg) . ':';
544 // Found a NULL argument
545 $argsString .= 'NULL';
546 } elseif (is_string($arg)) {
547 // Add length for strings
548 $argsString .= strlen($arg);
549 } elseif ((is_int($arg)) || (is_float($arg))) {
552 } elseif (is_array($arg)) {
553 // .. or size if array
554 $argsString .= count($arg);
555 } elseif (is_object($arg)) {
557 $reflection = new ReflectionClass($arg);
559 // Is an other object, maybe no __toString() available
560 $argsString .= $reflection->getName();
561 } elseif ($arg === TRUE) {
562 // ... is boolean 'TRUE'
563 $argsString .= 'TRUE';
564 } elseif ($arg === FALSE) {
565 // ... is boolean 'FALSE'
566 $argsString .= 'FALSE';
569 // Comma for next one
574 if (substr($argsString, -2, 1) == ',') {
575 $argsString = substr($argsString, 0, -2);
581 // Invalid arguments!
582 $argsString = '!INVALID:' . gettype($args) . '!';
585 // Output stub message
586 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
587 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
597 * Getter for $realClass
599 * @return $realClass The name of the real class (not BaseFrameworkSystem)
601 public function __toString () {
602 return $this->realClass;
606 * Magic method to catch setting of missing but set class fields/attributes
608 * @param $name Name of the field/attribute
609 * @param $value Value to store
612 public final function __set ($name, $value) {
613 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
616 print_r($value, TRUE)
621 * Magic method to catch getting of missing fields/attributes
623 * @param $name Name of the field/attribute
626 public final function __get ($name) {
627 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
633 * Magic method to catch unsetting of missing fields/attributes
635 * @param $name Name of the field/attribute
638 public final function __unset ($name) {
639 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
645 * Magic method to catch object serialization
647 * @return $unsupported Unsupported method
648 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
650 public final function __sleep () {
651 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
655 * Magic method to catch object deserialization
657 * @return $unsupported Unsupported method
658 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
660 public final function __wakeup () {
661 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
665 * Magic method to catch calls when an object instance is called
667 * @return $unsupported Unsupported method
668 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
670 public final function __invoke () {
671 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
675 * Setter for the real class name
677 * @param $realClass Class name (string)
680 public final function setRealClass ($realClass) {
682 $this->realClass = (string) $realClass;
686 * Setter for database result instance
688 * @param $resultInstance An instance of a database result class
690 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
692 protected final function setResultInstance (SearchableResult $resultInstance) {
693 $this->resultInstance = $resultInstance;
697 * Getter for database result instance
699 * @return $resultInstance An instance of a database result class
701 public final function getResultInstance () {
702 return $this->resultInstance;
706 * Setter for template engine instances
708 * @param $templateInstance An instance of a template engine class
711 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
712 $this->templateInstance = $templateInstance;
716 * Getter for template engine instances
718 * @return $templateInstance An instance of a template engine class
720 protected final function getTemplateInstance () {
721 return $this->templateInstance;
725 * Setter for search instance
727 * @param $searchInstance Searchable criteria instance
730 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
731 $this->searchInstance = $searchInstance;
735 * Getter for search instance
737 * @return $searchInstance Searchable criteria instance
739 public final function getSearchInstance () {
740 return $this->searchInstance;
744 * Setter for update instance
746 * @param $updateInstance Searchable criteria instance
749 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
750 $this->updateInstance = $updateInstance;
754 * Getter for update instance
756 * @return $updateInstance Updateable criteria instance
758 public final function getUpdateInstance () {
759 return $this->updateInstance;
763 * Setter for resolver instance
765 * @param $resolverInstance Instance of a command resolver class
768 public final function setResolverInstance (Resolver $resolverInstance) {
769 $this->resolverInstance = $resolverInstance;
773 * Getter for resolver instance
775 * @return $resolverInstance Instance of a command resolver class
777 public final function getResolverInstance () {
778 return $this->resolverInstance;
782 * Setter for language instance
784 * @param $configInstance The configuration instance which shall
785 * be FrameworkConfiguration
788 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
789 Registry::getRegistry()->addInstance('config', $configInstance);
793 * Getter for configuration instance
795 * @return $configInstance Configuration instance
797 public final function getConfigInstance () {
798 $configInstance = Registry::getRegistry()->getInstance('config');
799 return $configInstance;
803 * Setter for debug instance
805 * @param $debugInstance The instance for debug output class
808 public final function setDebugInstance (DebugMiddleware $debugInstance) {
809 Registry::getRegistry()->addInstance('debug', $debugInstance);
813 * Getter for debug instance
815 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
817 public final function getDebugInstance () {
818 // Get debug instance
819 $debugInstance = Registry::getRegistry()->getInstance('debug');
822 return $debugInstance;
826 * Setter for web output instance
828 * @param $webInstance The instance for web output class
831 public final function setWebOutputInstance (OutputStreamer $webInstance) {
832 Registry::getRegistry()->addInstance('web_output', $webInstance);
836 * Getter for web output instance
838 * @return $webOutputInstance - Instance to class WebOutput
840 public final function getWebOutputInstance () {
841 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
842 return $webOutputInstance;
846 * Setter for database instance
848 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
851 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
852 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
856 * Getter for database layer
858 * @return $databaseInstance The database layer instance
860 public final function getDatabaseInstance () {
862 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
865 return $databaseInstance;
869 * Setter for compressor channel
871 * @param $compressorInstance An instance of CompressorChannel
874 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
875 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
879 * Getter for compressor channel
881 * @return $compressorInstance The compressor channel
883 public final function getCompressorChannel () {
884 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
885 return $compressorInstance;
889 * Protected getter for a manageable application helper class
891 * @return $applicationInstance An instance of a manageable application helper class
893 protected final function getApplicationInstance () {
894 $applicationInstance = Registry::getRegistry()->getInstance('application');
895 return $applicationInstance;
899 * Setter for a manageable application helper class
901 * @param $applicationInstance An instance of a manageable application helper class
904 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
905 Registry::getRegistry()->addInstance('application', $applicationInstance);
909 * Setter for request instance
911 * @param $requestInstance An instance of a Requestable class
914 public final function setRequestInstance (Requestable $requestInstance) {
915 $this->requestInstance = $requestInstance;
919 * Getter for request instance
921 * @return $requestInstance An instance of a Requestable class
923 public final function getRequestInstance () {
924 return $this->requestInstance;
928 * Setter for response instance
930 * @param $responseInstance An instance of a Responseable class
933 public final function setResponseInstance (Responseable $responseInstance) {
934 $this->responseInstance = $responseInstance;
938 * Getter for response instance
940 * @return $responseInstance An instance of a Responseable class
942 public final function getResponseInstance () {
943 return $this->responseInstance;
947 * Private getter for language instance
949 * @return $langInstance An instance to the language sub-system
951 protected final function getLanguageInstance () {
952 $langInstance = Registry::getRegistry()->getInstance('language');
953 return $langInstance;
957 * Setter for language instance
959 * @param $langInstance An instance to the language sub-system
961 * @see LanguageSystem
963 public final function setLanguageInstance (ManageableLanguage $langInstance) {
964 Registry::getRegistry()->addInstance('language', $langInstance);
968 * Private getter for file IO instance
970 * @return $fileIoInstance An instance to the file I/O sub-system
972 protected final function getFileIoInstance () {
973 return $this->fileIoInstance;
977 * Setter for file I/O instance
979 * @param $fileIoInstance An instance to the file I/O sub-system
982 public final function setFileIoInstance (IoHandler $fileIoInstance) {
983 $this->fileIoInstance = $fileIoInstance;
987 * Protected setter for user instance
989 * @param $userInstance An instance of a user class
992 protected final function setUserInstance (ManageableAccount $userInstance) {
993 $this->userInstance = $userInstance;
997 * Getter for user instance
999 * @return $userInstance An instance of a user class
1001 public final function getUserInstance () {
1002 return $this->userInstance;
1006 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1008 * @param $controllerInstance An instance of the controller
1011 public final function setControllerInstance (Controller $controllerInstance) {
1012 $this->controllerInstance = $controllerInstance;
1016 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1018 * @return $controllerInstance An instance of the controller
1020 public final function getControllerInstance () {
1021 return $this->controllerInstance;
1025 * Setter for RNG instance
1027 * @param $rngInstance An instance of a random number generator (RNG)
1030 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1031 $this->rngInstance = $rngInstance;
1035 * Getter for RNG instance
1037 * @return $rngInstance An instance of a random number generator (RNG)
1039 public final function getRngInstance () {
1040 return $this->rngInstance;
1044 * Setter for Cryptable instance
1046 * @param $cryptoInstance An instance of a Cryptable class
1049 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1050 $this->cryptoInstance = $cryptoInstance;
1054 * Getter for Cryptable instance
1056 * @return $cryptoInstance An instance of a Cryptable class
1058 public final function getCryptoInstance () {
1059 return $this->cryptoInstance;
1063 * Setter for the list instance
1065 * @param $listInstance A list of Listable
1068 protected final function setListInstance (Listable $listInstance) {
1069 $this->listInstance = $listInstance;
1073 * Getter for the list instance
1075 * @return $listInstance A list of Listable
1077 protected final function getListInstance () {
1078 return $this->listInstance;
1082 * Setter for the menu instance
1084 * @param $menuInstance A RenderableMenu instance
1087 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1088 $this->menuInstance = $menuInstance;
1092 * Getter for the menu instance
1094 * @return $menuInstance A RenderableMenu instance
1096 protected final function getMenuInstance () {
1097 return $this->menuInstance;
1101 * Setter for image instance
1103 * @param $imageInstance An instance of an image
1106 public final function setImageInstance (BaseImage $imageInstance) {
1107 $this->imageInstance = $imageInstance;
1111 * Getter for image instance
1113 * @return $imageInstance An instance of an image
1115 public final function getImageInstance () {
1116 return $this->imageInstance;
1120 * Setter for stacker instance
1122 * @param $stackInstance An instance of an stacker
1125 public final function setStackInstance (Stackable $stackInstance) {
1126 $this->stackInstance = $stackInstance;
1130 * Getter for stacker instance
1132 * @return $stackInstance An instance of an stacker
1134 public final function getStackInstance () {
1135 return $this->stackInstance;
1139 * Setter for compressor instance
1141 * @param $compressorInstance An instance of an compressor
1144 public final function setCompressorInstance (Compressor $compressorInstance) {
1145 $this->compressorInstance = $compressorInstance;
1149 * Getter for compressor instance
1151 * @return $compressorInstance An instance of an compressor
1153 public final function getCompressorInstance () {
1154 return $this->compressorInstance;
1158 * Setter for Parseable instance
1160 * @param $parserInstance An instance of an Parseable
1163 public final function setParserInstance (Parseable $parserInstance) {
1164 $this->parserInstance = $parserInstance;
1168 * Getter for Parseable instance
1170 * @return $parserInstance An instance of an Parseable
1172 public final function getParserInstance () {
1173 return $this->parserInstance;
1177 * Setter for HandleableProtocol instance
1179 * @param $protocolInstance An instance of an HandleableProtocol
1182 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1183 $this->protocolInstance = $protocolInstance;
1187 * Getter for HandleableProtocol instance
1189 * @return $protocolInstance An instance of an HandleableProtocol
1191 public final function getProtocolInstance () {
1192 return $this->protocolInstance;
1196 * Setter for DatabaseWrapper instance
1198 * @param $wrapperInstance An instance of an DatabaseWrapper
1201 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1202 $this->wrapperInstance = $wrapperInstance;
1206 * Getter for DatabaseWrapper instance
1208 * @return $wrapperInstance An instance of an DatabaseWrapper
1210 public final function getWrapperInstance () {
1211 return $this->wrapperInstance;
1215 * Setter for socket resource
1217 * @param $socketResource A valid socket resource
1220 public final function setSocketResource ($socketResource) {
1221 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1222 $this->socketResource = $socketResource;
1226 * Getter for socket resource
1228 * @return $socketResource A valid socket resource
1230 public final function getSocketResource () {
1231 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1232 return $this->socketResource;
1236 * Setter for regular expression
1238 * @param $regularExpression A valid regular expression
1241 public final function setRegularExpression ($regularExpression) {
1242 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1243 $this->regularExpression = $regularExpression;
1247 * Getter for regular expression
1249 * @return $regularExpression A valid regular expression
1251 public final function getRegularExpression () {
1252 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1253 return $this->regularExpression;
1257 * Setter for helper instance
1259 * @param $helperInstance An instance of a helper class
1262 protected final function setHelperInstance (Helper $helperInstance) {
1263 $this->helperInstance = $helperInstance;
1267 * Getter for helper instance
1269 * @return $helperInstance An instance of a helper class
1271 public final function getHelperInstance () {
1272 return $this->helperInstance;
1276 * Setter for a Source instance
1278 * @param $sourceInstance An instance of a Source class
1281 protected final function setSourceInstance (Source $sourceInstance) {
1282 $this->sourceInstance = $sourceInstance;
1286 * Getter for a Source instance
1288 * @return $sourceInstance An instance of a Source class
1290 protected final function getSourceInstance () {
1291 return $this->sourceInstance;
1295 * Setter for a UrlSource instance
1297 * @param $sourceInstance An instance of a UrlSource class
1300 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1301 $this->urlSourceInstance = $urlSourceInstance;
1305 * Getter for a UrlSource instance
1307 * @return $urlSourceInstance An instance of a UrlSource class
1309 protected final function getUrlSourceInstance () {
1310 return $this->urlSourceInstance;
1314 * Getter for a InputStream instance
1316 * @param $inputStreamInstance The InputStream instance
1318 protected final function getInputStreamInstance () {
1319 return $this->inputStreamInstance;
1323 * Setter for a InputStream instance
1325 * @param $inputStreamInstance The InputStream instance
1328 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1329 $this->inputStreamInstance = $inputStreamInstance;
1333 * Getter for a OutputStream instance
1335 * @param $outputStreamInstance The OutputStream instance
1337 protected final function getOutputStreamInstance () {
1338 return $this->outputStreamInstance;
1342 * Setter for a OutputStream instance
1344 * @param $outputStreamInstance The OutputStream instance
1347 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1348 $this->outputStreamInstance = $outputStreamInstance;
1352 * Setter for handler instance
1354 * @param $handlerInstance An instance of a Handleable class
1357 protected final function setHandlerInstance (Handleable $handlerInstance) {
1358 $this->handlerInstance = $handlerInstance;
1362 * Getter for handler instance
1364 * @return $handlerInstance A Networkable instance
1366 protected final function getHandlerInstance () {
1367 return $this->handlerInstance;
1371 * Setter for visitor instance
1373 * @param $visitorInstance A Visitor instance
1376 protected final function setVisitorInstance (Visitor $visitorInstance) {
1377 $this->visitorInstance = $visitorInstance;
1381 * Getter for visitor instance
1383 * @return $visitorInstance A Visitor instance
1385 protected final function getVisitorInstance () {
1386 return $this->visitorInstance;
1390 * Setter for DHT instance
1392 * @param $dhtInstance A Distributable instance
1395 protected final function setDhtInstance (Distributable $dhtInstance) {
1396 $this->dhtInstance = $dhtInstance;
1400 * Getter for DHT instance
1402 * @return $dhtInstance A Distributable instance
1404 protected final function getDhtInstance () {
1405 return $this->dhtInstance;
1409 * Setter for raw package Data
1411 * @param $packageData Raw package Data
1414 public final function setPackageData (array $packageData) {
1415 $this->packageData = $packageData;
1419 * Getter for raw package Data
1421 * @return $packageData Raw package Data
1423 public function getPackageData () {
1424 return $this->packageData;
1429 * Setter for Iterator instance
1431 * @param $iteratorInstance An instance of an Iterator
1434 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1435 $this->iteratorInstance = $iteratorInstance;
1439 * Getter for Iterator instance
1441 * @return $iteratorInstance An instance of an Iterator
1443 public final function getIteratorInstance () {
1444 return $this->iteratorInstance;
1448 * Setter for FilePointer instance
1450 * @param $pointerInstance An instance of an FilePointer class
1453 protected final function setPointerInstance (FilePointer $pointerInstance) {
1454 $this->pointerInstance = $pointerInstance;
1458 * Getter for FilePointer instance
1460 * @return $pointerInstance An instance of an FilePointer class
1462 public final function getPointerInstance () {
1463 return $this->pointerInstance;
1467 * Unsets pointer instance which triggers a call of __destruct() if the
1468 * instance is still there. This is surely not fatal on already "closed"
1469 * file pointer instances.
1471 * I don't want to mess around with above setter by giving it a default
1472 * value NULL as setter should always explicitly only set (existing) object
1473 * instances and NULL is NULL.
1477 protected final function unsetPointerInstance () {
1478 // Simply it to NULL
1479 $this->pointerInstance = NULL;
1483 * Setter for Indexable instance
1485 * @param $indexInstance An instance of an Indexable class
1488 protected final function setIndexInstance (Indexable $indexInstance) {
1489 $this->indexInstance = $indexInstance;
1493 * Getter for Indexable instance
1495 * @return $indexInstance An instance of an Indexable class
1497 public final function getIndexInstance () {
1498 return $this->indexInstance;
1502 * Setter for Block instance
1504 * @param $blockInstance An instance of an Block class
1507 protected final function setBlockInstance (Block $blockInstance) {
1508 $this->blockInstance = $blockInstance;
1512 * Getter for Block instance
1514 * @return $blockInstance An instance of an Block class
1516 public final function getBlockInstance () {
1517 return $this->blockInstance;
1521 * Setter for Minable instance
1523 * @param $minableInstance A Minable instance
1526 protected final function setMinableInstance (Minable $minableInstance) {
1527 $this->minableInstance = $minableInstance;
1531 * Getter for minable instance
1533 * @return $minableInstance A Minable instance
1535 protected final function getMinableInstance () {
1536 return $this->minableInstance;
1540 * Setter for FrameworkDirectory instance
1542 * @param $directoryInstance A FrameworkDirectory instance
1545 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1546 $this->directoryInstance = $directoryInstance;
1550 * Getter for FrameworkDirectory instance
1552 * @return $directoryInstance A FrameworkDirectory instance
1554 protected final function getDirectoryInstance () {
1555 return $this->directoryInstance;
1559 * Setter for listener instance
1561 * @param $listenerInstance A Listenable instance
1564 protected final function setListenerInstance (Listenable $listenerInstance) {
1565 $this->listenerInstance = $listenerInstance;
1569 * Getter for listener instance
1571 * @return $listenerInstance A Listenable instance
1573 protected final function getListenerInstance () {
1574 return $this->listenerInstance;
1578 * Getter for communicator instance
1580 * @return $communicatorInstance An instance of a Communicator class
1582 public final function getCommunicatorInstance () {
1583 return $this->communicatorInstance;
1587 * Setter for communicator instance
1589 * @param $communicatorInstance An instance of a Communicator class
1592 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1593 $this->communicatorInstance = $communicatorInstance;
1597 * Setter for state instance
1599 * @param $stateInstance A Stateable instance
1602 public final function setStateInstance (Stateable $stateInstance) {
1603 $this->stateInstance = $stateInstance;
1607 * Getter for state instance
1609 * @return $stateInstance A Stateable instance
1611 public final function getStateInstance () {
1612 return $this->stateInstance;
1616 * Setter for output instance
1618 * @param $outputInstance The debug output instance
1621 public final function setOutputInstance (OutputStreamer $outputInstance) {
1622 $this->outputInstance = $outputInstance;
1626 * Getter for output instance
1628 * @return $outputInstance The debug output instance
1630 public final function getOutputInstance () {
1631 return $this->outputInstance;
1635 * Setter for command name
1637 * @param $commandName Last validated command name
1640 protected final function setCommandName ($commandName) {
1641 $this->commandName = $commandName;
1645 * Getter for command name
1647 * @return $commandName Last validated command name
1649 protected final function getCommandName () {
1650 return $this->commandName;
1654 * Setter for controller name
1656 * @param $controllerName Last validated controller name
1659 protected final function setControllerName ($controllerName) {
1660 $this->controllerName = $controllerName;
1664 * Getter for controller name
1666 * @return $controllerName Last validated controller name
1668 protected final function getControllerName () {
1669 return $this->controllerName;
1673 * Getter for protocol name
1675 * @return $protocolName Name of used protocol
1677 public final function getProtocolName () {
1678 return $this->protocolName;
1682 * Setter for protocol name
1684 * @param $protocolName Name of used protocol
1687 protected final function setProtocolName ($protocolName) {
1688 $this->protocolName = $protocolName;
1692 * Checks whether an object equals this object. You should overwrite this
1693 * method to implement own equality checks
1695 * @param $objectInstance An instance of a FrameworkInterface object
1696 * @return $equals Whether both objects equals
1698 public function equals (FrameworkInterface $objectInstance) {
1701 $this->__toString() == $objectInstance->__toString()
1703 $this->hashCode() == $objectInstance->hashCode()
1706 // Return the result
1711 * Generates a generic hash code of this class. You should really overwrite
1712 * this method with your own hash code generator code. But keep KISS in mind.
1714 * @return $hashCode A generic hash code respresenting this whole class
1716 public function hashCode () {
1718 return crc32($this->__toString());
1722 * Formats computer generated price values into human-understandable formats
1723 * with thousand and decimal separators.
1725 * @param $value The in computer format value for a price
1726 * @param $currency The currency symbol (use HTML-valid characters!)
1727 * @param $decNum Number of decimals after commata
1728 * @return $price The for the current language formated price string
1729 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1730 * thousands separator
1733 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1734 // Are all required attriutes set?
1735 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1736 // Throw an exception
1737 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1741 $value = (float) $value;
1743 // Reformat the US number
1744 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1746 // Return as string...
1751 * Appends a trailing slash to a string
1753 * @param $str A string (maybe) without trailing slash
1754 * @return $str A string with an auto-appended trailing slash
1756 public final function addMissingTrailingSlash ($str) {
1757 // Is there a trailing slash?
1758 if (substr($str, -1, 1) != '/') {
1762 // Return string with trailing slash
1767 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1768 * application helper instance (ApplicationHelper by default).
1770 * @param $applicationInstance An application helper instance or
1771 * null if we shall use the default
1772 * @return $templateInstance The template engine instance
1773 * @throws NullPointerException If the discovered application
1774 * instance is still null
1776 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1777 // Is the application instance set?
1778 if (is_null($applicationInstance)) {
1779 // Get the current instance
1780 $applicationInstance = $this->getApplicationInstance();
1783 if (is_null($applicationInstance)) {
1784 // Thrown an exception
1785 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1789 // Initialize the template engine
1790 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1792 // Return the prepared instance
1793 return $templateInstance;
1797 * Debugs this instance by putting out it's full content
1799 * @param $message Optional message to show in debug output
1802 public final function debugInstance ($message = '') {
1803 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1804 restore_error_handler();
1809 // Is a message set?
1810 if (!empty($message)) {
1811 // Construct message
1812 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1815 // Generate the output
1816 $content .= sprintf('<pre>%s</pre>',
1819 print_r($this, TRUE)
1825 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>',
1826 $this->__toString(),
1828 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1833 * Replaces control characters with printable output
1835 * @param $str String with control characters
1836 * @return $str Replaced string
1838 protected function replaceControlCharacters ($str) {
1841 chr(13), '[r]', str_replace(
1842 chr(10), '[n]', str_replace(
1852 * Output a partial stub message for the caller method
1854 * @param $message An optional message to display
1857 protected function partialStub ($message = '') {
1858 // Get the backtrace
1859 $backtrace = debug_backtrace();
1861 // Generate the class::method string
1862 $methodName = 'UnknownClass->unknownMethod';
1863 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1864 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1867 // Construct the full message
1868 $stubMessage = sprintf('[%s:] Partial stub!',
1872 // Is the extra message given?
1873 if (!empty($message)) {
1874 // Then add it as well
1875 $stubMessage .= ' Message: ' . $message;
1878 // Debug instance is there?
1879 if (!is_null($this->getDebugInstance())) {
1880 // Output stub message
1881 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1884 trigger_error($stubMessage);
1890 * Outputs a debug backtrace and stops further script execution
1892 * @param $message An optional message to output
1893 * @param $doExit Whether exit the program (TRUE is default)
1896 public function debugBackTrace ($message = '', $doExit = TRUE) {
1897 // Sorry, there is no other way getting this nice backtrace
1898 if (!empty($message)) {
1900 printf('Message: %s<br />' . PHP_EOL, $message);
1904 debug_print_backtrace();
1908 if ($doExit === TRUE) {
1914 * Creates an instance of a debugger instance
1916 * @param $className Name of the class (currently unsupported)
1917 * @param $lineNumber Line number where the call was made
1918 * @return $debugInstance An instance of a debugger class
1919 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1921 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1922 // Is the instance set?
1923 if (!Registry::getRegistry()->instanceExists('debug')) {
1924 // Init debug instance
1925 $debugInstance = NULL;
1929 // Get a debugger instance
1930 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1931 } catch (NullPointerException $e) {
1932 // Didn't work, no instance there
1933 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1936 // Empty string should be ignored and used for testing the middleware
1937 DebugMiddleware::getSelfInstance()->output('');
1939 // Set it in its own class. This will set it in the registry
1940 $debugInstance->setDebugInstance($debugInstance);
1942 // Get instance from registry
1943 $debugInstance = Registry::getRegistry()->getDebugInstance();
1947 return $debugInstance;
1951 * Simple output of a message with line-break
1953 * @param $message Message to output
1956 public function outputLine ($message) {
1958 print($message . PHP_EOL);
1962 * Outputs a debug message whether to debug instance (should be set!) or
1963 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1964 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1966 * @param $message Message we shall send out...
1967 * @param $doPrint Whether print or die here (default: print)
1968 * @paran $stripTags Whether to strip tags (default: FALSE)
1971 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1972 // Set debug instance to NULL
1973 $debugInstance = NULL;
1977 // Get debug instance
1978 $debugInstance = $this->getDebugInstance();
1979 } catch (NullPointerException $e) {
1980 // The debug instance is not set (yet)
1983 // Is the debug instance there?
1984 if (is_object($debugInstance)) {
1985 // Use debug output handler
1986 $debugInstance->output($message, $stripTags);
1988 if ($doPrint === FALSE) {
1989 // Die here if not printed
1993 // Are debug times enabled?
1994 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1996 $message = $this->getPrintableExecutionTime() . $message;
2000 if ($doPrint === TRUE) {
2002 $this->outputLine($message);
2011 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2013 * @param $str The string, what ever it is needs to be converted
2014 * @return $className Generated class name
2016 public static final function convertToClassName ($str) {
2020 // Convert all dashes in underscores
2021 $str = self::convertDashesToUnderscores($str);
2023 // Now use that underscores to get classname parts for hungarian style
2024 foreach (explode('_', $str) as $strPart) {
2025 // Make the class name part lower case and first upper case
2026 $className .= ucfirst(strtolower($strPart));
2029 // Return class name
2034 * Converts dashes to underscores, e.g. useable for configuration entries
2036 * @param $str The string with maybe dashes inside
2037 * @return $str The converted string with no dashed, but underscores
2039 public static final function convertDashesToUnderscores ($str) {
2041 $str = str_replace('-', '_', $str);
2043 // Return converted string
2048 * Marks up the code by adding e.g. line numbers
2050 * @param $phpCode Unmarked PHP code
2051 * @return $markedCode Marked PHP code
2053 public function markupCode ($phpCode) {
2058 $errorArray = error_get_last();
2060 // Init the code with error message
2061 if (is_array($errorArray)) {
2063 $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>',
2064 basename($errorArray['file']),
2065 $errorArray['line'],
2066 $errorArray['message'],
2071 // Add line number to the code
2072 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2074 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2076 htmlentities($code, ENT_QUOTES)
2085 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2086 * beatiful for web-based front-ends. If null is given a message id
2087 * null_timestamp will be resolved and returned.
2089 * @param $timestamp Timestamp to prepare (filter) for display
2090 * @return $readable A readable timestamp
2092 public function doFilterFormatTimestamp ($timestamp) {
2093 // Default value to return
2096 // Is the timestamp null?
2097 if (is_null($timestamp)) {
2098 // Get a message string
2099 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2101 switch ($this->getLanguageInstance()->getLanguageCode()) {
2102 case 'de': // German format is a bit different to default
2103 // Split the GMT stamp up
2104 $dateTime = explode(' ', $timestamp );
2105 $dateArray = explode('-', $dateTime[0]);
2106 $timeArray = explode(':', $dateTime[1]);
2108 // Construct the timestamp
2109 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2119 default: // Default is pass-through
2120 $readable = $timestamp;
2130 * Filter a given number into a localized number
2132 * @param $value The raw value from e.g. database
2133 * @return $localized Localized value
2135 public function doFilterFormatNumber ($value) {
2136 // Generate it from config and localize dependencies
2137 switch ($this->getLanguageInstance()->getLanguageCode()) {
2138 case 'de': // German format is a bit different to default
2139 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2142 default: // US, etc.
2143 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2152 * "Getter" for databse entry
2154 * @return $entry An array with database entries
2155 * @throws NullPointerException If the database result is not found
2156 * @throws InvalidDatabaseResultException If the database result is invalid
2158 protected final function getDatabaseEntry () {
2159 // Is there an instance?
2160 if (!$this->getResultInstance() instanceof SearchableResult) {
2161 // Throw an exception here
2162 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2166 $this->getResultInstance()->rewind();
2168 // Do we have an entry?
2169 if ($this->getResultInstance()->valid() === FALSE) {
2170 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2171 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2175 $this->getResultInstance()->next();
2178 $entry = $this->getResultInstance()->current();
2185 * Getter for field name
2187 * @param $fieldName Field name which we shall get
2188 * @return $fieldValue Field value from the user
2189 * @throws NullPointerException If the result instance is null
2191 public final function getField ($fieldName) {
2192 // Default field value
2195 // Get result instance
2196 $resultInstance = $this->getResultInstance();
2198 // Is this instance null?
2199 if (is_null($resultInstance)) {
2200 // Then the user instance is no longer valid (expired cookies?)
2201 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2204 // Get current array
2205 $fieldArray = $resultInstance->current();
2206 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2208 // Convert dashes to underscore
2209 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2211 // Does the field exist?
2212 if ($this->isFieldSet($fieldName)) {
2214 $fieldValue = $fieldArray[$fieldName2];
2215 } elseif (defined('DEVELOPER')) {
2216 // Missing field entry, may require debugging
2217 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2219 // Missing field entry, may require debugging
2220 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2228 * Checks if given field is set
2230 * @param $fieldName Field name to check
2231 * @return $isSet Whether the given field name is set
2232 * @throws NullPointerException If the result instance is null
2234 public function isFieldSet ($fieldName) {
2235 // Get result instance
2236 $resultInstance = $this->getResultInstance();
2238 // Is this instance null?
2239 if (is_null($resultInstance)) {
2240 // Then the user instance is no longer valid (expired cookies?)
2241 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2244 // Get current array
2245 $fieldArray = $resultInstance->current();
2246 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2248 // Convert dashes to underscore
2249 $fieldName = self::convertDashesToUnderscores($fieldName);
2252 $isSet = isset($fieldArray[$fieldName]);
2259 * Flushs all pending updates to the database layer
2263 public function flushPendingUpdates () {
2264 // Get result instance
2265 $resultInstance = $this->getResultInstance();
2267 // Do we have data to update?
2268 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2269 // Get wrapper class name config entry
2270 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2272 // Create object instance
2273 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2275 // Yes, then send the whole result to the database layer
2276 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2281 * Outputs a deprecation warning to the developer.
2283 * @param $message The message we shall output to the developer
2285 * @todo Write a logging mechanism for productive mode
2287 public function deprecationWarning ($message) {
2288 // Is developer mode active?
2289 if (defined('DEVELOPER')) {
2290 // Debug instance is there?
2291 if (!is_null($this->getDebugInstance())) {
2292 // Output stub message
2293 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2296 trigger_error($message . "<br />\n");
2300 // @TODO Finish this part!
2301 $this->partialStub('Developer mode inactive. Message:' . $message);
2306 * Checks whether the given PHP extension is loaded
2308 * @param $phpExtension The PHP extension we shall check
2309 * @return $isLoaded Whether the PHP extension is loaded
2311 public final function isPhpExtensionLoaded ($phpExtension) {
2313 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2320 * "Getter" as a time() replacement but with milliseconds. You should use this
2321 * method instead of the encapsulated getimeofday() function.
2323 * @return $milliTime Timestamp with milliseconds
2325 public function getMilliTime () {
2326 // Get the time of day as float
2327 $milliTime = gettimeofday(TRUE);
2334 * Idles (sleeps) for given milliseconds
2336 * @return $hasSlept Whether it goes fine
2338 public function idle ($milliSeconds) {
2339 // Sleep is fine by default
2342 // Idle so long with found function
2343 if (function_exists('time_sleep_until')) {
2344 // Get current time and add idle time
2345 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2347 // New PHP 5.1.0 function found, ignore errors
2348 $hasSlept = @time_sleep_until($sleepUntil);
2351 * My Sun station doesn't have that function even with latest PHP
2354 usleep($milliSeconds * 1000);
2361 * Converts a hexadecimal string, even with negative sign as first string to
2362 * a decimal number using BC functions.
2364 * This work is based on comment #86673 on php.net documentation page at:
2365 * <http://de.php.net/manual/en/function.dechex.php#86673>
2367 * @param $hex Hexadecimal string
2368 * @return $dec Decimal number
2370 protected function hex2dec ($hex) {
2371 // Convert to all lower-case
2372 $hex = strtolower($hex);
2374 // Detect sign (negative/positive numbers)
2376 if (substr($hex, 0, 1) == '-') {
2378 $hex = substr($hex, 1);
2381 // Decode the hexadecimal string into a decimal number
2383 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2384 $factor = self::$hexdec[substr($hex, $i, 1)];
2385 $dec = bcadd($dec, bcmul($factor, $e));
2388 // Return the decimal number
2389 return $sign . $dec;
2393 * Converts even very large decimal numbers, also signed, to a hexadecimal
2396 * This work is based on comment #97756 on php.net documentation page at:
2397 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2399 * @param $dec Decimal number, even with negative sign
2400 * @param $maxLength Optional maximum length of the string
2401 * @return $hex Hexadecimal string
2403 protected function dec2hex ($dec, $maxLength = 0) {
2404 // maxLength can be zero or devideable by 2
2405 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2407 // Detect sign (negative/positive numbers)
2414 // Encode the decimal number into a hexadecimal string
2417 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2419 } while ($dec >= 1);
2422 * Leading zeros are required for hex-decimal "numbers". In some
2423 * situations more leading zeros are wanted, so check for both
2426 if ($maxLength > 0) {
2427 // Prepend more zeros
2428 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2429 } elseif ((strlen($hex) % 2) != 0) {
2430 // Only make string's length dividable by 2
2434 // Return the hexadecimal string
2435 return $sign . $hex;
2439 * Converts a ASCII string (0 to 255) into a decimal number.
2441 * @param $asc The ASCII string to be converted
2442 * @return $dec Decimal number
2444 protected function asc2dec ($asc) {
2445 // Convert it into a hexadecimal number
2446 $hex = bin2hex($asc);
2448 // And back into a decimal number
2449 $dec = $this->hex2dec($hex);
2456 * Converts a decimal number into an ASCII string.
2458 * @param $dec Decimal number
2459 * @return $asc An ASCII string
2461 protected function dec2asc ($dec) {
2462 // First convert the number into a hexadecimal string
2463 $hex = $this->dec2hex($dec);
2465 // Then convert it into the ASCII string
2466 $asc = $this->hex2asc($hex);
2473 * Converts a hexadecimal number into an ASCII string. Negative numbers
2476 * @param $hex Hexadecimal string
2477 * @return $asc An ASCII string
2479 protected function hex2asc ($hex) {
2480 // Check for length, it must be devideable by 2
2481 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2482 assert((strlen($hex) % 2) == 0);
2486 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2487 // Get the decimal number of the chunk
2488 $part = hexdec(substr($hex, $idx, 2));
2490 // Add it to the final string
2494 // Return the final string
2499 * Checks whether the given encoded data was encoded with Base64
2501 * @param $encodedData Encoded data we shall check
2502 * @return $isBase64 Whether the encoded data is Base64
2504 protected function isBase64Encoded ($encodedData) {
2506 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2513 * "Getter" to get response/request type from analysis of the system.
2515 * @return $responseType Analyzed response type
2517 protected static function getResponseTypeFromSystem () {
2518 // Default is console
2519 $responseType = 'console';
2521 // Is 'HTTP_HOST' set?
2522 if (isset($_SERVER['HTTP_HOST'])) {
2524 * Then it is a HTML response/request as RSS and so on may be
2525 * transfered over HTTP as well.
2527 $responseType = 'html';
2531 return $responseType;
2535 * Gets a cache key from Criteria instance
2537 * @param $criteriaInstance An instance of a Criteria class
2538 * @param $onlyKeys Only use these keys for a cache key
2539 * @return $cacheKey A cache key suitable for lookup/storage purposes
2541 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2543 $cacheKey = sprintf('%s@%s',
2544 $this->__toString(),
2545 $criteriaInstance->getCacheKey($onlyKeys)
2549 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2554 * Getter for startup time in miliseconds
2556 * @return $startupTime Startup time in miliseconds
2558 protected function getStartupTime () {
2559 return self::$startupTime;
2563 * "Getter" for a printable currently execution time in nice braces
2565 * @return $executionTime Current execution time in nice braces
2567 protected function getPrintableExecutionTime () {
2568 // Caculate the execution time
2569 $executionTime = microtime(TRUE) - $this->getStartupTime();
2571 // Pack it in nice braces
2572 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2575 return $executionTime;
2579 * Hashes a given string with a simple but stronger hash function (no salt)
2580 * and hex-encode it.
2582 * @param $str The string to be hashed
2583 * @return $hash The hash from string $str
2585 public static final function hash ($str) {
2586 // Hash given string with (better secure) hasher
2587 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2594 * "Getter" for length of hash() output. This will be "cached" to speed up
2597 * @return $length Length of hash() output
2599 public static final function getHashLength () {
2601 if (is_null(self::$hashLength)) {
2602 // No, then hash a string and save its length.
2603 self::$hashLength = strlen(self::hash('abc123'));
2607 return self::$hashLength;
2611 * Checks whether the given number is really a number (only chars 0-9).
2613 * @param $num A string consisting only chars between 0 and 9
2614 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2615 * @param $assertMismatch Whether to assert mismatches
2616 * @return $ret The (hopefully) secured numbered value
2618 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2619 // Filter all numbers out
2620 $ret = preg_replace('/[^0123456789]/', '', $num);
2623 if ($castValue === TRUE) {
2624 // Cast to biggest numeric type
2625 $ret = (double) $ret;
2628 // Assert only if requested
2629 if ($assertMismatch === TRUE) {
2630 // Has the whole value changed?
2631 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2639 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2641 * @param $num A string consisting only chars between 0 and 9
2642 * @param $assertMismatch Whether to assert mismatches
2643 * @return $ret The (hopefully) secured hext-numbered value
2645 public function hexval ($num, $assertMismatch = FALSE) {
2646 // Filter all numbers out
2647 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2649 // Assert only if requested
2650 if ($assertMismatch === TRUE) {
2651 // Has the whole value changed?
2652 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2660 * Checks whether start/end marker are set
2662 * @param $data Data to be checked
2663 * @return $isset Whether start/end marker are set
2665 public final function ifStartEndMarkersSet ($data) {
2667 $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));
2669 // ... and return it
2674 * Determines if an element is set in the generic array
2676 * @param $keyGroup Main group for the key
2677 * @param $subGroup Sub group for the key
2678 * @param $key Key to check
2679 * @param $element Element to check
2680 * @return $isset Whether the given key is set
2682 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2684 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2687 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2693 * Determines if a key is set in the generic array
2695 * @param $keyGroup Main group for the key
2696 * @param $subGroup Sub group for the key
2697 * @param $key Key to check
2698 * @return $isset Whether the given key is set
2700 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2702 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2705 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2713 * Determines if a group is set in the generic array
2715 * @param $keyGroup Main group
2716 * @param $subGroup Sub group
2717 * @return $isset Whether the given group is set
2719 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2721 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2724 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2731 * Getter for sub key group
2733 * @param $keyGroup Main key group
2734 * @param $subGroup Sub key group
2735 * @return $array An array with all array elements
2737 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2739 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2740 // No, then abort here
2741 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2746 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2749 return $this->genericArray[$keyGroup][$subGroup];
2753 * Unsets a given key in generic array
2755 * @param $keyGroup Main group for the key
2756 * @param $subGroup Sub group for the key
2757 * @param $key Key to unset
2760 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2762 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2765 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2769 * Unsets a given element in generic array
2771 * @param $keyGroup Main group for the key
2772 * @param $subGroup Sub group for the key
2773 * @param $key Key to unset
2774 * @param $element Element to unset
2777 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2779 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2782 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2786 * Append a string to a given generic array key
2788 * @param $keyGroup Main group for the key
2789 * @param $subGroup Sub group for the key
2790 * @param $key Key to unset
2791 * @param $value Value to add/append
2794 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2796 //* 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);
2798 // Is it already there?
2799 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2801 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2804 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2809 * Append a string to a given generic array element
2811 * @param $keyGroup Main group for the key
2812 * @param $subGroup Sub group for the key
2813 * @param $key Key to unset
2814 * @param $element Element to check
2815 * @param $value Value to add/append
2818 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2820 //* 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);
2822 // Is it already there?
2823 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2825 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2828 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2833 * Sets a string in a given generic array element
2835 * @param $keyGroup Main group for the key
2836 * @param $subGroup Sub group for the key
2837 * @param $key Key to unset
2838 * @param $element Element to check
2839 * @param $value Value to add/append
2842 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2844 //* 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);
2847 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2851 * Initializes given generic array group
2853 * @param $keyGroup Main group for the key
2854 * @param $subGroup Sub group for the key
2855 * @param $key Key to use
2856 * @param $forceInit Optionally force initialization
2859 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2861 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2863 // Is it already set?
2864 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2865 // Already initialized
2866 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2871 $this->genericArray[$keyGroup][$subGroup] = array();
2875 * Initializes given generic array key
2877 * @param $keyGroup Main group for the key
2878 * @param $subGroup Sub group for the key
2879 * @param $key Key to use
2880 * @param $forceInit Optionally force initialization
2883 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2885 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2887 // Is it already set?
2888 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2889 // Already initialized
2890 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2895 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2899 * Initializes given generic array element
2901 * @param $keyGroup Main group for the key
2902 * @param $subGroup Sub group for the key
2903 * @param $key Key to use
2904 * @param $element Element to use
2905 * @param $forceInit Optionally force initialization
2908 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2910 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2912 // Is it already set?
2913 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2914 // Already initialized
2915 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2920 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2924 * Pushes an element to a generic key
2926 * @param $keyGroup Main group for the key
2927 * @param $subGroup Sub group for the key
2928 * @param $key Key to use
2929 * @param $value Value to add/append
2930 * @return $count Number of array elements
2932 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2934 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2937 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2939 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2943 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2946 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2947 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2952 * Pushes an element to a generic array element
2954 * @param $keyGroup Main group for the key
2955 * @param $subGroup Sub group for the key
2956 * @param $key Key to use
2957 * @param $element Element to check
2958 * @param $value Value to add/append
2959 * @return $count Number of array elements
2961 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2963 //* 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));
2966 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2968 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2972 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2975 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2976 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2981 * Pops an element from a generic group
2983 * @param $keyGroup Main group for the key
2984 * @param $subGroup Sub group for the key
2985 * @param $key Key to unset
2986 * @return $value Last "popped" value
2988 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2990 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2993 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2995 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3000 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
3003 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3004 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3009 * Shifts an element from a generic group
3011 * @param $keyGroup Main group for the key
3012 * @param $subGroup Sub group for the key
3013 * @param $key Key to unset
3014 * @return $value Last "popped" value
3016 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3018 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3021 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3023 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3028 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3031 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3032 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3037 * Count generic array group
3039 * @param $keyGroup Main group for the key
3040 * @return $count Count of given group
3042 protected final function countGenericArray ($keyGroup) {
3044 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3047 if (!isset($this->genericArray[$keyGroup])) {
3049 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3054 $count = count($this->genericArray[$keyGroup]);
3057 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3064 * Count generic array sub group
3066 * @param $keyGroup Main group for the key
3067 * @param $subGroup Sub group for the key
3068 * @return $count Count of given group
3070 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3072 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3075 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3077 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3082 $count = count($this->genericArray[$keyGroup][$subGroup]);
3085 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3092 * Count generic array elements
3094 * @param $keyGroup Main group for the key
3095 * @param $subGroup Sub group for the key
3096 * @para $key Key to count
3097 * @return $count Count of given key
3099 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3101 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3104 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3106 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3108 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3110 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3115 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3118 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3125 * Getter for whole generic group array
3127 * @param $keyGroup Key group to get
3128 * @return $array Whole generic array group
3130 protected final function getGenericArray ($keyGroup) {
3132 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3135 if (!isset($this->genericArray[$keyGroup])) {
3137 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3142 return $this->genericArray[$keyGroup];
3146 * Setter for generic array key
3148 * @param $keyGroup Key group to get
3149 * @param $subGroup Sub group for the key
3150 * @param $key Key to unset
3151 * @param $value Mixed value from generic array element
3154 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3156 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3159 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3163 * Getter for generic array key
3165 * @param $keyGroup Key group to get
3166 * @param $subGroup Sub group for the key
3167 * @param $key Key to unset
3168 * @return $value Mixed value from generic array element
3170 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3172 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3175 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3177 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3182 return $this->genericArray[$keyGroup][$subGroup][$key];
3186 * Sets a value in given generic array key/element
3188 * @param $keyGroup Main group for the key
3189 * @param $subGroup Sub group for the key
3190 * @param $key Key to set
3191 * @param $element Element to set
3192 * @param $value Value to set
3195 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3197 //* 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));
3200 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3204 * Getter for generic array element
3206 * @param $keyGroup Key group to get
3207 * @param $subGroup Sub group for the key
3208 * @param $key Key to look for
3209 * @param $element Element to look for
3210 * @return $value Mixed value from generic array element
3212 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3214 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3217 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3219 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3224 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3228 * Checks if a given sub group is valid (array)
3230 * @param $keyGroup Key group to get
3231 * @param $subGroup Sub group for the key
3232 * @return $isValid Whether given sub group is valid
3234 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3236 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3239 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3246 * Checks if a given key is valid (array)
3248 * @param $keyGroup Key group to get
3249 * @param $subGroup Sub group for the key
3250 * @param $key Key to check
3251 * @return $isValid Whether given sub group is valid
3253 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3255 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3258 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3265 * Initializes the web output instance
3269 protected function initWebOutputInstance () {
3270 // Get application instance
3271 $applicationInstance = Registry::getRegistry()->getInstance('app');
3273 // Is this a response instance?
3274 if ($this instanceof Responseable) {
3275 // Then set it in application instance
3276 $applicationInstance->setResponseInstance($this);
3279 // Init web output instance
3280 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3283 $this->setWebOutputInstance($outputInstance);
3287 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3289 * @param $boolean Boolean value
3290 * @return $translated Translated boolean value
3292 public static final function translateBooleanToYesNo ($boolean) {
3293 // Make sure it is really boolean
3294 assert(is_bool($boolean));
3297 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3299 // ... and return it
3304 * Encodes raw data (almost any type) by "serializing" it and then pack it
3305 * into a "binary format".
3307 * @param $rawData Raw data (almost any type)
3308 * @return $encoded Encoded data
3310 protected function encodeData ($rawData) {
3311 // Make sure no objects or resources pass through
3312 assert(!is_object($rawData));
3313 assert(!is_resource($rawData));
3315 // First "serialize" it (json_encode() is faster than serialize())
3316 $encoded = $this->packString(json_encode($rawData));
3323 * Pack a string into a "binary format". Please execuse me that this is
3324 * widely undocumented. :-(
3326 * @param $str Unpacked string
3327 * @return $packed Packed string
3328 * @todo Improve documentation
3330 protected function packString ($str) {
3332 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3334 // First compress the string (gzcompress is okay)
3335 $str = gzcompress($str);
3340 // And start the "encoding" loop
3341 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3343 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3344 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3346 if (($idx + $i) <= strlen($str)) {
3347 $ord = ord(substr($str, ($idx + $i), 1));
3349 $add = $ord * pow(256, $factor);
3353 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3357 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3358 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3360 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3361 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3367 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3372 * Checks whether the given file/path is in open_basedir(). This does not
3373 * gurantee that the file is actually readable and/or writeable. If you need
3374 * such gurantee then please use isReadableFile() instead.
3376 * @param $filePathName Name of the file/path to be checked
3377 * @return $isReachable Whether it is within open_basedir()
3379 protected static function isReachableFilePath ($filePathName) {
3380 // Is not reachable by default
3381 $isReachable = FALSE;
3383 // Get open_basedir parameter
3384 $openBaseDir = ini_get('open_basedir');
3387 if (!empty($openBaseDir)) {
3388 // Check all entries
3389 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3390 // Check on existence
3391 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3393 $isReachable = TRUE;
3397 // If open_basedir is not set, all is allowed
3398 $isReachable = TRUE;
3402 return $isReachable;
3406 * Checks whether the give file is within open_basedir() (done by
3407 * isReachableFilePath()), is actually a file and is readable.
3409 * @param $fileName Name of the file to be checked
3410 * @return $isReadable Whether the file is readable (and therefor exists)
3412 public static function isReadableFile ($fileName) {
3413 // Default is not readable
3414 $isReadable = FALSE;
3416 // Is within parameters, so check if it is a file and readable
3417 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3424 * Creates a full-qualified file name (FQFN) for given file name by adding
3425 * a configured temporary file path to it.
3427 * @param $fileName Name for temporary file
3428 * @return $fqfn Full-qualified file name
3429 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3430 * @throws FileIoException If the file cannot be written
3432 protected static function createTempPathForFile ($fileName) {
3434 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3436 // Is the path writeable?
3437 if (!is_writable($basePath)) {
3438 // Path is write-protected
3439 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3443 $fqfn = $basePath . '/' . $fileName;
3446 if (!self::isReachableFilePath($fqfn)) {
3448 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3456 * "Getter" for a printable state name
3458 * @return $stateName Name of the node's state in a printable format
3460 public final function getPrintableState () {
3461 // Default is 'null'
3462 $stateName = 'null';
3464 // Get the state instance
3465 $stateInstance = $this->getStateInstance();
3467 // Is it an instance of Stateable?
3468 if ($stateInstance instanceof Stateable) {
3469 // Then use that state name
3470 $stateName = $stateInstance->getStateName();
3478 * Handles socket error for given socket resource and peer data. This method
3479 * validates $socketResource if it is a valid resource (see is_resource())
3480 * but assumes valid data in array $recipientData, except that
3481 * count($recipientData) is always 2.
3483 * @param $method Value of __METHOD__ from calling method
3484 * @param $line Value of __LINE__ from calling method
3485 * @param $socketResource A valid socket resource
3486 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3488 * @throws InvalidSocketException If $socketResource is no socket resource
3489 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3490 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3492 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3493 // This method handles only socket resources
3494 if (!is_resource($socketResource)) {
3495 // No resource, abort here
3496 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3499 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3500 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3501 assert(isset($socketData[0]));
3502 assert(isset($socketData[1]));
3504 // Get error code for first validation (0 is not an error)
3505 $errorCode = socket_last_error($socketResource);
3507 // If the error code is zero, someone called this method without an error
3508 if ($errorCode == 0) {
3509 // No error detected (or previously cleared outside this method)
3510 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3513 // Get handler (method) name
3514 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3516 // Call-back the error handler method
3517 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3519 // Finally clear the error because it has been handled
3520 socket_clear_error($socketResource);