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\Response\Responseable;
27 use CoreFramework\Stream\Output\OutputStreamer;
28 use CoreFramework\Template\CompileableTemplate;
34 * The simulator system class is the super class of all other classes. This
35 * class handles saving of games etc.
37 * @author Roland Haeder <webmaster@shipsimu.org>
39 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
40 * @license GNU GPL 3.0 or any newer version
41 * @link http://www.shipsimu.org
43 * This program is free software: you can redistribute it and/or modify
44 * it under the terms of the GNU General Public License as published by
45 * the Free Software Foundation, either version 3 of the License, or
46 * (at your option) any later version.
48 * This program is distributed in the hope that it will be useful,
49 * but WITHOUT ANY WARRANTY; without even the implied warranty of
50 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
51 * GNU General Public License for more details.
53 * You should have received a copy of the GNU General Public License
54 * along with this program. If not, see <http://www.gnu.org/licenses/>.
56 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
58 * Length of output from hash()
60 private static $hashLength = NULL;
65 private $realClass = 'BaseFrameworkSystem';
68 * Instance of a Requestable class
70 private $requestInstance = NULL;
73 * Instance of a Responseable class
75 private $responseInstance = NULL;
78 * Search criteria instance
80 private $searchInstance = NULL;
83 * Update criteria instance
85 private $updateInstance = NULL;
88 * The file I/O instance for the template loader
90 private $fileIoInstance = NULL;
95 private $resolverInstance = NULL;
98 * Template engine instance
100 private $templateInstance = NULL;
103 * Database result instance
105 private $resultInstance = NULL;
108 * Instance for user class
110 private $userInstance = NULL;
113 * A controller instance
115 private $controllerInstance = NULL;
120 private $rngInstance = NULL;
123 * Instance of a crypto helper
125 private $cryptoInstance = NULL;
128 * Instance of an Iterator class
130 private $iteratorInstance = NULL;
133 * Instance of the list
135 private $listInstance = NULL;
140 private $menuInstance = NULL;
143 * Instance of the image
145 private $imageInstance = NULL;
148 * Instance of the stacker
150 private $stackInstance = NULL;
153 * A Compressor instance
155 private $compressorInstance = NULL;
158 * A Parseable instance
160 private $parserInstance = NULL;
163 * A HandleableProtocol instance
165 private $protocolInstance = NULL;
168 * A database wrapper instance
170 private $databaseInstance = NULL;
173 * A helper instance for the form
175 private $helperInstance = NULL;
178 * An instance of a Source class
180 private $sourceInstance = NULL;
183 * An instance of a UrlSource class
185 private $urlSourceInstance = NULL;
188 * An instance of a InputStream class
190 private $inputStreamInstance = NULL;
193 * An instance of a OutputStream class
195 private $outputStreamInstance = NULL;
198 * Networkable handler instance
200 private $handlerInstance = NULL;
203 * Visitor handler instance
205 private $visitorInstance = NULL;
210 private $dhtInstance = NULL;
213 * An instance of a database wrapper class
215 private $wrapperInstance = NULL;
218 * An instance of a file I/O pointer class (not handler)
220 private $pointerInstance = NULL;
223 * An instance of an Indexable class
225 private $indexInstance = NULL;
228 * An instance of a Block class
230 private $blockInstance = NULL;
235 private $minableInstance = NULL;
238 * A FrameworkDirectory instance
240 private $directoryInstance = NULL;
245 private $listenerInstance = NULL;
248 * An instance of a communicator
250 private $communicatorInstance = NULL;
253 * The concrete output instance
255 private $outputInstance = NULL;
260 private $stateInstance = NULL;
263 * Thousands separator
265 private $thousands = '.'; // German
270 private $decimals = ','; // German
275 private $socketResource = FALSE;
278 * Regular expression to use for validation
280 private $regularExpression = '';
285 private $packageData = array();
290 private $genericArray = array();
295 private $commandName = '';
300 private $controllerName = '';
303 * Name of used protocol
305 private $protocolName = 'invalid';
308 * Array with bitmasks and such for pack/unpack methods to support both
309 * 32-bit and 64-bit systems
311 private $packingData = array(
314 'left' => 0xffff0000,
315 'right' => 0x0000ffff,
321 'left' => 0xffffffff00000000,
322 'right' => 0x00000000ffffffff,
329 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
331 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
333 private $archArrayElement = FALSE;
335 /***********************
336 * Exception codes.... *
337 ***********************/
339 // @todo Try to clean these constants up
340 const EXCEPTION_IS_NULL_POINTER = 0x001;
341 const EXCEPTION_IS_NO_OBJECT = 0x002;
342 const EXCEPTION_IS_NO_ARRAY = 0x003;
343 const EXCEPTION_MISSING_METHOD = 0x004;
344 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
345 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
346 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
347 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
348 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
349 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
350 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
351 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
352 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
353 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
354 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
355 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
356 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
357 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
358 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
359 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
360 const EXCEPTION_PATH_NOT_FOUND = 0x015;
361 const EXCEPTION_INVALID_PATH_NAME = 0x016;
362 const EXCEPTION_READ_PROTECED_PATH = 0x017;
363 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
364 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
365 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
366 const EXCEPTION_INVALID_RESOURCE = 0x01b;
367 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
368 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
369 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
370 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
371 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
372 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
373 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
374 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
375 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
376 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
377 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
378 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
379 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
380 const EXCEPTION_INVALID_STRING = 0x029;
381 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
382 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
383 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
384 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
385 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
386 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
387 const EXCEPTION_MISSING_ELEMENT = 0x030;
388 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
389 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
390 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
391 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
392 const EXCEPTION_FATAL_ERROR = 0x035;
393 const EXCEPTION_FILE_NOT_FOUND = 0x036;
394 const EXCEPTION_ASSERTION_FAILED = 0x037;
395 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
396 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
397 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
398 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
399 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
400 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
403 * Hexadecimal->Decimal translation array
405 private static $hexdec = array(
425 * Decimal->hexadecimal translation array
427 private static $dechex = array(
447 * Startup time in miliseconds
449 private static $startupTime = 0;
452 * Protected super constructor
454 * @param $className Name of the class
457 protected function __construct ($className) {
459 $this->setRealClass($className);
461 // Set configuration instance if no registry ...
462 if (!$this instanceof Register) {
463 // ... because registries doesn't need to be configured
464 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
467 // Is the startup time set? (0 cannot be TRUE anymore)
468 if (self::$startupTime == 0) {
470 self::$startupTime = microtime(TRUE);
474 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
478 * Destructor for all classes. You should not call this method on your own.
482 public function __destruct () {
483 // Flush any updated entries to the database
484 $this->flushPendingUpdates();
486 // Is this object already destroyed?
487 if ($this->__toString() != 'DestructedObject') {
488 // Destroy all informations about this class but keep some text about it alive
489 $this->setRealClass('DestructedObject');
490 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
491 // Already destructed object
492 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
497 // Do not call this twice
498 trigger_error(__METHOD__ . ': Called twice.');
504 * The __call() method where all non-implemented methods end up
506 * @param $methodName Name of the missing method
507 * @args $args Arguments passed to the method
510 public final function __call ($methodName, $args) {
511 return self::__callStatic($methodName, $args);
515 * The __callStatic() method where all non-implemented static methods end up
517 * @param $methodName Name of the missing method
518 * @args $args Arguments passed to the method
521 public static final function __callStatic ($methodName, $args) {
523 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
525 // Init argument string
528 // Is it NULL, empty or an array?
529 if (is_null($args)) {
531 $argsString = 'NULL';
532 } elseif (is_array($args)) {
536 // Some arguments are there
537 foreach ($args as $arg) {
538 // Add data about the argument
539 $argsString .= gettype($arg) . ':';
542 // Found a NULL argument
543 $argsString .= 'NULL';
544 } elseif (is_string($arg)) {
545 // Add length for strings
546 $argsString .= strlen($arg);
547 } elseif ((is_int($arg)) || (is_float($arg))) {
550 } elseif (is_array($arg)) {
551 // .. or size if array
552 $argsString .= count($arg);
553 } elseif (is_object($arg)) {
555 $reflection = new ReflectionClass($arg);
557 // Is an other object, maybe no __toString() available
558 $argsString .= $reflection->getName();
559 } elseif ($arg === TRUE) {
560 // ... is boolean 'TRUE'
561 $argsString .= 'TRUE';
562 } elseif ($arg === FALSE) {
563 // ... is boolean 'FALSE'
564 $argsString .= 'FALSE';
567 // Comma for next one
572 if (substr($argsString, -2, 1) == ',') {
573 $argsString = substr($argsString, 0, -2);
579 // Invalid arguments!
580 $argsString = '!INVALID:' . gettype($args) . '!';
583 // Output stub message
584 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
585 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
595 * Getter for $realClass
597 * @return $realClass The name of the real class (not BaseFrameworkSystem)
599 public function __toString () {
600 return $this->realClass;
604 * Magic method to catch setting of missing but set class fields/attributes
606 * @param $name Name of the field/attribute
607 * @param $value Value to store
610 public final function __set ($name, $value) {
611 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
614 print_r($value, TRUE)
619 * Magic method to catch getting of missing fields/attributes
621 * @param $name Name of the field/attribute
624 public final function __get ($name) {
625 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
631 * Magic method to catch unsetting of missing fields/attributes
633 * @param $name Name of the field/attribute
636 public final function __unset ($name) {
637 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
643 * Magic method to catch object serialization
645 * @return $unsupported Unsupported method
646 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
648 public final function __sleep () {
649 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
653 * Magic method to catch object deserialization
655 * @return $unsupported Unsupported method
656 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
658 public final function __wakeup () {
659 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
663 * Magic method to catch calls when an object instance is called
665 * @return $unsupported Unsupported method
666 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
668 public final function __invoke () {
669 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
673 * Setter for the real class name
675 * @param $realClass Class name (string)
678 public final function setRealClass ($realClass) {
680 $this->realClass = (string) $realClass;
684 * Setter for database result instance
686 * @param $resultInstance An instance of a database result class
688 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
690 protected final function setResultInstance (SearchableResult $resultInstance) {
691 $this->resultInstance = $resultInstance;
695 * Getter for database result instance
697 * @return $resultInstance An instance of a database result class
699 public final function getResultInstance () {
700 return $this->resultInstance;
704 * Setter for template engine instances
706 * @param $templateInstance An instance of a template engine class
709 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
710 $this->templateInstance = $templateInstance;
714 * Getter for template engine instances
716 * @return $templateInstance An instance of a template engine class
718 protected final function getTemplateInstance () {
719 return $this->templateInstance;
723 * Setter for search instance
725 * @param $searchInstance Searchable criteria instance
728 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
729 $this->searchInstance = $searchInstance;
733 * Getter for search instance
735 * @return $searchInstance Searchable criteria instance
737 public final function getSearchInstance () {
738 return $this->searchInstance;
742 * Setter for update instance
744 * @param $updateInstance Searchable criteria instance
747 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
748 $this->updateInstance = $updateInstance;
752 * Getter for update instance
754 * @return $updateInstance Updateable criteria instance
756 public final function getUpdateInstance () {
757 return $this->updateInstance;
761 * Setter for resolver instance
763 * @param $resolverInstance Instance of a command resolver class
766 public final function setResolverInstance (Resolver $resolverInstance) {
767 $this->resolverInstance = $resolverInstance;
771 * Getter for resolver instance
773 * @return $resolverInstance Instance of a command resolver class
775 public final function getResolverInstance () {
776 return $this->resolverInstance;
780 * Setter for language instance
782 * @param $configInstance The configuration instance which shall
783 * be FrameworkConfiguration
786 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
787 Registry::getRegistry()->addInstance('config', $configInstance);
791 * Getter for configuration instance
793 * @return $configInstance Configuration instance
795 public final function getConfigInstance () {
796 $configInstance = Registry::getRegistry()->getInstance('config');
797 return $configInstance;
801 * Setter for debug instance
803 * @param $debugInstance The instance for debug output class
806 public final function setDebugInstance (DebugMiddleware $debugInstance) {
807 Registry::getRegistry()->addInstance('debug', $debugInstance);
811 * Getter for debug instance
813 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
815 public final function getDebugInstance () {
816 // Get debug instance
817 $debugInstance = Registry::getRegistry()->getInstance('debug');
820 return $debugInstance;
824 * Setter for web output instance
826 * @param $webInstance The instance for web output class
829 public final function setWebOutputInstance (OutputStreamer $webInstance) {
830 Registry::getRegistry()->addInstance('web_output', $webInstance);
834 * Getter for web output instance
836 * @return $webOutputInstance - Instance to class WebOutput
838 public final function getWebOutputInstance () {
839 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
840 return $webOutputInstance;
844 * Setter for database instance
846 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
849 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
850 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
854 * Getter for database layer
856 * @return $databaseInstance The database layer instance
858 public final function getDatabaseInstance () {
860 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
863 return $databaseInstance;
867 * Setter for compressor channel
869 * @param $compressorInstance An instance of CompressorChannel
872 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
873 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
877 * Getter for compressor channel
879 * @return $compressorInstance The compressor channel
881 public final function getCompressorChannel () {
882 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
883 return $compressorInstance;
887 * Protected getter for a manageable application helper class
889 * @return $applicationInstance An instance of a manageable application helper class
891 protected final function getApplicationInstance () {
892 $applicationInstance = Registry::getRegistry()->getInstance('application');
893 return $applicationInstance;
897 * Setter for a manageable application helper class
899 * @param $applicationInstance An instance of a manageable application helper class
902 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
903 Registry::getRegistry()->addInstance('application', $applicationInstance);
907 * Setter for request instance
909 * @param $requestInstance An instance of a Requestable class
912 public final function setRequestInstance (Requestable $requestInstance) {
913 $this->requestInstance = $requestInstance;
917 * Getter for request instance
919 * @return $requestInstance An instance of a Requestable class
921 public final function getRequestInstance () {
922 return $this->requestInstance;
926 * Setter for response instance
928 * @param $responseInstance An instance of a Responseable class
931 public final function setResponseInstance (Responseable $responseInstance) {
932 $this->responseInstance = $responseInstance;
936 * Getter for response instance
938 * @return $responseInstance An instance of a Responseable class
940 public final function getResponseInstance () {
941 return $this->responseInstance;
945 * Private getter for language instance
947 * @return $langInstance An instance to the language sub-system
949 protected final function getLanguageInstance () {
950 $langInstance = Registry::getRegistry()->getInstance('language');
951 return $langInstance;
955 * Setter for language instance
957 * @param $langInstance An instance to the language sub-system
959 * @see LanguageSystem
961 public final function setLanguageInstance (ManageableLanguage $langInstance) {
962 Registry::getRegistry()->addInstance('language', $langInstance);
966 * Private getter for file IO instance
968 * @return $fileIoInstance An instance to the file I/O sub-system
970 protected final function getFileIoInstance () {
971 return $this->fileIoInstance;
975 * Setter for file I/O instance
977 * @param $fileIoInstance An instance to the file I/O sub-system
980 public final function setFileIoInstance (IoHandler $fileIoInstance) {
981 $this->fileIoInstance = $fileIoInstance;
985 * Protected setter for user instance
987 * @param $userInstance An instance of a user class
990 protected final function setUserInstance (ManageableAccount $userInstance) {
991 $this->userInstance = $userInstance;
995 * Getter for user instance
997 * @return $userInstance An instance of a user class
999 public final function getUserInstance () {
1000 return $this->userInstance;
1004 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1006 * @param $controllerInstance An instance of the controller
1009 public final function setControllerInstance (Controller $controllerInstance) {
1010 $this->controllerInstance = $controllerInstance;
1014 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1016 * @return $controllerInstance An instance of the controller
1018 public final function getControllerInstance () {
1019 return $this->controllerInstance;
1023 * Setter for RNG instance
1025 * @param $rngInstance An instance of a random number generator (RNG)
1028 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1029 $this->rngInstance = $rngInstance;
1033 * Getter for RNG instance
1035 * @return $rngInstance An instance of a random number generator (RNG)
1037 public final function getRngInstance () {
1038 return $this->rngInstance;
1042 * Setter for Cryptable instance
1044 * @param $cryptoInstance An instance of a Cryptable class
1047 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1048 $this->cryptoInstance = $cryptoInstance;
1052 * Getter for Cryptable instance
1054 * @return $cryptoInstance An instance of a Cryptable class
1056 public final function getCryptoInstance () {
1057 return $this->cryptoInstance;
1061 * Setter for the list instance
1063 * @param $listInstance A list of Listable
1066 protected final function setListInstance (Listable $listInstance) {
1067 $this->listInstance = $listInstance;
1071 * Getter for the list instance
1073 * @return $listInstance A list of Listable
1075 protected final function getListInstance () {
1076 return $this->listInstance;
1080 * Setter for the menu instance
1082 * @param $menuInstance A RenderableMenu instance
1085 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1086 $this->menuInstance = $menuInstance;
1090 * Getter for the menu instance
1092 * @return $menuInstance A RenderableMenu instance
1094 protected final function getMenuInstance () {
1095 return $this->menuInstance;
1099 * Setter for image instance
1101 * @param $imageInstance An instance of an image
1104 public final function setImageInstance (BaseImage $imageInstance) {
1105 $this->imageInstance = $imageInstance;
1109 * Getter for image instance
1111 * @return $imageInstance An instance of an image
1113 public final function getImageInstance () {
1114 return $this->imageInstance;
1118 * Setter for stacker instance
1120 * @param $stackInstance An instance of an stacker
1123 public final function setStackInstance (Stackable $stackInstance) {
1124 $this->stackInstance = $stackInstance;
1128 * Getter for stacker instance
1130 * @return $stackInstance An instance of an stacker
1132 public final function getStackInstance () {
1133 return $this->stackInstance;
1137 * Setter for compressor instance
1139 * @param $compressorInstance An instance of an compressor
1142 public final function setCompressorInstance (Compressor $compressorInstance) {
1143 $this->compressorInstance = $compressorInstance;
1147 * Getter for compressor instance
1149 * @return $compressorInstance An instance of an compressor
1151 public final function getCompressorInstance () {
1152 return $this->compressorInstance;
1156 * Setter for Parseable instance
1158 * @param $parserInstance An instance of an Parseable
1161 public final function setParserInstance (Parseable $parserInstance) {
1162 $this->parserInstance = $parserInstance;
1166 * Getter for Parseable instance
1168 * @return $parserInstance An instance of an Parseable
1170 public final function getParserInstance () {
1171 return $this->parserInstance;
1175 * Setter for HandleableProtocol instance
1177 * @param $protocolInstance An instance of an HandleableProtocol
1180 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1181 $this->protocolInstance = $protocolInstance;
1185 * Getter for HandleableProtocol instance
1187 * @return $protocolInstance An instance of an HandleableProtocol
1189 public final function getProtocolInstance () {
1190 return $this->protocolInstance;
1194 * Setter for DatabaseWrapper instance
1196 * @param $wrapperInstance An instance of an DatabaseWrapper
1199 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1200 $this->wrapperInstance = $wrapperInstance;
1204 * Getter for DatabaseWrapper instance
1206 * @return $wrapperInstance An instance of an DatabaseWrapper
1208 public final function getWrapperInstance () {
1209 return $this->wrapperInstance;
1213 * Setter for socket resource
1215 * @param $socketResource A valid socket resource
1218 public final function setSocketResource ($socketResource) {
1219 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1220 $this->socketResource = $socketResource;
1224 * Getter for socket resource
1226 * @return $socketResource A valid socket resource
1228 public final function getSocketResource () {
1229 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1230 return $this->socketResource;
1234 * Setter for regular expression
1236 * @param $regularExpression A valid regular expression
1239 public final function setRegularExpression ($regularExpression) {
1240 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1241 $this->regularExpression = $regularExpression;
1245 * Getter for regular expression
1247 * @return $regularExpression A valid regular expression
1249 public final function getRegularExpression () {
1250 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1251 return $this->regularExpression;
1255 * Setter for helper instance
1257 * @param $helperInstance An instance of a helper class
1260 protected final function setHelperInstance (Helper $helperInstance) {
1261 $this->helperInstance = $helperInstance;
1265 * Getter for helper instance
1267 * @return $helperInstance An instance of a helper class
1269 public final function getHelperInstance () {
1270 return $this->helperInstance;
1274 * Setter for a Source instance
1276 * @param $sourceInstance An instance of a Source class
1279 protected final function setSourceInstance (Source $sourceInstance) {
1280 $this->sourceInstance = $sourceInstance;
1284 * Getter for a Source instance
1286 * @return $sourceInstance An instance of a Source class
1288 protected final function getSourceInstance () {
1289 return $this->sourceInstance;
1293 * Setter for a UrlSource instance
1295 * @param $sourceInstance An instance of a UrlSource class
1298 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1299 $this->urlSourceInstance = $urlSourceInstance;
1303 * Getter for a UrlSource instance
1305 * @return $urlSourceInstance An instance of a UrlSource class
1307 protected final function getUrlSourceInstance () {
1308 return $this->urlSourceInstance;
1312 * Getter for a InputStream instance
1314 * @param $inputStreamInstance The InputStream instance
1316 protected final function getInputStreamInstance () {
1317 return $this->inputStreamInstance;
1321 * Setter for a InputStream instance
1323 * @param $inputStreamInstance The InputStream instance
1326 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1327 $this->inputStreamInstance = $inputStreamInstance;
1331 * Getter for a OutputStream instance
1333 * @param $outputStreamInstance The OutputStream instance
1335 protected final function getOutputStreamInstance () {
1336 return $this->outputStreamInstance;
1340 * Setter for a OutputStream instance
1342 * @param $outputStreamInstance The OutputStream instance
1345 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1346 $this->outputStreamInstance = $outputStreamInstance;
1350 * Setter for handler instance
1352 * @param $handlerInstance An instance of a Handleable class
1355 protected final function setHandlerInstance (Handleable $handlerInstance) {
1356 $this->handlerInstance = $handlerInstance;
1360 * Getter for handler instance
1362 * @return $handlerInstance A Networkable instance
1364 protected final function getHandlerInstance () {
1365 return $this->handlerInstance;
1369 * Setter for visitor instance
1371 * @param $visitorInstance A Visitor instance
1374 protected final function setVisitorInstance (Visitor $visitorInstance) {
1375 $this->visitorInstance = $visitorInstance;
1379 * Getter for visitor instance
1381 * @return $visitorInstance A Visitor instance
1383 protected final function getVisitorInstance () {
1384 return $this->visitorInstance;
1388 * Setter for DHT instance
1390 * @param $dhtInstance A Distributable instance
1393 protected final function setDhtInstance (Distributable $dhtInstance) {
1394 $this->dhtInstance = $dhtInstance;
1398 * Getter for DHT instance
1400 * @return $dhtInstance A Distributable instance
1402 protected final function getDhtInstance () {
1403 return $this->dhtInstance;
1407 * Setter for raw package Data
1409 * @param $packageData Raw package Data
1412 public final function setPackageData (array $packageData) {
1413 $this->packageData = $packageData;
1417 * Getter for raw package Data
1419 * @return $packageData Raw package Data
1421 public function getPackageData () {
1422 return $this->packageData;
1427 * Setter for Iterator instance
1429 * @param $iteratorInstance An instance of an Iterator
1432 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1433 $this->iteratorInstance = $iteratorInstance;
1437 * Getter for Iterator instance
1439 * @return $iteratorInstance An instance of an Iterator
1441 public final function getIteratorInstance () {
1442 return $this->iteratorInstance;
1446 * Setter for FilePointer instance
1448 * @param $pointerInstance An instance of an FilePointer class
1451 protected final function setPointerInstance (FilePointer $pointerInstance) {
1452 $this->pointerInstance = $pointerInstance;
1456 * Getter for FilePointer instance
1458 * @return $pointerInstance An instance of an FilePointer class
1460 public final function getPointerInstance () {
1461 return $this->pointerInstance;
1465 * Unsets pointer instance which triggers a call of __destruct() if the
1466 * instance is still there. This is surely not fatal on already "closed"
1467 * file pointer instances.
1469 * I don't want to mess around with above setter by giving it a default
1470 * value NULL as setter should always explicitly only set (existing) object
1471 * instances and NULL is NULL.
1475 protected final function unsetPointerInstance () {
1476 // Simply it to NULL
1477 $this->pointerInstance = NULL;
1481 * Setter for Indexable instance
1483 * @param $indexInstance An instance of an Indexable class
1486 protected final function setIndexInstance (Indexable $indexInstance) {
1487 $this->indexInstance = $indexInstance;
1491 * Getter for Indexable instance
1493 * @return $indexInstance An instance of an Indexable class
1495 public final function getIndexInstance () {
1496 return $this->indexInstance;
1500 * Setter for Block instance
1502 * @param $blockInstance An instance of an Block class
1505 protected final function setBlockInstance (Block $blockInstance) {
1506 $this->blockInstance = $blockInstance;
1510 * Getter for Block instance
1512 * @return $blockInstance An instance of an Block class
1514 public final function getBlockInstance () {
1515 return $this->blockInstance;
1519 * Setter for Minable instance
1521 * @param $minableInstance A Minable instance
1524 protected final function setMinableInstance (Minable $minableInstance) {
1525 $this->minableInstance = $minableInstance;
1529 * Getter for minable instance
1531 * @return $minableInstance A Minable instance
1533 protected final function getMinableInstance () {
1534 return $this->minableInstance;
1538 * Setter for FrameworkDirectory instance
1540 * @param $directoryInstance A FrameworkDirectory instance
1543 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1544 $this->directoryInstance = $directoryInstance;
1548 * Getter for FrameworkDirectory instance
1550 * @return $directoryInstance A FrameworkDirectory instance
1552 protected final function getDirectoryInstance () {
1553 return $this->directoryInstance;
1557 * Setter for listener instance
1559 * @param $listenerInstance A Listenable instance
1562 protected final function setListenerInstance (Listenable $listenerInstance) {
1563 $this->listenerInstance = $listenerInstance;
1567 * Getter for listener instance
1569 * @return $listenerInstance A Listenable instance
1571 protected final function getListenerInstance () {
1572 return $this->listenerInstance;
1576 * Getter for communicator instance
1578 * @return $communicatorInstance An instance of a Communicator class
1580 public final function getCommunicatorInstance () {
1581 return $this->communicatorInstance;
1585 * Setter for communicator instance
1587 * @param $communicatorInstance An instance of a Communicator class
1590 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1591 $this->communicatorInstance = $communicatorInstance;
1595 * Setter for state instance
1597 * @param $stateInstance A Stateable instance
1600 public final function setStateInstance (Stateable $stateInstance) {
1601 $this->stateInstance = $stateInstance;
1605 * Getter for state instance
1607 * @return $stateInstance A Stateable instance
1609 public final function getStateInstance () {
1610 return $this->stateInstance;
1614 * Setter for output instance
1616 * @param $outputInstance The debug output instance
1619 public final function setOutputInstance (OutputStreamer $outputInstance) {
1620 $this->outputInstance = $outputInstance;
1624 * Getter for output instance
1626 * @return $outputInstance The debug output instance
1628 public final function getOutputInstance () {
1629 return $this->outputInstance;
1633 * Setter for command name
1635 * @param $commandName Last validated command name
1638 protected final function setCommandName ($commandName) {
1639 $this->commandName = $commandName;
1643 * Getter for command name
1645 * @return $commandName Last validated command name
1647 protected final function getCommandName () {
1648 return $this->commandName;
1652 * Setter for controller name
1654 * @param $controllerName Last validated controller name
1657 protected final function setControllerName ($controllerName) {
1658 $this->controllerName = $controllerName;
1662 * Getter for controller name
1664 * @return $controllerName Last validated controller name
1666 protected final function getControllerName () {
1667 return $this->controllerName;
1671 * Getter for protocol name
1673 * @return $protocolName Name of used protocol
1675 public final function getProtocolName () {
1676 return $this->protocolName;
1680 * Setter for protocol name
1682 * @param $protocolName Name of used protocol
1685 protected final function setProtocolName ($protocolName) {
1686 $this->protocolName = $protocolName;
1690 * Checks whether an object equals this object. You should overwrite this
1691 * method to implement own equality checks
1693 * @param $objectInstance An instance of a FrameworkInterface object
1694 * @return $equals Whether both objects equals
1696 public function equals (FrameworkInterface $objectInstance) {
1699 $this->__toString() == $objectInstance->__toString()
1701 $this->hashCode() == $objectInstance->hashCode()
1704 // Return the result
1709 * Generates a generic hash code of this class. You should really overwrite
1710 * this method with your own hash code generator code. But keep KISS in mind.
1712 * @return $hashCode A generic hash code respresenting this whole class
1714 public function hashCode () {
1716 return crc32($this->__toString());
1720 * Formats computer generated price values into human-understandable formats
1721 * with thousand and decimal separators.
1723 * @param $value The in computer format value for a price
1724 * @param $currency The currency symbol (use HTML-valid characters!)
1725 * @param $decNum Number of decimals after commata
1726 * @return $price The for the current language formated price string
1727 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1728 * thousands separator
1731 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1732 // Are all required attriutes set?
1733 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1734 // Throw an exception
1735 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1739 $value = (float) $value;
1741 // Reformat the US number
1742 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1744 // Return as string...
1749 * Appends a trailing slash to a string
1751 * @param $str A string (maybe) without trailing slash
1752 * @return $str A string with an auto-appended trailing slash
1754 public final function addMissingTrailingSlash ($str) {
1755 // Is there a trailing slash?
1756 if (substr($str, -1, 1) != '/') {
1760 // Return string with trailing slash
1765 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1766 * application helper instance (ApplicationHelper by default).
1768 * @param $applicationInstance An application helper instance or
1769 * null if we shall use the default
1770 * @return $templateInstance The template engine instance
1771 * @throws NullPointerException If the discovered application
1772 * instance is still null
1774 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1775 // Is the application instance set?
1776 if (is_null($applicationInstance)) {
1777 // Get the current instance
1778 $applicationInstance = $this->getApplicationInstance();
1781 if (is_null($applicationInstance)) {
1782 // Thrown an exception
1783 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1787 // Initialize the template engine
1788 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1790 // Return the prepared instance
1791 return $templateInstance;
1795 * Debugs this instance by putting out it's full content
1797 * @param $message Optional message to show in debug output
1800 public final function debugInstance ($message = '') {
1801 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1802 restore_error_handler();
1807 // Is a message set?
1808 if (!empty($message)) {
1809 // Construct message
1810 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1813 // Generate the output
1814 $content .= sprintf('<pre>%s</pre>',
1817 print_r($this, TRUE)
1823 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>',
1824 $this->__toString(),
1826 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1831 * Replaces control characters with printable output
1833 * @param $str String with control characters
1834 * @return $str Replaced string
1836 protected function replaceControlCharacters ($str) {
1839 chr(13), '[r]', str_replace(
1840 chr(10), '[n]', str_replace(
1850 * Output a partial stub message for the caller method
1852 * @param $message An optional message to display
1855 protected function partialStub ($message = '') {
1856 // Get the backtrace
1857 $backtrace = debug_backtrace();
1859 // Generate the class::method string
1860 $methodName = 'UnknownClass->unknownMethod';
1861 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1862 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1865 // Construct the full message
1866 $stubMessage = sprintf('[%s:] Partial stub!',
1870 // Is the extra message given?
1871 if (!empty($message)) {
1872 // Then add it as well
1873 $stubMessage .= ' Message: ' . $message;
1876 // Debug instance is there?
1877 if (!is_null($this->getDebugInstance())) {
1878 // Output stub message
1879 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1882 trigger_error($stubMessage);
1888 * Outputs a debug backtrace and stops further script execution
1890 * @param $message An optional message to output
1891 * @param $doExit Whether exit the program (TRUE is default)
1894 public function debugBackTrace ($message = '', $doExit = TRUE) {
1895 // Sorry, there is no other way getting this nice backtrace
1896 if (!empty($message)) {
1898 printf('Message: %s<br />' . PHP_EOL, $message);
1902 debug_print_backtrace();
1906 if ($doExit === TRUE) {
1912 * Creates an instance of a debugger instance
1914 * @param $className Name of the class (currently unsupported)
1915 * @param $lineNumber Line number where the call was made
1916 * @return $debugInstance An instance of a debugger class
1917 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1919 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1920 // Is the instance set?
1921 if (!Registry::getRegistry()->instanceExists('debug')) {
1922 // Init debug instance
1923 $debugInstance = NULL;
1927 // Get a debugger instance
1928 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1929 } catch (NullPointerException $e) {
1930 // Didn't work, no instance there
1931 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1934 // Empty string should be ignored and used for testing the middleware
1935 DebugMiddleware::getSelfInstance()->output('');
1937 // Set it in its own class. This will set it in the registry
1938 $debugInstance->setDebugInstance($debugInstance);
1940 // Get instance from registry
1941 $debugInstance = Registry::getRegistry()->getDebugInstance();
1945 return $debugInstance;
1949 * Simple output of a message with line-break
1951 * @param $message Message to output
1954 public function outputLine ($message) {
1956 print($message . PHP_EOL);
1960 * Outputs a debug message whether to debug instance (should be set!) or
1961 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1962 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1964 * @param $message Message we shall send out...
1965 * @param $doPrint Whether print or die here (default: print)
1966 * @paran $stripTags Whether to strip tags (default: FALSE)
1969 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1970 // Set debug instance to NULL
1971 $debugInstance = NULL;
1975 // Get debug instance
1976 $debugInstance = $this->getDebugInstance();
1977 } catch (NullPointerException $e) {
1978 // The debug instance is not set (yet)
1981 // Is the debug instance there?
1982 if (is_object($debugInstance)) {
1983 // Use debug output handler
1984 $debugInstance->output($message, $stripTags);
1986 if ($doPrint === FALSE) {
1987 // Die here if not printed
1991 // Are debug times enabled?
1992 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1994 $message = $this->getPrintableExecutionTime() . $message;
1998 if ($doPrint === TRUE) {
2000 $this->outputLine($message);
2009 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2011 * @param $str The string, what ever it is needs to be converted
2012 * @return $className Generated class name
2014 public static final function convertToClassName ($str) {
2018 // Convert all dashes in underscores
2019 $str = self::convertDashesToUnderscores($str);
2021 // Now use that underscores to get classname parts for hungarian style
2022 foreach (explode('_', $str) as $strPart) {
2023 // Make the class name part lower case and first upper case
2024 $className .= ucfirst(strtolower($strPart));
2027 // Return class name
2032 * Converts dashes to underscores, e.g. useable for configuration entries
2034 * @param $str The string with maybe dashes inside
2035 * @return $str The converted string with no dashed, but underscores
2037 public static final function convertDashesToUnderscores ($str) {
2039 $str = str_replace('-', '_', $str);
2041 // Return converted string
2046 * Marks up the code by adding e.g. line numbers
2048 * @param $phpCode Unmarked PHP code
2049 * @return $markedCode Marked PHP code
2051 public function markupCode ($phpCode) {
2056 $errorArray = error_get_last();
2058 // Init the code with error message
2059 if (is_array($errorArray)) {
2061 $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>',
2062 basename($errorArray['file']),
2063 $errorArray['line'],
2064 $errorArray['message'],
2069 // Add line number to the code
2070 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2072 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2074 htmlentities($code, ENT_QUOTES)
2083 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2084 * beatiful for web-based front-ends. If null is given a message id
2085 * null_timestamp will be resolved and returned.
2087 * @param $timestamp Timestamp to prepare (filter) for display
2088 * @return $readable A readable timestamp
2090 public function doFilterFormatTimestamp ($timestamp) {
2091 // Default value to return
2094 // Is the timestamp null?
2095 if (is_null($timestamp)) {
2096 // Get a message string
2097 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2099 switch ($this->getLanguageInstance()->getLanguageCode()) {
2100 case 'de': // German format is a bit different to default
2101 // Split the GMT stamp up
2102 $dateTime = explode(' ', $timestamp );
2103 $dateArray = explode('-', $dateTime[0]);
2104 $timeArray = explode(':', $dateTime[1]);
2106 // Construct the timestamp
2107 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2117 default: // Default is pass-through
2118 $readable = $timestamp;
2128 * Filter a given number into a localized number
2130 * @param $value The raw value from e.g. database
2131 * @return $localized Localized value
2133 public function doFilterFormatNumber ($value) {
2134 // Generate it from config and localize dependencies
2135 switch ($this->getLanguageInstance()->getLanguageCode()) {
2136 case 'de': // German format is a bit different to default
2137 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2140 default: // US, etc.
2141 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2150 * "Getter" for databse entry
2152 * @return $entry An array with database entries
2153 * @throws NullPointerException If the database result is not found
2154 * @throws InvalidDatabaseResultException If the database result is invalid
2156 protected final function getDatabaseEntry () {
2157 // Is there an instance?
2158 if (!$this->getResultInstance() instanceof SearchableResult) {
2159 // Throw an exception here
2160 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2164 $this->getResultInstance()->rewind();
2166 // Do we have an entry?
2167 if ($this->getResultInstance()->valid() === FALSE) {
2168 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2169 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2173 $this->getResultInstance()->next();
2176 $entry = $this->getResultInstance()->current();
2183 * Getter for field name
2185 * @param $fieldName Field name which we shall get
2186 * @return $fieldValue Field value from the user
2187 * @throws NullPointerException If the result instance is null
2189 public final function getField ($fieldName) {
2190 // Default field value
2193 // Get result instance
2194 $resultInstance = $this->getResultInstance();
2196 // Is this instance null?
2197 if (is_null($resultInstance)) {
2198 // Then the user instance is no longer valid (expired cookies?)
2199 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2202 // Get current array
2203 $fieldArray = $resultInstance->current();
2204 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2206 // Convert dashes to underscore
2207 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2209 // Does the field exist?
2210 if ($this->isFieldSet($fieldName)) {
2212 $fieldValue = $fieldArray[$fieldName2];
2213 } elseif (defined('DEVELOPER')) {
2214 // Missing field entry, may require debugging
2215 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2217 // Missing field entry, may require debugging
2218 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2226 * Checks if given field is set
2228 * @param $fieldName Field name to check
2229 * @return $isSet Whether the given field name is set
2230 * @throws NullPointerException If the result instance is null
2232 public function isFieldSet ($fieldName) {
2233 // Get result instance
2234 $resultInstance = $this->getResultInstance();
2236 // Is this instance null?
2237 if (is_null($resultInstance)) {
2238 // Then the user instance is no longer valid (expired cookies?)
2239 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2242 // Get current array
2243 $fieldArray = $resultInstance->current();
2244 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2246 // Convert dashes to underscore
2247 $fieldName = self::convertDashesToUnderscores($fieldName);
2250 $isSet = isset($fieldArray[$fieldName]);
2257 * Flushs all pending updates to the database layer
2261 public function flushPendingUpdates () {
2262 // Get result instance
2263 $resultInstance = $this->getResultInstance();
2265 // Do we have data to update?
2266 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2267 // Get wrapper class name config entry
2268 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2270 // Create object instance
2271 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2273 // Yes, then send the whole result to the database layer
2274 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2279 * Outputs a deprecation warning to the developer.
2281 * @param $message The message we shall output to the developer
2283 * @todo Write a logging mechanism for productive mode
2285 public function deprecationWarning ($message) {
2286 // Is developer mode active?
2287 if (defined('DEVELOPER')) {
2288 // Debug instance is there?
2289 if (!is_null($this->getDebugInstance())) {
2290 // Output stub message
2291 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2294 trigger_error($message . "<br />\n");
2298 // @TODO Finish this part!
2299 $this->partialStub('Developer mode inactive. Message:' . $message);
2304 * Checks whether the given PHP extension is loaded
2306 * @param $phpExtension The PHP extension we shall check
2307 * @return $isLoaded Whether the PHP extension is loaded
2309 public final function isPhpExtensionLoaded ($phpExtension) {
2311 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2318 * "Getter" as a time() replacement but with milliseconds. You should use this
2319 * method instead of the encapsulated getimeofday() function.
2321 * @return $milliTime Timestamp with milliseconds
2323 public function getMilliTime () {
2324 // Get the time of day as float
2325 $milliTime = gettimeofday(TRUE);
2332 * Idles (sleeps) for given milliseconds
2334 * @return $hasSlept Whether it goes fine
2336 public function idle ($milliSeconds) {
2337 // Sleep is fine by default
2340 // Idle so long with found function
2341 if (function_exists('time_sleep_until')) {
2342 // Get current time and add idle time
2343 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2345 // New PHP 5.1.0 function found, ignore errors
2346 $hasSlept = @time_sleep_until($sleepUntil);
2349 * My Sun station doesn't have that function even with latest PHP
2352 usleep($milliSeconds * 1000);
2359 * Converts a hexadecimal string, even with negative sign as first string to
2360 * a decimal number using BC functions.
2362 * This work is based on comment #86673 on php.net documentation page at:
2363 * <http://de.php.net/manual/en/function.dechex.php#86673>
2365 * @param $hex Hexadecimal string
2366 * @return $dec Decimal number
2368 protected function hex2dec ($hex) {
2369 // Convert to all lower-case
2370 $hex = strtolower($hex);
2372 // Detect sign (negative/positive numbers)
2374 if (substr($hex, 0, 1) == '-') {
2376 $hex = substr($hex, 1);
2379 // Decode the hexadecimal string into a decimal number
2381 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2382 $factor = self::$hexdec[substr($hex, $i, 1)];
2383 $dec = bcadd($dec, bcmul($factor, $e));
2386 // Return the decimal number
2387 return $sign . $dec;
2391 * Converts even very large decimal numbers, also signed, to a hexadecimal
2394 * This work is based on comment #97756 on php.net documentation page at:
2395 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2397 * @param $dec Decimal number, even with negative sign
2398 * @param $maxLength Optional maximum length of the string
2399 * @return $hex Hexadecimal string
2401 protected function dec2hex ($dec, $maxLength = 0) {
2402 // maxLength can be zero or devideable by 2
2403 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2405 // Detect sign (negative/positive numbers)
2412 // Encode the decimal number into a hexadecimal string
2415 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2417 } while ($dec >= 1);
2420 * Leading zeros are required for hex-decimal "numbers". In some
2421 * situations more leading zeros are wanted, so check for both
2424 if ($maxLength > 0) {
2425 // Prepend more zeros
2426 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2427 } elseif ((strlen($hex) % 2) != 0) {
2428 // Only make string's length dividable by 2
2432 // Return the hexadecimal string
2433 return $sign . $hex;
2437 * Converts a ASCII string (0 to 255) into a decimal number.
2439 * @param $asc The ASCII string to be converted
2440 * @return $dec Decimal number
2442 protected function asc2dec ($asc) {
2443 // Convert it into a hexadecimal number
2444 $hex = bin2hex($asc);
2446 // And back into a decimal number
2447 $dec = $this->hex2dec($hex);
2454 * Converts a decimal number into an ASCII string.
2456 * @param $dec Decimal number
2457 * @return $asc An ASCII string
2459 protected function dec2asc ($dec) {
2460 // First convert the number into a hexadecimal string
2461 $hex = $this->dec2hex($dec);
2463 // Then convert it into the ASCII string
2464 $asc = $this->hex2asc($hex);
2471 * Converts a hexadecimal number into an ASCII string. Negative numbers
2474 * @param $hex Hexadecimal string
2475 * @return $asc An ASCII string
2477 protected function hex2asc ($hex) {
2478 // Check for length, it must be devideable by 2
2479 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2480 assert((strlen($hex) % 2) == 0);
2484 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2485 // Get the decimal number of the chunk
2486 $part = hexdec(substr($hex, $idx, 2));
2488 // Add it to the final string
2492 // Return the final string
2497 * Checks whether the given encoded data was encoded with Base64
2499 * @param $encodedData Encoded data we shall check
2500 * @return $isBase64 Whether the encoded data is Base64
2502 protected function isBase64Encoded ($encodedData) {
2504 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2511 * "Getter" to get response/request type from analysis of the system.
2513 * @return $responseType Analyzed response type
2515 protected static function getResponseTypeFromSystem () {
2516 // Default is console
2517 $responseType = 'console';
2519 // Is 'HTTP_HOST' set?
2520 if (isset($_SERVER['HTTP_HOST'])) {
2522 * Then it is a HTML response/request as RSS and so on may be
2523 * transfered over HTTP as well.
2525 $responseType = 'html';
2529 return $responseType;
2533 * Gets a cache key from Criteria instance
2535 * @param $criteriaInstance An instance of a Criteria class
2536 * @param $onlyKeys Only use these keys for a cache key
2537 * @return $cacheKey A cache key suitable for lookup/storage purposes
2539 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2541 $cacheKey = sprintf('%s@%s',
2542 $this->__toString(),
2543 $criteriaInstance->getCacheKey($onlyKeys)
2547 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2552 * Getter for startup time in miliseconds
2554 * @return $startupTime Startup time in miliseconds
2556 protected function getStartupTime () {
2557 return self::$startupTime;
2561 * "Getter" for a printable currently execution time in nice braces
2563 * @return $executionTime Current execution time in nice braces
2565 protected function getPrintableExecutionTime () {
2566 // Caculate the execution time
2567 $executionTime = microtime(TRUE) - $this->getStartupTime();
2569 // Pack it in nice braces
2570 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2573 return $executionTime;
2577 * Hashes a given string with a simple but stronger hash function (no salt)
2578 * and hex-encode it.
2580 * @param $str The string to be hashed
2581 * @return $hash The hash from string $str
2583 public static final function hash ($str) {
2584 // Hash given string with (better secure) hasher
2585 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2592 * "Getter" for length of hash() output. This will be "cached" to speed up
2595 * @return $length Length of hash() output
2597 public static final function getHashLength () {
2599 if (is_null(self::$hashLength)) {
2600 // No, then hash a string and save its length.
2601 self::$hashLength = strlen(self::hash('abc123'));
2605 return self::$hashLength;
2609 * Checks whether the given number is really a number (only chars 0-9).
2611 * @param $num A string consisting only chars between 0 and 9
2612 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2613 * @param $assertMismatch Whether to assert mismatches
2614 * @return $ret The (hopefully) secured numbered value
2616 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2617 // Filter all numbers out
2618 $ret = preg_replace('/[^0123456789]/', '', $num);
2621 if ($castValue === TRUE) {
2622 // Cast to biggest numeric type
2623 $ret = (double) $ret;
2626 // Assert only if requested
2627 if ($assertMismatch === TRUE) {
2628 // Has the whole value changed?
2629 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2637 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2639 * @param $num A string consisting only chars between 0 and 9
2640 * @param $assertMismatch Whether to assert mismatches
2641 * @return $ret The (hopefully) secured hext-numbered value
2643 public function hexval ($num, $assertMismatch = FALSE) {
2644 // Filter all numbers out
2645 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2647 // Assert only if requested
2648 if ($assertMismatch === TRUE) {
2649 // Has the whole value changed?
2650 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2658 * Checks whether start/end marker are set
2660 * @param $data Data to be checked
2661 * @return $isset Whether start/end marker are set
2663 public final function ifStartEndMarkersSet ($data) {
2665 $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));
2667 // ... and return it
2672 * Determines if an element is set in the generic array
2674 * @param $keyGroup Main group for the key
2675 * @param $subGroup Sub group for the key
2676 * @param $key Key to check
2677 * @param $element Element to check
2678 * @return $isset Whether the given key is set
2680 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2682 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2685 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2691 * Determines if a key is set in the generic array
2693 * @param $keyGroup Main group for the key
2694 * @param $subGroup Sub group for the key
2695 * @param $key Key to check
2696 * @return $isset Whether the given key is set
2698 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2700 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2703 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2711 * Determines if a group is set in the generic array
2713 * @param $keyGroup Main group
2714 * @param $subGroup Sub group
2715 * @return $isset Whether the given group is set
2717 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2719 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2722 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2729 * Getter for sub key group
2731 * @param $keyGroup Main key group
2732 * @param $subGroup Sub key group
2733 * @return $array An array with all array elements
2735 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2737 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2738 // No, then abort here
2739 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2744 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2747 return $this->genericArray[$keyGroup][$subGroup];
2751 * Unsets a given key in generic array
2753 * @param $keyGroup Main group for the key
2754 * @param $subGroup Sub group for the key
2755 * @param $key Key to unset
2758 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2760 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2763 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2767 * Unsets a given element in generic array
2769 * @param $keyGroup Main group for the key
2770 * @param $subGroup Sub group for the key
2771 * @param $key Key to unset
2772 * @param $element Element to unset
2775 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2777 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2780 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2784 * Append a string to a given generic array key
2786 * @param $keyGroup Main group for the key
2787 * @param $subGroup Sub group for the key
2788 * @param $key Key to unset
2789 * @param $value Value to add/append
2792 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2794 //* 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);
2796 // Is it already there?
2797 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2799 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2802 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2807 * Append a string to a given generic array element
2809 * @param $keyGroup Main group for the key
2810 * @param $subGroup Sub group for the key
2811 * @param $key Key to unset
2812 * @param $element Element to check
2813 * @param $value Value to add/append
2816 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2818 //* 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);
2820 // Is it already there?
2821 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2823 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2826 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2831 * Sets a string in a given generic array element
2833 * @param $keyGroup Main group for the key
2834 * @param $subGroup Sub group for the key
2835 * @param $key Key to unset
2836 * @param $element Element to check
2837 * @param $value Value to add/append
2840 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2842 //* 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);
2845 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2849 * Initializes given generic array group
2851 * @param $keyGroup Main group for the key
2852 * @param $subGroup Sub group for the key
2853 * @param $key Key to use
2854 * @param $forceInit Optionally force initialization
2857 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2859 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2861 // Is it already set?
2862 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2863 // Already initialized
2864 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2869 $this->genericArray[$keyGroup][$subGroup] = array();
2873 * Initializes given generic array key
2875 * @param $keyGroup Main group for the key
2876 * @param $subGroup Sub group for the key
2877 * @param $key Key to use
2878 * @param $forceInit Optionally force initialization
2881 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2883 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2885 // Is it already set?
2886 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2887 // Already initialized
2888 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2893 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2897 * Initializes given generic array element
2899 * @param $keyGroup Main group for the key
2900 * @param $subGroup Sub group for the key
2901 * @param $key Key to use
2902 * @param $element Element to use
2903 * @param $forceInit Optionally force initialization
2906 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2908 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2910 // Is it already set?
2911 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2912 // Already initialized
2913 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2918 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2922 * Pushes an element to a generic key
2924 * @param $keyGroup Main group for the key
2925 * @param $subGroup Sub group for the key
2926 * @param $key Key to use
2927 * @param $value Value to add/append
2928 * @return $count Number of array elements
2930 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2932 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2935 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2937 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2941 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2944 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2945 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2950 * Pushes an element to a generic array element
2952 * @param $keyGroup Main group for the key
2953 * @param $subGroup Sub group for the key
2954 * @param $key Key to use
2955 * @param $element Element to check
2956 * @param $value Value to add/append
2957 * @return $count Number of array elements
2959 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2961 //* 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));
2964 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2966 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2970 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2973 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2974 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2979 * Pops an element from a generic group
2981 * @param $keyGroup Main group for the key
2982 * @param $subGroup Sub group for the key
2983 * @param $key Key to unset
2984 * @return $value Last "popped" value
2986 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2988 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2991 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2993 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2998 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
3001 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3002 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3007 * Shifts an element from a generic group
3009 * @param $keyGroup Main group for the key
3010 * @param $subGroup Sub group for the key
3011 * @param $key Key to unset
3012 * @return $value Last "popped" value
3014 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3016 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3019 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3021 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3026 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3029 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3030 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3035 * Count generic array group
3037 * @param $keyGroup Main group for the key
3038 * @return $count Count of given group
3040 protected final function countGenericArray ($keyGroup) {
3042 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3045 if (!isset($this->genericArray[$keyGroup])) {
3047 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3052 $count = count($this->genericArray[$keyGroup]);
3055 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3062 * Count generic array sub group
3064 * @param $keyGroup Main group for the key
3065 * @param $subGroup Sub group for the key
3066 * @return $count Count of given group
3068 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3070 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3073 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3075 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3080 $count = count($this->genericArray[$keyGroup][$subGroup]);
3083 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3090 * Count generic array elements
3092 * @param $keyGroup Main group for the key
3093 * @param $subGroup Sub group for the key
3094 * @para $key Key to count
3095 * @return $count Count of given key
3097 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3099 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3102 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3104 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3106 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3108 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3113 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3116 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3123 * Getter for whole generic group array
3125 * @param $keyGroup Key group to get
3126 * @return $array Whole generic array group
3128 protected final function getGenericArray ($keyGroup) {
3130 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3133 if (!isset($this->genericArray[$keyGroup])) {
3135 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3140 return $this->genericArray[$keyGroup];
3144 * Setter for generic array key
3146 * @param $keyGroup Key group to get
3147 * @param $subGroup Sub group for the key
3148 * @param $key Key to unset
3149 * @param $value Mixed value from generic array element
3152 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3154 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3157 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3161 * Getter for generic array key
3163 * @param $keyGroup Key group to get
3164 * @param $subGroup Sub group for the key
3165 * @param $key Key to unset
3166 * @return $value Mixed value from generic array element
3168 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3170 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3173 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3175 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3180 return $this->genericArray[$keyGroup][$subGroup][$key];
3184 * Sets a value in given generic array key/element
3186 * @param $keyGroup Main group for the key
3187 * @param $subGroup Sub group for the key
3188 * @param $key Key to set
3189 * @param $element Element to set
3190 * @param $value Value to set
3193 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3195 //* 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));
3198 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3202 * Getter for generic array element
3204 * @param $keyGroup Key group to get
3205 * @param $subGroup Sub group for the key
3206 * @param $key Key to look for
3207 * @param $element Element to look for
3208 * @return $value Mixed value from generic array element
3210 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3212 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3215 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3217 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3222 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3226 * Checks if a given sub group is valid (array)
3228 * @param $keyGroup Key group to get
3229 * @param $subGroup Sub group for the key
3230 * @return $isValid Whether given sub group is valid
3232 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3234 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3237 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3244 * Checks if a given key is valid (array)
3246 * @param $keyGroup Key group to get
3247 * @param $subGroup Sub group for the key
3248 * @param $key Key to check
3249 * @return $isValid Whether given sub group is valid
3251 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3253 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3256 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3263 * Initializes the web output instance
3267 protected function initWebOutputInstance () {
3268 // Get application instance
3269 $applicationInstance = Registry::getRegistry()->getInstance('app');
3271 // Is this a response instance?
3272 if ($this instanceof Responseable) {
3273 // Then set it in application instance
3274 $applicationInstance->setResponseInstance($this);
3277 // Init web output instance
3278 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3281 $this->setWebOutputInstance($outputInstance);
3285 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3287 * @param $boolean Boolean value
3288 * @return $translated Translated boolean value
3290 public static final function translateBooleanToYesNo ($boolean) {
3291 // Make sure it is really boolean
3292 assert(is_bool($boolean));
3295 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3297 // ... and return it
3302 * Encodes raw data (almost any type) by "serializing" it and then pack it
3303 * into a "binary format".
3305 * @param $rawData Raw data (almost any type)
3306 * @return $encoded Encoded data
3308 protected function encodeData ($rawData) {
3309 // Make sure no objects or resources pass through
3310 assert(!is_object($rawData));
3311 assert(!is_resource($rawData));
3313 // First "serialize" it (json_encode() is faster than serialize())
3314 $encoded = $this->packString(json_encode($rawData));
3321 * Pack a string into a "binary format". Please execuse me that this is
3322 * widely undocumented. :-(
3324 * @param $str Unpacked string
3325 * @return $packed Packed string
3326 * @todo Improve documentation
3328 protected function packString ($str) {
3330 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3332 // First compress the string (gzcompress is okay)
3333 $str = gzcompress($str);
3338 // And start the "encoding" loop
3339 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3341 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3342 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3344 if (($idx + $i) <= strlen($str)) {
3345 $ord = ord(substr($str, ($idx + $i), 1));
3347 $add = $ord * pow(256, $factor);
3351 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3355 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3356 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3358 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3359 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3365 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3370 * Checks whether the given file/path is in open_basedir(). This does not
3371 * gurantee that the file is actually readable and/or writeable. If you need
3372 * such gurantee then please use isReadableFile() instead.
3374 * @param $filePathName Name of the file/path to be checked
3375 * @return $isReachable Whether it is within open_basedir()
3377 protected static function isReachableFilePath ($filePathName) {
3378 // Is not reachable by default
3379 $isReachable = FALSE;
3381 // Get open_basedir parameter
3382 $openBaseDir = ini_get('open_basedir');
3385 if (!empty($openBaseDir)) {
3386 // Check all entries
3387 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3388 // Check on existence
3389 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3391 $isReachable = TRUE;
3395 // If open_basedir is not set, all is allowed
3396 $isReachable = TRUE;
3400 return $isReachable;
3404 * Checks whether the give file is within open_basedir() (done by
3405 * isReachableFilePath()), is actually a file and is readable.
3407 * @param $fileName Name of the file to be checked
3408 * @return $isReadable Whether the file is readable (and therefor exists)
3410 public static function isReadableFile ($fileName) {
3411 // Default is not readable
3412 $isReadable = FALSE;
3414 // Is within parameters, so check if it is a file and readable
3415 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3422 * Creates a full-qualified file name (FQFN) for given file name by adding
3423 * a configured temporary file path to it.
3425 * @param $fileName Name for temporary file
3426 * @return $fqfn Full-qualified file name
3427 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3428 * @throws FileIoException If the file cannot be written
3430 protected static function createTempPathForFile ($fileName) {
3432 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3434 // Is the path writeable?
3435 if (!is_writable($basePath)) {
3436 // Path is write-protected
3437 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3441 $fqfn = $basePath . '/' . $fileName;
3444 if (!self::isReachableFilePath($fqfn)) {
3446 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3454 * "Getter" for a printable state name
3456 * @return $stateName Name of the node's state in a printable format
3458 public final function getPrintableState () {
3459 // Default is 'null'
3460 $stateName = 'null';
3462 // Get the state instance
3463 $stateInstance = $this->getStateInstance();
3465 // Is it an instance of Stateable?
3466 if ($stateInstance instanceof Stateable) {
3467 // Then use that state name
3468 $stateName = $stateInstance->getStateName();
3476 * Handles socket error for given socket resource and peer data. This method
3477 * validates $socketResource if it is a valid resource (see is_resource())
3478 * but assumes valid data in array $recipientData, except that
3479 * count($recipientData) is always 2.
3481 * @param $method Value of __METHOD__ from calling method
3482 * @param $line Value of __LINE__ from calling method
3483 * @param $socketResource A valid socket resource
3484 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3486 * @throws InvalidSocketException If $socketResource is no socket resource
3487 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3488 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3490 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3491 // This method handles only socket resources
3492 if (!is_resource($socketResource)) {
3493 // No resource, abort here
3494 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3497 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3498 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3499 assert(isset($socketData[0]));
3500 assert(isset($socketData[1]));
3502 // Get error code for first validation (0 is not an error)
3503 $errorCode = socket_last_error($socketResource);
3505 // If the error code is zero, someone called this method without an error
3506 if ($errorCode == 0) {
3507 // No error detected (or previously cleared outside this method)
3508 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3511 // Get handler (method) name
3512 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3514 // Call-back the error handler method
3515 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3517 // Finally clear the error because it has been handled
3518 socket_clear_error($socketResource);