3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Controller\Controller;
8 use CoreFramework\Criteria\Criteria;
9 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
10 use CoreFramework\Factory\ObjectFactory;
11 use CoreFramework\Generic\FrameworkInterface;
12 use CoreFramework\Generic\NullPointerException;
13 use CoreFramework\Handler\Stream\IoHandler;
14 use CoreFramework\Loader\ClassLoader;
15 use CoreFramework\Manager\ManageableApplication;
16 use CoreFramework\Middleware\Debug\DebugMiddleware;
17 use CoreFramework\Registry\Register;
18 use CoreFramework\Registry\Registry;
19 use CoreFramework\Request\Requestable;
20 use CoreFramework\Resolver\Resolver;
21 use CoreFramework\Response\Responseable;
22 use CoreFramework\Stream\Output\OutputStreamer;
23 use CoreFramework\Template\CompileableTemplate;
29 * The simulator system class is the super class of all other classes. This
30 * class handles saving of games etc.
32 * @author Roland Haeder <webmaster@shipsimu.org>
34 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
35 * @license GNU GPL 3.0 or any newer version
36 * @link http://www.shipsimu.org
38 * This program is free software: you can redistribute it and/or modify
39 * it under the terms of the GNU General Public License as published by
40 * the Free Software Foundation, either version 3 of the License, or
41 * (at your option) any later version.
43 * This program is distributed in the hope that it will be useful,
44 * but WITHOUT ANY WARRANTY; without even the implied warranty of
45 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
46 * GNU General Public License for more details.
48 * You should have received a copy of the GNU General Public License
49 * along with this program. If not, see <http://www.gnu.org/licenses/>.
51 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
53 * Length of output from hash()
55 private static $hashLength = NULL;
60 private $realClass = 'BaseFrameworkSystem';
63 * Instance of a Requestable class
65 private $requestInstance = NULL;
68 * Instance of a Responseable class
70 private $responseInstance = NULL;
73 * Search criteria instance
75 private $searchInstance = NULL;
78 * Update criteria instance
80 private $updateInstance = NULL;
83 * The file I/O instance for the template loader
85 private $fileIoInstance = NULL;
90 private $resolverInstance = NULL;
93 * Template engine instance
95 private $templateInstance = NULL;
98 * Database result instance
100 private $resultInstance = NULL;
103 * Instance for user class
105 private $userInstance = NULL;
108 * A controller instance
110 private $controllerInstance = NULL;
115 private $rngInstance = NULL;
118 * Instance of a crypto helper
120 private $cryptoInstance = NULL;
123 * Instance of an Iterator class
125 private $iteratorInstance = NULL;
128 * Instance of the list
130 private $listInstance = NULL;
135 private $menuInstance = NULL;
138 * Instance of the image
140 private $imageInstance = NULL;
143 * Instance of the stacker
145 private $stackInstance = NULL;
148 * A Compressor instance
150 private $compressorInstance = NULL;
153 * A Parseable instance
155 private $parserInstance = NULL;
158 * A HandleableProtocol instance
160 private $protocolInstance = NULL;
163 * A database wrapper instance
165 private $databaseInstance = NULL;
168 * A helper instance for the form
170 private $helperInstance = NULL;
173 * An instance of a Source class
175 private $sourceInstance = NULL;
178 * An instance of a UrlSource class
180 private $urlSourceInstance = NULL;
183 * An instance of a InputStream class
185 private $inputStreamInstance = NULL;
188 * An instance of a OutputStream class
190 private $outputStreamInstance = NULL;
193 * Networkable handler instance
195 private $handlerInstance = NULL;
198 * Visitor handler instance
200 private $visitorInstance = NULL;
205 private $dhtInstance = NULL;
208 * An instance of a database wrapper class
210 private $wrapperInstance = NULL;
213 * An instance of a file I/O pointer class (not handler)
215 private $pointerInstance = NULL;
218 * An instance of an Indexable class
220 private $indexInstance = NULL;
223 * An instance of a Block class
225 private $blockInstance = NULL;
230 private $minableInstance = NULL;
233 * A FrameworkDirectory instance
235 private $directoryInstance = NULL;
240 private $listenerInstance = NULL;
243 * An instance of a communicator
245 private $communicatorInstance = NULL;
248 * The concrete output instance
250 private $outputInstance = NULL;
255 private $stateInstance = NULL;
258 * Thousands separator
260 private $thousands = '.'; // German
265 private $decimals = ','; // German
270 private $socketResource = FALSE;
273 * Regular expression to use for validation
275 private $regularExpression = '';
280 private $packageData = array();
285 private $genericArray = array();
290 private $commandName = '';
295 private $controllerName = '';
298 * Name of used protocol
300 private $protocolName = 'invalid';
303 * Array with bitmasks and such for pack/unpack methods to support both
304 * 32-bit and 64-bit systems
306 private $packingData = array(
309 'left' => 0xffff0000,
310 'right' => 0x0000ffff,
316 'left' => 0xffffffff00000000,
317 'right' => 0x00000000ffffffff,
324 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
326 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
328 private $archArrayElement = FALSE;
330 /***********************
331 * Exception codes.... *
332 ***********************/
334 // @todo Try to clean these constants up
335 const EXCEPTION_IS_NULL_POINTER = 0x001;
336 const EXCEPTION_IS_NO_OBJECT = 0x002;
337 const EXCEPTION_IS_NO_ARRAY = 0x003;
338 const EXCEPTION_MISSING_METHOD = 0x004;
339 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
340 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
341 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
342 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
343 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
344 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
345 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
346 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
347 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
348 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
349 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
350 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
351 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
352 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
353 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
354 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
355 const EXCEPTION_PATH_NOT_FOUND = 0x015;
356 const EXCEPTION_INVALID_PATH_NAME = 0x016;
357 const EXCEPTION_READ_PROTECED_PATH = 0x017;
358 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
359 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
360 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
361 const EXCEPTION_INVALID_RESOURCE = 0x01b;
362 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
363 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
364 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
365 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
366 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
367 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
368 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
369 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
370 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
371 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
372 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
373 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
374 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
375 const EXCEPTION_INVALID_STRING = 0x029;
376 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
377 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
378 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
379 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
380 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
381 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
382 const EXCEPTION_MISSING_ELEMENT = 0x030;
383 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
384 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
385 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
386 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
387 const EXCEPTION_FATAL_ERROR = 0x035;
388 const EXCEPTION_FILE_NOT_FOUND = 0x036;
389 const EXCEPTION_ASSERTION_FAILED = 0x037;
390 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
391 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
392 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
393 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
394 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
395 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
398 * Hexadecimal->Decimal translation array
400 private static $hexdec = array(
420 * Decimal->hexadecimal translation array
422 private static $dechex = array(
442 * Startup time in miliseconds
444 private static $startupTime = 0;
447 * Protected super constructor
449 * @param $className Name of the class
452 protected function __construct ($className) {
454 $this->setRealClass($className);
456 // Set configuration instance if no registry ...
457 if (!$this instanceof Register) {
458 // ... because registries doesn't need to be configured
459 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
462 // Is the startup time set? (0 cannot be TRUE anymore)
463 if (self::$startupTime == 0) {
465 self::$startupTime = microtime(TRUE);
469 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
473 * Destructor for all classes. You should not call this method on your own.
477 public function __destruct () {
478 // Flush any updated entries to the database
479 $this->flushPendingUpdates();
481 // Is this object already destroyed?
482 if ($this->__toString() != 'DestructedObject') {
483 // Destroy all informations about this class but keep some text about it alive
484 $this->setRealClass('DestructedObject');
485 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
486 // Already destructed object
487 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
492 // Do not call this twice
493 trigger_error(__METHOD__ . ': Called twice.');
499 * The __call() method where all non-implemented methods end up
501 * @param $methodName Name of the missing method
502 * @args $args Arguments passed to the method
505 public final function __call ($methodName, $args) {
506 return self::__callStatic($methodName, $args);
510 * The __callStatic() method where all non-implemented static methods end up
512 * @param $methodName Name of the missing method
513 * @args $args Arguments passed to the method
516 public static final function __callStatic ($methodName, $args) {
518 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
520 // Init argument string
523 // Is it NULL, empty or an array?
524 if (is_null($args)) {
526 $argsString = 'NULL';
527 } elseif (is_array($args)) {
531 // Some arguments are there
532 foreach ($args as $arg) {
533 // Add data about the argument
534 $argsString .= gettype($arg) . ':';
537 // Found a NULL argument
538 $argsString .= 'NULL';
539 } elseif (is_string($arg)) {
540 // Add length for strings
541 $argsString .= strlen($arg);
542 } elseif ((is_int($arg)) || (is_float($arg))) {
545 } elseif (is_array($arg)) {
546 // .. or size if array
547 $argsString .= count($arg);
548 } elseif (is_object($arg)) {
550 $reflection = new ReflectionClass($arg);
552 // Is an other object, maybe no __toString() available
553 $argsString .= $reflection->getName();
554 } elseif ($arg === TRUE) {
555 // ... is boolean 'TRUE'
556 $argsString .= 'TRUE';
557 } elseif ($arg === FALSE) {
558 // ... is boolean 'FALSE'
559 $argsString .= 'FALSE';
562 // Comma for next one
567 if (substr($argsString, -2, 1) == ',') {
568 $argsString = substr($argsString, 0, -2);
574 // Invalid arguments!
575 $argsString = '!INVALID:' . gettype($args) . '!';
578 // Output stub message
579 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
580 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
590 * Getter for $realClass
592 * @return $realClass The name of the real class (not BaseFrameworkSystem)
594 public function __toString () {
595 return $this->realClass;
599 * Magic method to catch setting of missing but set class fields/attributes
601 * @param $name Name of the field/attribute
602 * @param $value Value to store
605 public final function __set ($name, $value) {
606 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
609 print_r($value, TRUE)
614 * Magic method to catch getting of missing fields/attributes
616 * @param $name Name of the field/attribute
619 public final function __get ($name) {
620 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
626 * Magic method to catch unsetting of missing fields/attributes
628 * @param $name Name of the field/attribute
631 public final function __unset ($name) {
632 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
638 * Magic method to catch object serialization
640 * @return $unsupported Unsupported method
641 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
643 public final function __sleep () {
644 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
648 * Magic method to catch object deserialization
650 * @return $unsupported Unsupported method
651 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
653 public final function __wakeup () {
654 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
658 * Magic method to catch calls when an object instance is called
660 * @return $unsupported Unsupported method
661 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
663 public final function __invoke () {
664 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
668 * Setter for the real class name
670 * @param $realClass Class name (string)
673 public final function setRealClass ($realClass) {
675 $this->realClass = (string) $realClass;
679 * Setter for database result instance
681 * @param $resultInstance An instance of a database result class
683 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
685 protected final function setResultInstance (SearchableResult $resultInstance) {
686 $this->resultInstance = $resultInstance;
690 * Getter for database result instance
692 * @return $resultInstance An instance of a database result class
694 public final function getResultInstance () {
695 return $this->resultInstance;
699 * Setter for template engine instances
701 * @param $templateInstance An instance of a template engine class
704 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
705 $this->templateInstance = $templateInstance;
709 * Getter for template engine instances
711 * @return $templateInstance An instance of a template engine class
713 protected final function getTemplateInstance () {
714 return $this->templateInstance;
718 * Setter for search instance
720 * @param $searchInstance Searchable criteria instance
723 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
724 $this->searchInstance = $searchInstance;
728 * Getter for search instance
730 * @return $searchInstance Searchable criteria instance
732 public final function getSearchInstance () {
733 return $this->searchInstance;
737 * Setter for update instance
739 * @param $updateInstance Searchable criteria instance
742 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
743 $this->updateInstance = $updateInstance;
747 * Getter for update instance
749 * @return $updateInstance Updateable criteria instance
751 public final function getUpdateInstance () {
752 return $this->updateInstance;
756 * Setter for resolver instance
758 * @param $resolverInstance Instance of a command resolver class
761 public final function setResolverInstance (Resolver $resolverInstance) {
762 $this->resolverInstance = $resolverInstance;
766 * Getter for resolver instance
768 * @return $resolverInstance Instance of a command resolver class
770 public final function getResolverInstance () {
771 return $this->resolverInstance;
775 * Setter for language instance
777 * @param $configInstance The configuration instance which shall
778 * be FrameworkConfiguration
781 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
782 Registry::getRegistry()->addInstance('config', $configInstance);
786 * Getter for configuration instance
788 * @return $configInstance Configuration instance
790 public final function getConfigInstance () {
791 $configInstance = Registry::getRegistry()->getInstance('config');
792 return $configInstance;
796 * Setter for debug instance
798 * @param $debugInstance The instance for debug output class
801 public final function setDebugInstance (DebugMiddleware $debugInstance) {
802 Registry::getRegistry()->addInstance('debug', $debugInstance);
806 * Getter for debug instance
808 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
810 public final function getDebugInstance () {
811 // Get debug instance
812 $debugInstance = Registry::getRegistry()->getInstance('debug');
815 return $debugInstance;
819 * Setter for web output instance
821 * @param $webInstance The instance for web output class
824 public final function setWebOutputInstance (OutputStreamer $webInstance) {
825 Registry::getRegistry()->addInstance('web_output', $webInstance);
829 * Getter for web output instance
831 * @return $webOutputInstance - Instance to class WebOutput
833 public final function getWebOutputInstance () {
834 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
835 return $webOutputInstance;
839 * Setter for database instance
841 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
844 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
845 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
849 * Getter for database layer
851 * @return $databaseInstance The database layer instance
853 public final function getDatabaseInstance () {
855 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
858 return $databaseInstance;
862 * Setter for compressor channel
864 * @param $compressorInstance An instance of CompressorChannel
867 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
868 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
872 * Getter for compressor channel
874 * @return $compressorInstance The compressor channel
876 public final function getCompressorChannel () {
877 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
878 return $compressorInstance;
882 * Protected getter for a manageable application helper class
884 * @return $applicationInstance An instance of a manageable application helper class
886 protected final function getApplicationInstance () {
887 $applicationInstance = Registry::getRegistry()->getInstance('application');
888 return $applicationInstance;
892 * Setter for a manageable application helper class
894 * @param $applicationInstance An instance of a manageable application helper class
897 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
898 Registry::getRegistry()->addInstance('application', $applicationInstance);
902 * Setter for request instance
904 * @param $requestInstance An instance of a Requestable class
907 public final function setRequestInstance (Requestable $requestInstance) {
908 $this->requestInstance = $requestInstance;
912 * Getter for request instance
914 * @return $requestInstance An instance of a Requestable class
916 public final function getRequestInstance () {
917 return $this->requestInstance;
921 * Setter for response instance
923 * @param $responseInstance An instance of a Responseable class
926 public final function setResponseInstance (Responseable $responseInstance) {
927 $this->responseInstance = $responseInstance;
931 * Getter for response instance
933 * @return $responseInstance An instance of a Responseable class
935 public final function getResponseInstance () {
936 return $this->responseInstance;
940 * Private getter for language instance
942 * @return $langInstance An instance to the language sub-system
944 protected final function getLanguageInstance () {
945 $langInstance = Registry::getRegistry()->getInstance('language');
946 return $langInstance;
950 * Setter for language instance
952 * @param $langInstance An instance to the language sub-system
954 * @see LanguageSystem
956 public final function setLanguageInstance (ManageableLanguage $langInstance) {
957 Registry::getRegistry()->addInstance('language', $langInstance);
961 * Private getter for file IO instance
963 * @return $fileIoInstance An instance to the file I/O sub-system
965 protected final function getFileIoInstance () {
966 return $this->fileIoInstance;
970 * Setter for file I/O instance
972 * @param $fileIoInstance An instance to the file I/O sub-system
975 public final function setFileIoInstance (IoHandler $fileIoInstance) {
976 $this->fileIoInstance = $fileIoInstance;
980 * Protected setter for user instance
982 * @param $userInstance An instance of a user class
985 protected final function setUserInstance (ManageableAccount $userInstance) {
986 $this->userInstance = $userInstance;
990 * Getter for user instance
992 * @return $userInstance An instance of a user class
994 public final function getUserInstance () {
995 return $this->userInstance;
999 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1001 * @param $controllerInstance An instance of the controller
1004 public final function setControllerInstance (Controller $controllerInstance) {
1005 $this->controllerInstance = $controllerInstance;
1009 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1011 * @return $controllerInstance An instance of the controller
1013 public final function getControllerInstance () {
1014 return $this->controllerInstance;
1018 * Setter for RNG instance
1020 * @param $rngInstance An instance of a random number generator (RNG)
1023 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1024 $this->rngInstance = $rngInstance;
1028 * Getter for RNG instance
1030 * @return $rngInstance An instance of a random number generator (RNG)
1032 public final function getRngInstance () {
1033 return $this->rngInstance;
1037 * Setter for Cryptable instance
1039 * @param $cryptoInstance An instance of a Cryptable class
1042 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1043 $this->cryptoInstance = $cryptoInstance;
1047 * Getter for Cryptable instance
1049 * @return $cryptoInstance An instance of a Cryptable class
1051 public final function getCryptoInstance () {
1052 return $this->cryptoInstance;
1056 * Setter for the list instance
1058 * @param $listInstance A list of Listable
1061 protected final function setListInstance (Listable $listInstance) {
1062 $this->listInstance = $listInstance;
1066 * Getter for the list instance
1068 * @return $listInstance A list of Listable
1070 protected final function getListInstance () {
1071 return $this->listInstance;
1075 * Setter for the menu instance
1077 * @param $menuInstance A RenderableMenu instance
1080 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1081 $this->menuInstance = $menuInstance;
1085 * Getter for the menu instance
1087 * @return $menuInstance A RenderableMenu instance
1089 protected final function getMenuInstance () {
1090 return $this->menuInstance;
1094 * Setter for image instance
1096 * @param $imageInstance An instance of an image
1099 public final function setImageInstance (BaseImage $imageInstance) {
1100 $this->imageInstance = $imageInstance;
1104 * Getter for image instance
1106 * @return $imageInstance An instance of an image
1108 public final function getImageInstance () {
1109 return $this->imageInstance;
1113 * Setter for stacker instance
1115 * @param $stackInstance An instance of an stacker
1118 public final function setStackInstance (Stackable $stackInstance) {
1119 $this->stackInstance = $stackInstance;
1123 * Getter for stacker instance
1125 * @return $stackInstance An instance of an stacker
1127 public final function getStackInstance () {
1128 return $this->stackInstance;
1132 * Setter for compressor instance
1134 * @param $compressorInstance An instance of an compressor
1137 public final function setCompressorInstance (Compressor $compressorInstance) {
1138 $this->compressorInstance = $compressorInstance;
1142 * Getter for compressor instance
1144 * @return $compressorInstance An instance of an compressor
1146 public final function getCompressorInstance () {
1147 return $this->compressorInstance;
1151 * Setter for Parseable instance
1153 * @param $parserInstance An instance of an Parseable
1156 public final function setParserInstance (Parseable $parserInstance) {
1157 $this->parserInstance = $parserInstance;
1161 * Getter for Parseable instance
1163 * @return $parserInstance An instance of an Parseable
1165 public final function getParserInstance () {
1166 return $this->parserInstance;
1170 * Setter for HandleableProtocol instance
1172 * @param $protocolInstance An instance of an HandleableProtocol
1175 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1176 $this->protocolInstance = $protocolInstance;
1180 * Getter for HandleableProtocol instance
1182 * @return $protocolInstance An instance of an HandleableProtocol
1184 public final function getProtocolInstance () {
1185 return $this->protocolInstance;
1189 * Setter for DatabaseWrapper instance
1191 * @param $wrapperInstance An instance of an DatabaseWrapper
1194 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1195 $this->wrapperInstance = $wrapperInstance;
1199 * Getter for DatabaseWrapper instance
1201 * @return $wrapperInstance An instance of an DatabaseWrapper
1203 public final function getWrapperInstance () {
1204 return $this->wrapperInstance;
1208 * Setter for socket resource
1210 * @param $socketResource A valid socket resource
1213 public final function setSocketResource ($socketResource) {
1214 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1215 $this->socketResource = $socketResource;
1219 * Getter for socket resource
1221 * @return $socketResource A valid socket resource
1223 public final function getSocketResource () {
1224 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1225 return $this->socketResource;
1229 * Setter for regular expression
1231 * @param $regularExpression A valid regular expression
1234 public final function setRegularExpression ($regularExpression) {
1235 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1236 $this->regularExpression = $regularExpression;
1240 * Getter for regular expression
1242 * @return $regularExpression A valid regular expression
1244 public final function getRegularExpression () {
1245 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1246 return $this->regularExpression;
1250 * Setter for helper instance
1252 * @param $helperInstance An instance of a helper class
1255 protected final function setHelperInstance (Helper $helperInstance) {
1256 $this->helperInstance = $helperInstance;
1260 * Getter for helper instance
1262 * @return $helperInstance An instance of a helper class
1264 public final function getHelperInstance () {
1265 return $this->helperInstance;
1269 * Setter for a Source instance
1271 * @param $sourceInstance An instance of a Source class
1274 protected final function setSourceInstance (Source $sourceInstance) {
1275 $this->sourceInstance = $sourceInstance;
1279 * Getter for a Source instance
1281 * @return $sourceInstance An instance of a Source class
1283 protected final function getSourceInstance () {
1284 return $this->sourceInstance;
1288 * Setter for a UrlSource instance
1290 * @param $sourceInstance An instance of a UrlSource class
1293 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1294 $this->urlSourceInstance = $urlSourceInstance;
1298 * Getter for a UrlSource instance
1300 * @return $urlSourceInstance An instance of a UrlSource class
1302 protected final function getUrlSourceInstance () {
1303 return $this->urlSourceInstance;
1307 * Getter for a InputStream instance
1309 * @param $inputStreamInstance The InputStream instance
1311 protected final function getInputStreamInstance () {
1312 return $this->inputStreamInstance;
1316 * Setter for a InputStream instance
1318 * @param $inputStreamInstance The InputStream instance
1321 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1322 $this->inputStreamInstance = $inputStreamInstance;
1326 * Getter for a OutputStream instance
1328 * @param $outputStreamInstance The OutputStream instance
1330 protected final function getOutputStreamInstance () {
1331 return $this->outputStreamInstance;
1335 * Setter for a OutputStream instance
1337 * @param $outputStreamInstance The OutputStream instance
1340 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1341 $this->outputStreamInstance = $outputStreamInstance;
1345 * Setter for handler instance
1347 * @param $handlerInstance An instance of a Handleable class
1350 protected final function setHandlerInstance (Handleable $handlerInstance) {
1351 $this->handlerInstance = $handlerInstance;
1355 * Getter for handler instance
1357 * @return $handlerInstance A Networkable instance
1359 protected final function getHandlerInstance () {
1360 return $this->handlerInstance;
1364 * Setter for visitor instance
1366 * @param $visitorInstance A Visitor instance
1369 protected final function setVisitorInstance (Visitor $visitorInstance) {
1370 $this->visitorInstance = $visitorInstance;
1374 * Getter for visitor instance
1376 * @return $visitorInstance A Visitor instance
1378 protected final function getVisitorInstance () {
1379 return $this->visitorInstance;
1383 * Setter for DHT instance
1385 * @param $dhtInstance A Distributable instance
1388 protected final function setDhtInstance (Distributable $dhtInstance) {
1389 $this->dhtInstance = $dhtInstance;
1393 * Getter for DHT instance
1395 * @return $dhtInstance A Distributable instance
1397 protected final function getDhtInstance () {
1398 return $this->dhtInstance;
1402 * Setter for raw package Data
1404 * @param $packageData Raw package Data
1407 public final function setPackageData (array $packageData) {
1408 $this->packageData = $packageData;
1412 * Getter for raw package Data
1414 * @return $packageData Raw package Data
1416 public function getPackageData () {
1417 return $this->packageData;
1422 * Setter for Iterator instance
1424 * @param $iteratorInstance An instance of an Iterator
1427 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1428 $this->iteratorInstance = $iteratorInstance;
1432 * Getter for Iterator instance
1434 * @return $iteratorInstance An instance of an Iterator
1436 public final function getIteratorInstance () {
1437 return $this->iteratorInstance;
1441 * Setter for FilePointer instance
1443 * @param $pointerInstance An instance of an FilePointer class
1446 protected final function setPointerInstance (FilePointer $pointerInstance) {
1447 $this->pointerInstance = $pointerInstance;
1451 * Getter for FilePointer instance
1453 * @return $pointerInstance An instance of an FilePointer class
1455 public final function getPointerInstance () {
1456 return $this->pointerInstance;
1460 * Unsets pointer instance which triggers a call of __destruct() if the
1461 * instance is still there. This is surely not fatal on already "closed"
1462 * file pointer instances.
1464 * I don't want to mess around with above setter by giving it a default
1465 * value NULL as setter should always explicitly only set (existing) object
1466 * instances and NULL is NULL.
1470 protected final function unsetPointerInstance () {
1471 // Simply it to NULL
1472 $this->pointerInstance = NULL;
1476 * Setter for Indexable instance
1478 * @param $indexInstance An instance of an Indexable class
1481 protected final function setIndexInstance (Indexable $indexInstance) {
1482 $this->indexInstance = $indexInstance;
1486 * Getter for Indexable instance
1488 * @return $indexInstance An instance of an Indexable class
1490 public final function getIndexInstance () {
1491 return $this->indexInstance;
1495 * Setter for Block instance
1497 * @param $blockInstance An instance of an Block class
1500 protected final function setBlockInstance (Block $blockInstance) {
1501 $this->blockInstance = $blockInstance;
1505 * Getter for Block instance
1507 * @return $blockInstance An instance of an Block class
1509 public final function getBlockInstance () {
1510 return $this->blockInstance;
1514 * Setter for Minable instance
1516 * @param $minableInstance A Minable instance
1519 protected final function setMinableInstance (Minable $minableInstance) {
1520 $this->minableInstance = $minableInstance;
1524 * Getter for minable instance
1526 * @return $minableInstance A Minable instance
1528 protected final function getMinableInstance () {
1529 return $this->minableInstance;
1533 * Setter for FrameworkDirectory instance
1535 * @param $directoryInstance A FrameworkDirectoryPointer instance
1538 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1539 $this->directoryInstance = $directoryInstance;
1543 * Getter for FrameworkDirectory instance
1545 * @return $directoryInstance A FrameworkDirectory instance
1547 protected final function getDirectoryInstance () {
1548 return $this->directoryInstance;
1552 * Setter for listener instance
1554 * @param $listenerInstance A Listenable instance
1557 protected final function setListenerInstance (Listenable $listenerInstance) {
1558 $this->listenerInstance = $listenerInstance;
1562 * Getter for listener instance
1564 * @return $listenerInstance A Listenable instance
1566 protected final function getListenerInstance () {
1567 return $this->listenerInstance;
1571 * Getter for communicator instance
1573 * @return $communicatorInstance An instance of a Communicator class
1575 public final function getCommunicatorInstance () {
1576 return $this->communicatorInstance;
1580 * Setter for communicator instance
1582 * @param $communicatorInstance An instance of a Communicator class
1585 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1586 $this->communicatorInstance = $communicatorInstance;
1590 * Setter for state instance
1592 * @param $stateInstance A Stateable instance
1595 public final function setStateInstance (Stateable $stateInstance) {
1596 $this->stateInstance = $stateInstance;
1600 * Getter for state instance
1602 * @return $stateInstance A Stateable instance
1604 public final function getStateInstance () {
1605 return $this->stateInstance;
1609 * Setter for output instance
1611 * @param $outputInstance The debug output instance
1614 public final function setOutputInstance (OutputStreamer $outputInstance) {
1615 $this->outputInstance = $outputInstance;
1619 * Getter for output instance
1621 * @return $outputInstance The debug output instance
1623 public final function getOutputInstance () {
1624 return $this->outputInstance;
1628 * Setter for command name
1630 * @param $commandName Last validated command name
1633 protected final function setCommandName ($commandName) {
1634 $this->commandName = $commandName;
1638 * Getter for command name
1640 * @return $commandName Last validated command name
1642 protected final function getCommandName () {
1643 return $this->commandName;
1647 * Setter for controller name
1649 * @param $controllerName Last validated controller name
1652 protected final function setControllerName ($controllerName) {
1653 $this->controllerName = $controllerName;
1657 * Getter for controller name
1659 * @return $controllerName Last validated controller name
1661 protected final function getControllerName () {
1662 return $this->controllerName;
1666 * Getter for protocol name
1668 * @return $protocolName Name of used protocol
1670 public final function getProtocolName () {
1671 return $this->protocolName;
1675 * Setter for protocol name
1677 * @param $protocolName Name of used protocol
1680 protected final function setProtocolName ($protocolName) {
1681 $this->protocolName = $protocolName;
1685 * Checks whether an object equals this object. You should overwrite this
1686 * method to implement own equality checks
1688 * @param $objectInstance An instance of a FrameworkInterface object
1689 * @return $equals Whether both objects equals
1691 public function equals (FrameworkInterface $objectInstance) {
1694 $this->__toString() == $objectInstance->__toString()
1696 $this->hashCode() == $objectInstance->hashCode()
1699 // Return the result
1704 * Generates a generic hash code of this class. You should really overwrite
1705 * this method with your own hash code generator code. But keep KISS in mind.
1707 * @return $hashCode A generic hash code respresenting this whole class
1709 public function hashCode () {
1711 return crc32($this->__toString());
1715 * Formats computer generated price values into human-understandable formats
1716 * with thousand and decimal separators.
1718 * @param $value The in computer format value for a price
1719 * @param $currency The currency symbol (use HTML-valid characters!)
1720 * @param $decNum Number of decimals after commata
1721 * @return $price The for the current language formated price string
1722 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1723 * thousands separator
1726 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1727 // Are all required attriutes set?
1728 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1729 // Throw an exception
1730 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1734 $value = (float) $value;
1736 // Reformat the US number
1737 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1739 // Return as string...
1744 * Appends a trailing slash to a string
1746 * @param $str A string (maybe) without trailing slash
1747 * @return $str A string with an auto-appended trailing slash
1749 public final function addMissingTrailingSlash ($str) {
1750 // Is there a trailing slash?
1751 if (substr($str, -1, 1) != '/') {
1755 // Return string with trailing slash
1760 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1761 * application helper instance (ApplicationHelper by default).
1763 * @param $applicationInstance An application helper instance or
1764 * null if we shall use the default
1765 * @return $templateInstance The template engine instance
1766 * @throws NullPointerException If the discovered application
1767 * instance is still null
1769 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1770 // Is the application instance set?
1771 if (is_null($applicationInstance)) {
1772 // Get the current instance
1773 $applicationInstance = $this->getApplicationInstance();
1776 if (is_null($applicationInstance)) {
1777 // Thrown an exception
1778 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1782 // Initialize the template engine
1783 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1785 // Return the prepared instance
1786 return $templateInstance;
1790 * Debugs this instance by putting out it's full content
1792 * @param $message Optional message to show in debug output
1795 public final function debugInstance ($message = '') {
1796 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1797 restore_error_handler();
1802 // Is a message set?
1803 if (!empty($message)) {
1804 // Construct message
1805 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1808 // Generate the output
1809 $content .= sprintf('<pre>%s</pre>',
1812 print_r($this, TRUE)
1818 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>',
1819 $this->__toString(),
1821 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1826 * Replaces control characters with printable output
1828 * @param $str String with control characters
1829 * @return $str Replaced string
1831 protected function replaceControlCharacters ($str) {
1834 chr(13), '[r]', str_replace(
1835 chr(10), '[n]', str_replace(
1845 * Output a partial stub message for the caller method
1847 * @param $message An optional message to display
1850 protected function partialStub ($message = '') {
1851 // Get the backtrace
1852 $backtrace = debug_backtrace();
1854 // Generate the class::method string
1855 $methodName = 'UnknownClass->unknownMethod';
1856 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1857 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1860 // Construct the full message
1861 $stubMessage = sprintf('[%s:] Partial stub!',
1865 // Is the extra message given?
1866 if (!empty($message)) {
1867 // Then add it as well
1868 $stubMessage .= ' Message: ' . $message;
1871 // Debug instance is there?
1872 if (!is_null($this->getDebugInstance())) {
1873 // Output stub message
1874 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1877 trigger_error($stubMessage);
1883 * Outputs a debug backtrace and stops further script execution
1885 * @param $message An optional message to output
1886 * @param $doExit Whether exit the program (TRUE is default)
1889 public function debugBackTrace ($message = '', $doExit = TRUE) {
1890 // Sorry, there is no other way getting this nice backtrace
1891 if (!empty($message)) {
1893 printf('Message: %s<br />' . PHP_EOL, $message);
1897 debug_print_backtrace();
1901 if ($doExit === TRUE) {
1907 * Creates an instance of a debugger instance
1909 * @param $className Name of the class (currently unsupported)
1910 * @param $lineNumber Line number where the call was made
1911 * @return $debugInstance An instance of a debugger class
1912 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1914 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1915 // Is the instance set?
1916 if (!Registry::getRegistry()->instanceExists('debug')) {
1917 // Init debug instance
1918 $debugInstance = NULL;
1922 // Get a debugger instance
1923 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1924 } catch (NullPointerException $e) {
1925 // Didn't work, no instance there
1926 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1929 // Empty string should be ignored and used for testing the middleware
1930 DebugMiddleware::getSelfInstance()->output('');
1932 // Set it in its own class. This will set it in the registry
1933 $debugInstance->setDebugInstance($debugInstance);
1935 // Get instance from registry
1936 $debugInstance = Registry::getRegistry()->getDebugInstance();
1940 return $debugInstance;
1944 * Simple output of a message with line-break
1946 * @param $message Message to output
1949 public function outputLine ($message) {
1951 print($message . PHP_EOL);
1955 * Outputs a debug message whether to debug instance (should be set!) or
1956 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1957 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1959 * @param $message Message we shall send out...
1960 * @param $doPrint Whether print or die here (default: print)
1961 * @paran $stripTags Whether to strip tags (default: FALSE)
1964 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1965 // Set debug instance to NULL
1966 $debugInstance = NULL;
1970 // Get debug instance
1971 $debugInstance = $this->getDebugInstance();
1972 } catch (NullPointerException $e) {
1973 // The debug instance is not set (yet)
1976 // Is the debug instance there?
1977 if (is_object($debugInstance)) {
1978 // Use debug output handler
1979 $debugInstance->output($message, $stripTags);
1981 if ($doPrint === FALSE) {
1982 // Die here if not printed
1986 // Are debug times enabled?
1987 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1989 $message = $this->getPrintableExecutionTime() . $message;
1993 if ($doPrint === TRUE) {
1995 $this->outputLine($message);
2004 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2006 * @param $str The string, what ever it is needs to be converted
2007 * @return $className Generated class name
2009 public static final function convertToClassName ($str) {
2013 // Convert all dashes in underscores
2014 $str = self::convertDashesToUnderscores($str);
2016 // Now use that underscores to get classname parts for hungarian style
2017 foreach (explode('_', $str) as $strPart) {
2018 // Make the class name part lower case and first upper case
2019 $className .= ucfirst(strtolower($strPart));
2022 // Return class name
2027 * Converts dashes to underscores, e.g. useable for configuration entries
2029 * @param $str The string with maybe dashes inside
2030 * @return $str The converted string with no dashed, but underscores
2032 public static final function convertDashesToUnderscores ($str) {
2034 $str = str_replace('-', '_', $str);
2036 // Return converted string
2041 * Marks up the code by adding e.g. line numbers
2043 * @param $phpCode Unmarked PHP code
2044 * @return $markedCode Marked PHP code
2046 public function markupCode ($phpCode) {
2051 $errorArray = error_get_last();
2053 // Init the code with error message
2054 if (is_array($errorArray)) {
2056 $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>',
2057 basename($errorArray['file']),
2058 $errorArray['line'],
2059 $errorArray['message'],
2064 // Add line number to the code
2065 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2067 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2069 htmlentities($code, ENT_QUOTES)
2078 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2079 * beatiful for web-based front-ends. If null is given a message id
2080 * null_timestamp will be resolved and returned.
2082 * @param $timestamp Timestamp to prepare (filter) for display
2083 * @return $readable A readable timestamp
2085 public function doFilterFormatTimestamp ($timestamp) {
2086 // Default value to return
2089 // Is the timestamp null?
2090 if (is_null($timestamp)) {
2091 // Get a message string
2092 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2094 switch ($this->getLanguageInstance()->getLanguageCode()) {
2095 case 'de': // German format is a bit different to default
2096 // Split the GMT stamp up
2097 $dateTime = explode(' ', $timestamp );
2098 $dateArray = explode('-', $dateTime[0]);
2099 $timeArray = explode(':', $dateTime[1]);
2101 // Construct the timestamp
2102 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2112 default: // Default is pass-through
2113 $readable = $timestamp;
2123 * Filter a given number into a localized number
2125 * @param $value The raw value from e.g. database
2126 * @return $localized Localized value
2128 public function doFilterFormatNumber ($value) {
2129 // Generate it from config and localize dependencies
2130 switch ($this->getLanguageInstance()->getLanguageCode()) {
2131 case 'de': // German format is a bit different to default
2132 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2135 default: // US, etc.
2136 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2145 * "Getter" for databse entry
2147 * @return $entry An array with database entries
2148 * @throws NullPointerException If the database result is not found
2149 * @throws InvalidDatabaseResultException If the database result is invalid
2151 protected final function getDatabaseEntry () {
2152 // Is there an instance?
2153 if (!$this->getResultInstance() instanceof SearchableResult) {
2154 // Throw an exception here
2155 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2159 $this->getResultInstance()->rewind();
2161 // Do we have an entry?
2162 if ($this->getResultInstance()->valid() === FALSE) {
2163 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2164 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2168 $this->getResultInstance()->next();
2171 $entry = $this->getResultInstance()->current();
2178 * Getter for field name
2180 * @param $fieldName Field name which we shall get
2181 * @return $fieldValue Field value from the user
2182 * @throws NullPointerException If the result instance is null
2184 public final function getField ($fieldName) {
2185 // Default field value
2188 // Get result instance
2189 $resultInstance = $this->getResultInstance();
2191 // Is this instance null?
2192 if (is_null($resultInstance)) {
2193 // Then the user instance is no longer valid (expired cookies?)
2194 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2197 // Get current array
2198 $fieldArray = $resultInstance->current();
2199 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2201 // Convert dashes to underscore
2202 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2204 // Does the field exist?
2205 if ($this->isFieldSet($fieldName)) {
2207 $fieldValue = $fieldArray[$fieldName2];
2208 } elseif (defined('DEVELOPER')) {
2209 // Missing field entry, may require debugging
2210 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2212 // Missing field entry, may require debugging
2213 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2221 * Checks if given field is set
2223 * @param $fieldName Field name to check
2224 * @return $isSet Whether the given field name is set
2225 * @throws NullPointerException If the result instance is null
2227 public function isFieldSet ($fieldName) {
2228 // Get result instance
2229 $resultInstance = $this->getResultInstance();
2231 // Is this instance null?
2232 if (is_null($resultInstance)) {
2233 // Then the user instance is no longer valid (expired cookies?)
2234 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2237 // Get current array
2238 $fieldArray = $resultInstance->current();
2239 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2241 // Convert dashes to underscore
2242 $fieldName = self::convertDashesToUnderscores($fieldName);
2245 $isSet = isset($fieldArray[$fieldName]);
2252 * Flushs all pending updates to the database layer
2256 public function flushPendingUpdates () {
2257 // Get result instance
2258 $resultInstance = $this->getResultInstance();
2260 // Do we have data to update?
2261 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2262 // Get wrapper class name config entry
2263 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2265 // Create object instance
2266 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2268 // Yes, then send the whole result to the database layer
2269 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2274 * Outputs a deprecation warning to the developer.
2276 * @param $message The message we shall output to the developer
2278 * @todo Write a logging mechanism for productive mode
2280 public function deprecationWarning ($message) {
2281 // Is developer mode active?
2282 if (defined('DEVELOPER')) {
2283 // Debug instance is there?
2284 if (!is_null($this->getDebugInstance())) {
2285 // Output stub message
2286 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2289 trigger_error($message . "<br />\n");
2293 // @TODO Finish this part!
2294 $this->partialStub('Developer mode inactive. Message:' . $message);
2299 * Checks whether the given PHP extension is loaded
2301 * @param $phpExtension The PHP extension we shall check
2302 * @return $isLoaded Whether the PHP extension is loaded
2304 public final function isPhpExtensionLoaded ($phpExtension) {
2306 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2313 * "Getter" as a time() replacement but with milliseconds. You should use this
2314 * method instead of the encapsulated getimeofday() function.
2316 * @return $milliTime Timestamp with milliseconds
2318 public function getMilliTime () {
2319 // Get the time of day as float
2320 $milliTime = gettimeofday(TRUE);
2327 * Idles (sleeps) for given milliseconds
2329 * @return $hasSlept Whether it goes fine
2331 public function idle ($milliSeconds) {
2332 // Sleep is fine by default
2335 // Idle so long with found function
2336 if (function_exists('time_sleep_until')) {
2337 // Get current time and add idle time
2338 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2340 // New PHP 5.1.0 function found, ignore errors
2341 $hasSlept = @time_sleep_until($sleepUntil);
2344 * My Sun station doesn't have that function even with latest PHP
2347 usleep($milliSeconds * 1000);
2354 * Converts a hexadecimal string, even with negative sign as first string to
2355 * a decimal number using BC functions.
2357 * This work is based on comment #86673 on php.net documentation page at:
2358 * <http://de.php.net/manual/en/function.dechex.php#86673>
2360 * @param $hex Hexadecimal string
2361 * @return $dec Decimal number
2363 protected function hex2dec ($hex) {
2364 // Convert to all lower-case
2365 $hex = strtolower($hex);
2367 // Detect sign (negative/positive numbers)
2369 if (substr($hex, 0, 1) == '-') {
2371 $hex = substr($hex, 1);
2374 // Decode the hexadecimal string into a decimal number
2376 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2377 $factor = self::$hexdec[substr($hex, $i, 1)];
2378 $dec = bcadd($dec, bcmul($factor, $e));
2381 // Return the decimal number
2382 return $sign . $dec;
2386 * Converts even very large decimal numbers, also signed, to a hexadecimal
2389 * This work is based on comment #97756 on php.net documentation page at:
2390 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2392 * @param $dec Decimal number, even with negative sign
2393 * @param $maxLength Optional maximum length of the string
2394 * @return $hex Hexadecimal string
2396 protected function dec2hex ($dec, $maxLength = 0) {
2397 // maxLength can be zero or devideable by 2
2398 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2400 // Detect sign (negative/positive numbers)
2407 // Encode the decimal number into a hexadecimal string
2410 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2412 } while ($dec >= 1);
2415 * Leading zeros are required for hex-decimal "numbers". In some
2416 * situations more leading zeros are wanted, so check for both
2419 if ($maxLength > 0) {
2420 // Prepend more zeros
2421 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2422 } elseif ((strlen($hex) % 2) != 0) {
2423 // Only make string's length dividable by 2
2427 // Return the hexadecimal string
2428 return $sign . $hex;
2432 * Converts a ASCII string (0 to 255) into a decimal number.
2434 * @param $asc The ASCII string to be converted
2435 * @return $dec Decimal number
2437 protected function asc2dec ($asc) {
2438 // Convert it into a hexadecimal number
2439 $hex = bin2hex($asc);
2441 // And back into a decimal number
2442 $dec = $this->hex2dec($hex);
2449 * Converts a decimal number into an ASCII string.
2451 * @param $dec Decimal number
2452 * @return $asc An ASCII string
2454 protected function dec2asc ($dec) {
2455 // First convert the number into a hexadecimal string
2456 $hex = $this->dec2hex($dec);
2458 // Then convert it into the ASCII string
2459 $asc = $this->hex2asc($hex);
2466 * Converts a hexadecimal number into an ASCII string. Negative numbers
2469 * @param $hex Hexadecimal string
2470 * @return $asc An ASCII string
2472 protected function hex2asc ($hex) {
2473 // Check for length, it must be devideable by 2
2474 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2475 assert((strlen($hex) % 2) == 0);
2479 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2480 // Get the decimal number of the chunk
2481 $part = hexdec(substr($hex, $idx, 2));
2483 // Add it to the final string
2487 // Return the final string
2492 * Checks whether the given encoded data was encoded with Base64
2494 * @param $encodedData Encoded data we shall check
2495 * @return $isBase64 Whether the encoded data is Base64
2497 protected function isBase64Encoded ($encodedData) {
2499 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2506 * "Getter" to get response/request type from analysis of the system.
2508 * @return $responseType Analyzed response type
2510 protected static function getResponseTypeFromSystem () {
2511 // Default is console
2512 $responseType = 'console';
2514 // Is 'HTTP_HOST' set?
2515 if (isset($_SERVER['HTTP_HOST'])) {
2517 * Then it is a HTML response/request as RSS and so on may be
2518 * transfered over HTTP as well.
2520 $responseType = 'html';
2524 return $responseType;
2528 * Gets a cache key from Criteria instance
2530 * @param $criteriaInstance An instance of a Criteria class
2531 * @param $onlyKeys Only use these keys for a cache key
2532 * @return $cacheKey A cache key suitable for lookup/storage purposes
2534 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2536 $cacheKey = sprintf('%s@%s',
2537 $this->__toString(),
2538 $criteriaInstance->getCacheKey($onlyKeys)
2542 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2547 * Getter for startup time in miliseconds
2549 * @return $startupTime Startup time in miliseconds
2551 protected function getStartupTime () {
2552 return self::$startupTime;
2556 * "Getter" for a printable currently execution time in nice braces
2558 * @return $executionTime Current execution time in nice braces
2560 protected function getPrintableExecutionTime () {
2561 // Caculate the execution time
2562 $executionTime = microtime(TRUE) - $this->getStartupTime();
2564 // Pack it in nice braces
2565 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2568 return $executionTime;
2572 * Hashes a given string with a simple but stronger hash function (no salt)
2573 * and hex-encode it.
2575 * @param $str The string to be hashed
2576 * @return $hash The hash from string $str
2578 public static final function hash ($str) {
2579 // Hash given string with (better secure) hasher
2580 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2587 * "Getter" for length of hash() output. This will be "cached" to speed up
2590 * @return $length Length of hash() output
2592 public static final function getHashLength () {
2594 if (is_null(self::$hashLength)) {
2595 // No, then hash a string and save its length.
2596 self::$hashLength = strlen(self::hash('abc123'));
2600 return self::$hashLength;
2604 * Checks whether the given number is really a number (only chars 0-9).
2606 * @param $num A string consisting only chars between 0 and 9
2607 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2608 * @param $assertMismatch Whether to assert mismatches
2609 * @return $ret The (hopefully) secured numbered value
2611 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2612 // Filter all numbers out
2613 $ret = preg_replace('/[^0123456789]/', '', $num);
2616 if ($castValue === TRUE) {
2617 // Cast to biggest numeric type
2618 $ret = (double) $ret;
2621 // Assert only if requested
2622 if ($assertMismatch === TRUE) {
2623 // Has the whole value changed?
2624 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2632 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2634 * @param $num A string consisting only chars between 0 and 9
2635 * @param $assertMismatch Whether to assert mismatches
2636 * @return $ret The (hopefully) secured hext-numbered value
2638 public function hexval ($num, $assertMismatch = FALSE) {
2639 // Filter all numbers out
2640 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2642 // Assert only if requested
2643 if ($assertMismatch === TRUE) {
2644 // Has the whole value changed?
2645 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2653 * Checks whether start/end marker are set
2655 * @param $data Data to be checked
2656 * @return $isset Whether start/end marker are set
2658 public final function ifStartEndMarkersSet ($data) {
2660 $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));
2662 // ... and return it
2667 * Determines if an element is set in the generic array
2669 * @param $keyGroup Main group for the key
2670 * @param $subGroup Sub group for the key
2671 * @param $key Key to check
2672 * @param $element Element to check
2673 * @return $isset Whether the given key is set
2675 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2677 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2680 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2686 * Determines if a key is set in the generic array
2688 * @param $keyGroup Main group for the key
2689 * @param $subGroup Sub group for the key
2690 * @param $key Key to check
2691 * @return $isset Whether the given key is set
2693 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2695 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2698 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2706 * Determines if a group is set in the generic array
2708 * @param $keyGroup Main group
2709 * @param $subGroup Sub group
2710 * @return $isset Whether the given group is set
2712 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2714 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2717 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2724 * Getter for sub key group
2726 * @param $keyGroup Main key group
2727 * @param $subGroup Sub key group
2728 * @return $array An array with all array elements
2730 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2732 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2733 // No, then abort here
2734 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2739 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2742 return $this->genericArray[$keyGroup][$subGroup];
2746 * Unsets a given key in generic array
2748 * @param $keyGroup Main group for the key
2749 * @param $subGroup Sub group for the key
2750 * @param $key Key to unset
2753 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2755 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2758 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2762 * Unsets a given element in generic array
2764 * @param $keyGroup Main group for the key
2765 * @param $subGroup Sub group for the key
2766 * @param $key Key to unset
2767 * @param $element Element to unset
2770 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2772 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2775 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2779 * Append a string to a given generic array key
2781 * @param $keyGroup Main group for the key
2782 * @param $subGroup Sub group for the key
2783 * @param $key Key to unset
2784 * @param $value Value to add/append
2787 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2789 //* 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);
2791 // Is it already there?
2792 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2794 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2797 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2802 * Append a string to a given generic array element
2804 * @param $keyGroup Main group for the key
2805 * @param $subGroup Sub group for the key
2806 * @param $key Key to unset
2807 * @param $element Element to check
2808 * @param $value Value to add/append
2811 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2813 //* 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);
2815 // Is it already there?
2816 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2818 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2821 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2826 * Sets a string in a given generic array element
2828 * @param $keyGroup Main group for the key
2829 * @param $subGroup Sub group for the key
2830 * @param $key Key to unset
2831 * @param $element Element to check
2832 * @param $value Value to add/append
2835 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2837 //* 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);
2840 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2844 * Initializes given generic array group
2846 * @param $keyGroup Main group for the key
2847 * @param $subGroup Sub group for the key
2848 * @param $key Key to use
2849 * @param $forceInit Optionally force initialization
2852 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2854 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2856 // Is it already set?
2857 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2858 // Already initialized
2859 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2864 $this->genericArray[$keyGroup][$subGroup] = array();
2868 * Initializes given generic array key
2870 * @param $keyGroup Main group for the key
2871 * @param $subGroup Sub group for the key
2872 * @param $key Key to use
2873 * @param $forceInit Optionally force initialization
2876 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2878 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2880 // Is it already set?
2881 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2882 // Already initialized
2883 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2888 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2892 * Initializes given generic array element
2894 * @param $keyGroup Main group for the key
2895 * @param $subGroup Sub group for the key
2896 * @param $key Key to use
2897 * @param $element Element to use
2898 * @param $forceInit Optionally force initialization
2901 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2903 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2905 // Is it already set?
2906 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2907 // Already initialized
2908 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2913 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2917 * Pushes an element to a generic key
2919 * @param $keyGroup Main group for the key
2920 * @param $subGroup Sub group for the key
2921 * @param $key Key to use
2922 * @param $value Value to add/append
2923 * @return $count Number of array elements
2925 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2927 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2930 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2932 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2936 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2939 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2940 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2945 * Pushes an element to a generic array element
2947 * @param $keyGroup Main group for the key
2948 * @param $subGroup Sub group for the key
2949 * @param $key Key to use
2950 * @param $element Element to check
2951 * @param $value Value to add/append
2952 * @return $count Number of array elements
2954 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2956 //* 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));
2959 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2961 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2965 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2968 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2969 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2974 * Pops an element from a generic group
2976 * @param $keyGroup Main group for the key
2977 * @param $subGroup Sub group for the key
2978 * @param $key Key to unset
2979 * @return $value Last "popped" value
2981 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2983 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2986 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2988 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2993 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2996 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2997 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3002 * Shifts an element from a generic group
3004 * @param $keyGroup Main group for the key
3005 * @param $subGroup Sub group for the key
3006 * @param $key Key to unset
3007 * @return $value Last "popped" value
3009 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3011 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3014 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3016 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3021 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3024 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3025 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3030 * Count generic array group
3032 * @param $keyGroup Main group for the key
3033 * @return $count Count of given group
3035 protected final function countGenericArray ($keyGroup) {
3037 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3040 if (!isset($this->genericArray[$keyGroup])) {
3042 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3047 $count = count($this->genericArray[$keyGroup]);
3050 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3057 * Count generic array sub group
3059 * @param $keyGroup Main group for the key
3060 * @param $subGroup Sub group for the key
3061 * @return $count Count of given group
3063 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3065 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3068 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3070 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3075 $count = count($this->genericArray[$keyGroup][$subGroup]);
3078 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3085 * Count generic array elements
3087 * @param $keyGroup Main group for the key
3088 * @param $subGroup Sub group for the key
3089 * @para $key Key to count
3090 * @return $count Count of given key
3092 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3094 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3097 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3099 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3101 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3103 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3108 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3111 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3118 * Getter for whole generic group array
3120 * @param $keyGroup Key group to get
3121 * @return $array Whole generic array group
3123 protected final function getGenericArray ($keyGroup) {
3125 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3128 if (!isset($this->genericArray[$keyGroup])) {
3130 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3135 return $this->genericArray[$keyGroup];
3139 * Setter for generic array key
3141 * @param $keyGroup Key group to get
3142 * @param $subGroup Sub group for the key
3143 * @param $key Key to unset
3144 * @param $value Mixed value from generic array element
3147 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3149 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3152 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3156 * Getter for generic array key
3158 * @param $keyGroup Key group to get
3159 * @param $subGroup Sub group for the key
3160 * @param $key Key to unset
3161 * @return $value Mixed value from generic array element
3163 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3165 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3168 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3170 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3175 return $this->genericArray[$keyGroup][$subGroup][$key];
3179 * Sets a value in given generic array key/element
3181 * @param $keyGroup Main group for the key
3182 * @param $subGroup Sub group for the key
3183 * @param $key Key to set
3184 * @param $element Element to set
3185 * @param $value Value to set
3188 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3190 //* 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));
3193 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3197 * Getter for generic array element
3199 * @param $keyGroup Key group to get
3200 * @param $subGroup Sub group for the key
3201 * @param $key Key to look for
3202 * @param $element Element to look for
3203 * @return $value Mixed value from generic array element
3205 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3207 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3210 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3212 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3217 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3221 * Checks if a given sub group is valid (array)
3223 * @param $keyGroup Key group to get
3224 * @param $subGroup Sub group for the key
3225 * @return $isValid Whether given sub group is valid
3227 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3229 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3232 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3239 * Checks if a given key is valid (array)
3241 * @param $keyGroup Key group to get
3242 * @param $subGroup Sub group for the key
3243 * @param $key Key to check
3244 * @return $isValid Whether given sub group is valid
3246 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3248 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3251 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3258 * Initializes the web output instance
3262 protected function initWebOutputInstance () {
3263 // Get application instance
3264 $applicationInstance = Registry::getRegistry()->getInstance('app');
3266 // Is this a response instance?
3267 if ($this instanceof Responseable) {
3268 // Then set it in application instance
3269 $applicationInstance->setResponseInstance($this);
3272 // Init web output instance
3273 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3276 $this->setWebOutputInstance($outputInstance);
3280 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3282 * @param $boolean Boolean value
3283 * @return $translated Translated boolean value
3285 public static final function translateBooleanToYesNo ($boolean) {
3286 // Make sure it is really boolean
3287 assert(is_bool($boolean));
3290 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3292 // ... and return it
3297 * Encodes raw data (almost any type) by "serializing" it and then pack it
3298 * into a "binary format".
3300 * @param $rawData Raw data (almost any type)
3301 * @return $encoded Encoded data
3303 protected function encodeData ($rawData) {
3304 // Make sure no objects or resources pass through
3305 assert(!is_object($rawData));
3306 assert(!is_resource($rawData));
3308 // First "serialize" it (json_encode() is faster than serialize())
3309 $encoded = $this->packString(json_encode($rawData));
3316 * Pack a string into a "binary format". Please execuse me that this is
3317 * widely undocumented. :-(
3319 * @param $str Unpacked string
3320 * @return $packed Packed string
3321 * @todo Improve documentation
3323 protected function packString ($str) {
3325 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3327 // First compress the string (gzcompress is okay)
3328 $str = gzcompress($str);
3333 // And start the "encoding" loop
3334 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3336 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3337 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3339 if (($idx + $i) <= strlen($str)) {
3340 $ord = ord(substr($str, ($idx + $i), 1));
3342 $add = $ord * pow(256, $factor);
3346 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3350 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3351 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3353 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3354 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3360 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3365 * Checks whether the given file/path is in open_basedir(). This does not
3366 * gurantee that the file is actually readable and/or writeable. If you need
3367 * such gurantee then please use isReadableFile() instead.
3369 * @param $filePathName Name of the file/path to be checked
3370 * @return $isReachable Whether it is within open_basedir()
3372 protected static function isReachableFilePath ($filePathName) {
3373 // Is not reachable by default
3374 $isReachable = FALSE;
3376 // Get open_basedir parameter
3377 $openBaseDir = ini_get('open_basedir');
3380 if (!empty($openBaseDir)) {
3381 // Check all entries
3382 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3383 // Check on existence
3384 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3386 $isReachable = TRUE;
3390 // If open_basedir is not set, all is allowed
3391 $isReachable = TRUE;
3395 return $isReachable;
3399 * Checks whether the give file is within open_basedir() (done by
3400 * isReachableFilePath()), is actually a file and is readable.
3402 * @param $fileName Name of the file to be checked
3403 * @return $isReadable Whether the file is readable (and therefor exists)
3405 public static function isReadableFile ($fileName) {
3406 // Default is not readable
3407 $isReadable = FALSE;
3409 // Is within parameters, so check if it is a file and readable
3410 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3417 * Creates a full-qualified file name (FQFN) for given file name by adding
3418 * a configured temporary file path to it.
3420 * @param $fileName Name for temporary file
3421 * @return $fqfn Full-qualified file name
3422 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3423 * @throws FileIoException If the file cannot be written
3425 protected static function createTempPathForFile ($fileName) {
3427 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3429 // Is the path writeable?
3430 if (!is_writable($basePath)) {
3431 // Path is write-protected
3432 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3436 $fqfn = $basePath . '/' . $fileName;
3439 if (!self::isReachableFilePath($fqfn)) {
3441 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3449 * "Getter" for a printable state name
3451 * @return $stateName Name of the node's state in a printable format
3453 public final function getPrintableState () {
3454 // Default is 'null'
3455 $stateName = 'null';
3457 // Get the state instance
3458 $stateInstance = $this->getStateInstance();
3460 // Is it an instance of Stateable?
3461 if ($stateInstance instanceof Stateable) {
3462 // Then use that state name
3463 $stateName = $stateInstance->getStateName();
3471 * Handles socket error for given socket resource and peer data. This method
3472 * validates $socketResource if it is a valid resource (see is_resource())
3473 * but assumes valid data in array $recipientData, except that
3474 * count($recipientData) is always 2.
3476 * @param $method Value of __METHOD__ from calling method
3477 * @param $line Value of __LINE__ from calling method
3478 * @param $socketResource A valid socket resource
3479 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3481 * @throws InvalidSocketException If $socketResource is no socket resource
3482 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3483 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3485 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3486 // This method handles only socket resources
3487 if (!is_resource($socketResource)) {
3488 // No resource, abort here
3489 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3492 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3493 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3494 assert(isset($socketData[0]));
3495 assert(isset($socketData[1]));
3497 // Get error code for first validation (0 is not an error)
3498 $errorCode = socket_last_error($socketResource);
3500 // If the error code is zero, someone called this method without an error
3501 if ($errorCode == 0) {
3502 // No error detected (or previously cleared outside this method)
3503 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3506 // Get handler (method) name
3507 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3509 // Call-back the error handler method
3510 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3512 // Finally clear the error because it has been handled
3513 socket_clear_error($socketResource);