3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Factory\ObjectFactory;
8 use CoreFramework\Generic\FrameworkInterface;
9 use CoreFramework\Generic\NullPointerException;
10 use CoreFramework\Loader\ClassLoader;
11 use CoreFramework\Manager\ManageableApplication;
12 use CoreFramework\Middleware\Debug\DebugMiddleware;
13 use CoreFramework\Registry\Register;
14 use CoreFramework\Registry\Generic\Registry;
15 use CoreFramework\Request\Requestable;
16 use CoreFramework\Stream\Output\OutputStreamer;
17 use CoreFramework\Template\CompileableTemplate;
23 * The simulator system class is the super class of all other classes. This
24 * class handles saving of games etc.
26 * @author Roland Haeder <webmaster@shipsimu.org>
28 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
29 * @license GNU GPL 3.0 or any newer version
30 * @link http://www.shipsimu.org
32 * This program is free software: you can redistribute it and/or modify
33 * it under the terms of the GNU General Public License as published by
34 * the Free Software Foundation, either version 3 of the License, or
35 * (at your option) any later version.
37 * This program is distributed in the hope that it will be useful,
38 * but WITHOUT ANY WARRANTY; without even the implied warranty of
39 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
40 * GNU General Public License for more details.
42 * You should have received a copy of the GNU General Public License
43 * along with this program. If not, see <http://www.gnu.org/licenses/>.
45 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
47 * Length of output from hash()
49 private static $hashLength = NULL;
54 private $realClass = 'BaseFrameworkSystem';
57 * Instance of a Requestable class
59 private $requestInstance = NULL;
62 * Instance of a Responsable class
64 private $responseInstance = NULL;
67 * Search criteria instance
69 private $searchInstance = NULL;
72 * Update criteria instance
74 private $updateInstance = NULL;
77 * The file I/O instance for the template loader
79 private $fileIoInstance = NULL;
84 private $resolverInstance = NULL;
87 * Template engine instance
89 private $templateInstance = NULL;
92 * Database result instance
94 private $resultInstance = NULL;
97 * Instance for user class
99 private $userInstance = NULL;
102 * A controller instance
104 private $controllerInstance = NULL;
109 private $rngInstance = NULL;
112 * Instance of a crypto helper
114 private $cryptoInstance = NULL;
117 * Instance of an Iterator class
119 private $iteratorInstance = NULL;
122 * Instance of the list
124 private $listInstance = NULL;
129 private $menuInstance = NULL;
132 * Instance of the image
134 private $imageInstance = NULL;
137 * Instance of the stacker
139 private $stackInstance = NULL;
142 * A Compressor instance
144 private $compressorInstance = NULL;
147 * A Parseable instance
149 private $parserInstance = NULL;
152 * A HandleableProtocol instance
154 private $protocolInstance = NULL;
157 * A database wrapper instance
159 private $databaseInstance = NULL;
162 * A helper instance for the form
164 private $helperInstance = NULL;
167 * An instance of a Source class
169 private $sourceInstance = NULL;
172 * An instance of a UrlSource class
174 private $urlSourceInstance = NULL;
177 * An instance of a InputStream class
179 private $inputStreamInstance = NULL;
182 * An instance of a OutputStream class
184 private $outputStreamInstance = NULL;
187 * Networkable handler instance
189 private $handlerInstance = NULL;
192 * Visitor handler instance
194 private $visitorInstance = NULL;
199 private $dhtInstance = NULL;
202 * An instance of a database wrapper class
204 private $wrapperInstance = NULL;
207 * An instance of a file I/O pointer class (not handler)
209 private $pointerInstance = NULL;
212 * An instance of an Indexable class
214 private $indexInstance = NULL;
217 * An instance of a Block class
219 private $blockInstance = NULL;
224 private $minableInstance = NULL;
227 * A FrameworkDirectory instance
229 private $directoryInstance = NULL;
234 private $listenerInstance = NULL;
237 * An instance of a communicator
239 private $communicatorInstance = NULL;
242 * The concrete output instance
244 private $outputInstance = NULL;
249 private $stateInstance = NULL;
252 * Thousands separator
254 private $thousands = '.'; // German
259 private $decimals = ','; // German
264 private $socketResource = FALSE;
267 * Regular expression to use for validation
269 private $regularExpression = '';
274 private $packageData = array();
279 private $genericArray = array();
284 private $commandName = '';
289 private $controllerName = '';
292 * Name of used protocol
294 private $protocolName = 'invalid';
297 * Array with bitmasks and such for pack/unpack methods to support both
298 * 32-bit and 64-bit systems
300 private $packingData = array(
303 'left' => 0xffff0000,
304 'right' => 0x0000ffff,
310 'left' => 0xffffffff00000000,
311 'right' => 0x00000000ffffffff,
318 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
320 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
322 private $archArrayElement = FALSE;
324 /***********************
325 * Exception codes.... *
326 ***********************/
328 // @todo Try to clean these constants up
329 const EXCEPTION_IS_NULL_POINTER = 0x001;
330 const EXCEPTION_IS_NO_OBJECT = 0x002;
331 const EXCEPTION_IS_NO_ARRAY = 0x003;
332 const EXCEPTION_MISSING_METHOD = 0x004;
333 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
334 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
335 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
336 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
337 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
338 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
339 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
340 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
341 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
342 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
343 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
344 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
345 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
346 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
347 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
348 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
349 const EXCEPTION_PATH_NOT_FOUND = 0x015;
350 const EXCEPTION_INVALID_PATH_NAME = 0x016;
351 const EXCEPTION_READ_PROTECED_PATH = 0x017;
352 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
353 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
354 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
355 const EXCEPTION_INVALID_RESOURCE = 0x01b;
356 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
357 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
358 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
359 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
360 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
361 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
362 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
363 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
364 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
365 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
366 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
367 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
368 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
369 const EXCEPTION_INVALID_STRING = 0x029;
370 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
371 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
372 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
373 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
374 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
375 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
376 const EXCEPTION_MISSING_ELEMENT = 0x030;
377 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
378 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
379 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
380 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
381 const EXCEPTION_FATAL_ERROR = 0x035;
382 const EXCEPTION_FILE_NOT_FOUND = 0x036;
383 const EXCEPTION_ASSERTION_FAILED = 0x037;
384 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
385 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
386 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
387 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
388 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
389 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
392 * Hexadecimal->Decimal translation array
394 private static $hexdec = array(
414 * Decimal->hexadecimal translation array
416 private static $dechex = array(
436 * Startup time in miliseconds
438 private static $startupTime = 0;
441 * Protected super constructor
443 * @param $className Name of the class
446 protected function __construct ($className) {
448 $this->setRealClass($className);
450 // Set configuration instance if no registry ...
451 if (!$this instanceof Register) {
452 // ... because registries doesn't need to be configured
453 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
456 // Is the startup time set? (0 cannot be TRUE anymore)
457 if (self::$startupTime == 0) {
459 self::$startupTime = microtime(TRUE);
463 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
467 * Destructor for all classes. You should not call this method on your own.
471 public function __destruct () {
472 // Flush any updated entries to the database
473 $this->flushPendingUpdates();
475 // Is this object already destroyed?
476 if ($this->__toString() != 'DestructedObject') {
477 // Destroy all informations about this class but keep some text about it alive
478 $this->setRealClass('DestructedObject');
479 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
480 // Already destructed object
481 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
486 // Do not call this twice
487 trigger_error(__METHOD__ . ': Called twice.');
493 * The __call() method where all non-implemented methods end up
495 * @param $methodName Name of the missing method
496 * @args $args Arguments passed to the method
499 public final function __call ($methodName, $args) {
500 return self::__callStatic($methodName, $args);
504 * The __callStatic() method where all non-implemented static methods end up
506 * @param $methodName Name of the missing method
507 * @args $args Arguments passed to the method
510 public static final function __callStatic ($methodName, $args) {
512 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
514 // Init argument string
517 // Is it NULL, empty or an array?
518 if (is_null($args)) {
520 $argsString = 'NULL';
521 } elseif (is_array($args)) {
525 // Some arguments are there
526 foreach ($args as $arg) {
527 // Add data about the argument
528 $argsString .= gettype($arg) . ':';
531 // Found a NULL argument
532 $argsString .= 'NULL';
533 } elseif (is_string($arg)) {
534 // Add length for strings
535 $argsString .= strlen($arg);
536 } elseif ((is_int($arg)) || (is_float($arg))) {
539 } elseif (is_array($arg)) {
540 // .. or size if array
541 $argsString .= count($arg);
542 } elseif (is_object($arg)) {
544 $reflection = new ReflectionClass($arg);
546 // Is an other object, maybe no __toString() available
547 $argsString .= $reflection->getName();
548 } elseif ($arg === TRUE) {
549 // ... is boolean 'TRUE'
550 $argsString .= 'TRUE';
551 } elseif ($arg === FALSE) {
552 // ... is boolean 'FALSE'
553 $argsString .= 'FALSE';
556 // Comma for next one
561 if (substr($argsString, -2, 1) == ',') {
562 $argsString = substr($argsString, 0, -2);
568 // Invalid arguments!
569 $argsString = '!INVALID:' . gettype($args) . '!';
572 // Output stub message
573 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
574 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
584 * Getter for $realClass
586 * @return $realClass The name of the real class (not BaseFrameworkSystem)
588 public function __toString () {
589 return $this->realClass;
593 * Magic method to catch setting of missing but set class fields/attributes
595 * @param $name Name of the field/attribute
596 * @param $value Value to store
599 public final function __set ($name, $value) {
600 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
603 print_r($value, TRUE)
608 * Magic method to catch getting of missing fields/attributes
610 * @param $name Name of the field/attribute
613 public final function __get ($name) {
614 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
620 * Magic method to catch unsetting of missing fields/attributes
622 * @param $name Name of the field/attribute
625 public final function __unset ($name) {
626 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
632 * Magic method to catch object serialization
634 * @return $unsupported Unsupported method
635 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
637 public final function __sleep () {
638 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
642 * Magic method to catch object deserialization
644 * @return $unsupported Unsupported method
645 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
647 public final function __wakeup () {
648 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
652 * Magic method to catch calls when an object instance is called
654 * @return $unsupported Unsupported method
655 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
657 public final function __invoke () {
658 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
662 * Setter for the real class name
664 * @param $realClass Class name (string)
667 public final function setRealClass ($realClass) {
669 $this->realClass = (string) $realClass;
673 * Setter for database result instance
675 * @param $resultInstance An instance of a database result class
677 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
679 protected final function setResultInstance (SearchableResult $resultInstance) {
680 $this->resultInstance = $resultInstance;
684 * Getter for database result instance
686 * @return $resultInstance An instance of a database result class
688 public final function getResultInstance () {
689 return $this->resultInstance;
693 * Setter for template engine instances
695 * @param $templateInstance An instance of a template engine class
698 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
699 $this->templateInstance = $templateInstance;
703 * Getter for template engine instances
705 * @return $templateInstance An instance of a template engine class
707 protected final function getTemplateInstance () {
708 return $this->templateInstance;
712 * Setter for search instance
714 * @param $searchInstance Searchable criteria instance
717 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
718 $this->searchInstance = $searchInstance;
722 * Getter for search instance
724 * @return $searchInstance Searchable criteria instance
726 public final function getSearchInstance () {
727 return $this->searchInstance;
731 * Setter for update instance
733 * @param $updateInstance Searchable criteria instance
736 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
737 $this->updateInstance = $updateInstance;
741 * Getter for update instance
743 * @return $updateInstance Updateable criteria instance
745 public final function getUpdateInstance () {
746 return $this->updateInstance;
750 * Setter for resolver instance
752 * @param $resolverInstance Instance of a command resolver class
755 public final function setResolverInstance (Resolver $resolverInstance) {
756 $this->resolverInstance = $resolverInstance;
760 * Getter for resolver instance
762 * @return $resolverInstance Instance of a command resolver class
764 public final function getResolverInstance () {
765 return $this->resolverInstance;
769 * Setter for language instance
771 * @param $configInstance The configuration instance which shall
772 * be FrameworkConfiguration
775 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
776 Registry::getRegistry()->addInstance('config', $configInstance);
780 * Getter for configuration instance
782 * @return $configInstance Configuration instance
784 public final function getConfigInstance () {
785 $configInstance = Registry::getRegistry()->getInstance('config');
786 return $configInstance;
790 * Setter for debug instance
792 * @param $debugInstance The instance for debug output class
795 public final function setDebugInstance (DebugMiddleware $debugInstance) {
796 Registry::getRegistry()->addInstance('debug', $debugInstance);
800 * Getter for debug instance
802 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
804 public final function getDebugInstance () {
805 // Get debug instance
806 $debugInstance = Registry::getRegistry()->getInstance('debug');
809 return $debugInstance;
813 * Setter for web output instance
815 * @param $webInstance The instance for web output class
818 public final function setWebOutputInstance (OutputStreamer $webInstance) {
819 Registry::getRegistry()->addInstance('web_output', $webInstance);
823 * Getter for web output instance
825 * @return $webOutputInstance - Instance to class WebOutput
827 public final function getWebOutputInstance () {
828 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
829 return $webOutputInstance;
833 * Setter for database instance
835 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
838 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
839 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
843 * Getter for database layer
845 * @return $databaseInstance The database layer instance
847 public final function getDatabaseInstance () {
849 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
852 return $databaseInstance;
856 * Setter for compressor channel
858 * @param $compressorInstance An instance of CompressorChannel
861 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
862 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
866 * Getter for compressor channel
868 * @return $compressorInstance The compressor channel
870 public final function getCompressorChannel () {
871 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
872 return $compressorInstance;
876 * Protected getter for a manageable application helper class
878 * @return $applicationInstance An instance of a manageable application helper class
880 protected final function getApplicationInstance () {
881 $applicationInstance = Registry::getRegistry()->getInstance('application');
882 return $applicationInstance;
886 * Setter for a manageable application helper class
888 * @param $applicationInstance An instance of a manageable application helper class
891 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
892 Registry::getRegistry()->addInstance('application', $applicationInstance);
896 * Setter for request instance
898 * @param $requestInstance An instance of a Requestable class
901 public final function setRequestInstance (Requestable $requestInstance) {
902 $this->requestInstance = $requestInstance;
906 * Getter for request instance
908 * @return $requestInstance An instance of a Requestable class
910 public final function getRequestInstance () {
911 return $this->requestInstance;
915 * Setter for response instance
917 * @param $responseInstance An instance of a Responseable class
920 public final function setResponseInstance (Responseable $responseInstance) {
921 $this->responseInstance = $responseInstance;
925 * Getter for response instance
927 * @return $responseInstance An instance of a Responseable class
929 public final function getResponseInstance () {
930 return $this->responseInstance;
934 * Private getter for language instance
936 * @return $langInstance An instance to the language sub-system
938 protected final function getLanguageInstance () {
939 $langInstance = Registry::getRegistry()->getInstance('language');
940 return $langInstance;
944 * Setter for language instance
946 * @param $langInstance An instance to the language sub-system
948 * @see LanguageSystem
950 public final function setLanguageInstance (ManageableLanguage $langInstance) {
951 Registry::getRegistry()->addInstance('language', $langInstance);
955 * Private getter for file IO instance
957 * @return $fileIoInstance An instance to the file I/O sub-system
959 protected final function getFileIoInstance () {
960 return $this->fileIoInstance;
964 * Setter for file I/O instance
966 * @param $fileIoInstance An instance to the file I/O sub-system
969 public final function setFileIoInstance (IoHandler $fileIoInstance) {
970 $this->fileIoInstance = $fileIoInstance;
974 * Protected setter for user instance
976 * @param $userInstance An instance of a user class
979 protected final function setUserInstance (ManageableAccount $userInstance) {
980 $this->userInstance = $userInstance;
984 * Getter for user instance
986 * @return $userInstance An instance of a user class
988 public final function getUserInstance () {
989 return $this->userInstance;
993 * Setter for controller instance (this surely breaks a bit the MVC patterm)
995 * @param $controllerInstance An instance of the controller
998 public final function setControllerInstance (Controller $controllerInstance) {
999 $this->controllerInstance = $controllerInstance;
1003 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1005 * @return $controllerInstance An instance of the controller
1007 public final function getControllerInstance () {
1008 return $this->controllerInstance;
1012 * Setter for RNG instance
1014 * @param $rngInstance An instance of a random number generator (RNG)
1017 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1018 $this->rngInstance = $rngInstance;
1022 * Getter for RNG instance
1024 * @return $rngInstance An instance of a random number generator (RNG)
1026 public final function getRngInstance () {
1027 return $this->rngInstance;
1031 * Setter for Cryptable instance
1033 * @param $cryptoInstance An instance of a Cryptable class
1036 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1037 $this->cryptoInstance = $cryptoInstance;
1041 * Getter for Cryptable instance
1043 * @return $cryptoInstance An instance of a Cryptable class
1045 public final function getCryptoInstance () {
1046 return $this->cryptoInstance;
1050 * Setter for the list instance
1052 * @param $listInstance A list of Listable
1055 protected final function setListInstance (Listable $listInstance) {
1056 $this->listInstance = $listInstance;
1060 * Getter for the list instance
1062 * @return $listInstance A list of Listable
1064 protected final function getListInstance () {
1065 return $this->listInstance;
1069 * Setter for the menu instance
1071 * @param $menuInstance A RenderableMenu instance
1074 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1075 $this->menuInstance = $menuInstance;
1079 * Getter for the menu instance
1081 * @return $menuInstance A RenderableMenu instance
1083 protected final function getMenuInstance () {
1084 return $this->menuInstance;
1088 * Setter for image instance
1090 * @param $imageInstance An instance of an image
1093 public final function setImageInstance (BaseImage $imageInstance) {
1094 $this->imageInstance = $imageInstance;
1098 * Getter for image instance
1100 * @return $imageInstance An instance of an image
1102 public final function getImageInstance () {
1103 return $this->imageInstance;
1107 * Setter for stacker instance
1109 * @param $stackInstance An instance of an stacker
1112 public final function setStackInstance (Stackable $stackInstance) {
1113 $this->stackInstance = $stackInstance;
1117 * Getter for stacker instance
1119 * @return $stackInstance An instance of an stacker
1121 public final function getStackInstance () {
1122 return $this->stackInstance;
1126 * Setter for compressor instance
1128 * @param $compressorInstance An instance of an compressor
1131 public final function setCompressorInstance (Compressor $compressorInstance) {
1132 $this->compressorInstance = $compressorInstance;
1136 * Getter for compressor instance
1138 * @return $compressorInstance An instance of an compressor
1140 public final function getCompressorInstance () {
1141 return $this->compressorInstance;
1145 * Setter for Parseable instance
1147 * @param $parserInstance An instance of an Parseable
1150 public final function setParserInstance (Parseable $parserInstance) {
1151 $this->parserInstance = $parserInstance;
1155 * Getter for Parseable instance
1157 * @return $parserInstance An instance of an Parseable
1159 public final function getParserInstance () {
1160 return $this->parserInstance;
1164 * Setter for HandleableProtocol instance
1166 * @param $protocolInstance An instance of an HandleableProtocol
1169 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1170 $this->protocolInstance = $protocolInstance;
1174 * Getter for HandleableProtocol instance
1176 * @return $protocolInstance An instance of an HandleableProtocol
1178 public final function getProtocolInstance () {
1179 return $this->protocolInstance;
1183 * Setter for DatabaseWrapper instance
1185 * @param $wrapperInstance An instance of an DatabaseWrapper
1188 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1189 $this->wrapperInstance = $wrapperInstance;
1193 * Getter for DatabaseWrapper instance
1195 * @return $wrapperInstance An instance of an DatabaseWrapper
1197 public final function getWrapperInstance () {
1198 return $this->wrapperInstance;
1202 * Setter for socket resource
1204 * @param $socketResource A valid socket resource
1207 public final function setSocketResource ($socketResource) {
1208 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1209 $this->socketResource = $socketResource;
1213 * Getter for socket resource
1215 * @return $socketResource A valid socket resource
1217 public final function getSocketResource () {
1218 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1219 return $this->socketResource;
1223 * Setter for regular expression
1225 * @param $regularExpression A valid regular expression
1228 public final function setRegularExpression ($regularExpression) {
1229 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1230 $this->regularExpression = $regularExpression;
1234 * Getter for regular expression
1236 * @return $regularExpression A valid regular expression
1238 public final function getRegularExpression () {
1239 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1240 return $this->regularExpression;
1244 * Setter for helper instance
1246 * @param $helperInstance An instance of a helper class
1249 protected final function setHelperInstance (Helper $helperInstance) {
1250 $this->helperInstance = $helperInstance;
1254 * Getter for helper instance
1256 * @return $helperInstance An instance of a helper class
1258 public final function getHelperInstance () {
1259 return $this->helperInstance;
1263 * Setter for a Source instance
1265 * @param $sourceInstance An instance of a Source class
1268 protected final function setSourceInstance (Source $sourceInstance) {
1269 $this->sourceInstance = $sourceInstance;
1273 * Getter for a Source instance
1275 * @return $sourceInstance An instance of a Source class
1277 protected final function getSourceInstance () {
1278 return $this->sourceInstance;
1282 * Setter for a UrlSource instance
1284 * @param $sourceInstance An instance of a UrlSource class
1287 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1288 $this->urlSourceInstance = $urlSourceInstance;
1292 * Getter for a UrlSource instance
1294 * @return $urlSourceInstance An instance of a UrlSource class
1296 protected final function getUrlSourceInstance () {
1297 return $this->urlSourceInstance;
1301 * Getter for a InputStream instance
1303 * @param $inputStreamInstance The InputStream instance
1305 protected final function getInputStreamInstance () {
1306 return $this->inputStreamInstance;
1310 * Setter for a InputStream instance
1312 * @param $inputStreamInstance The InputStream instance
1315 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1316 $this->inputStreamInstance = $inputStreamInstance;
1320 * Getter for a OutputStream instance
1322 * @param $outputStreamInstance The OutputStream instance
1324 protected final function getOutputStreamInstance () {
1325 return $this->outputStreamInstance;
1329 * Setter for a OutputStream instance
1331 * @param $outputStreamInstance The OutputStream instance
1334 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1335 $this->outputStreamInstance = $outputStreamInstance;
1339 * Setter for handler instance
1341 * @param $handlerInstance An instance of a Handleable class
1344 protected final function setHandlerInstance (Handleable $handlerInstance) {
1345 $this->handlerInstance = $handlerInstance;
1349 * Getter for handler instance
1351 * @return $handlerInstance A Networkable instance
1353 protected final function getHandlerInstance () {
1354 return $this->handlerInstance;
1358 * Setter for visitor instance
1360 * @param $visitorInstance A Visitor instance
1363 protected final function setVisitorInstance (Visitor $visitorInstance) {
1364 $this->visitorInstance = $visitorInstance;
1368 * Getter for visitor instance
1370 * @return $visitorInstance A Visitor instance
1372 protected final function getVisitorInstance () {
1373 return $this->visitorInstance;
1377 * Setter for DHT instance
1379 * @param $dhtInstance A Distributable instance
1382 protected final function setDhtInstance (Distributable $dhtInstance) {
1383 $this->dhtInstance = $dhtInstance;
1387 * Getter for DHT instance
1389 * @return $dhtInstance A Distributable instance
1391 protected final function getDhtInstance () {
1392 return $this->dhtInstance;
1396 * Setter for raw package Data
1398 * @param $packageData Raw package Data
1401 public final function setPackageData (array $packageData) {
1402 $this->packageData = $packageData;
1406 * Getter for raw package Data
1408 * @return $packageData Raw package Data
1410 public function getPackageData () {
1411 return $this->packageData;
1416 * Setter for Iterator instance
1418 * @param $iteratorInstance An instance of an Iterator
1421 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1422 $this->iteratorInstance = $iteratorInstance;
1426 * Getter for Iterator instance
1428 * @return $iteratorInstance An instance of an Iterator
1430 public final function getIteratorInstance () {
1431 return $this->iteratorInstance;
1435 * Setter for FilePointer instance
1437 * @param $pointerInstance An instance of an FilePointer class
1440 protected final function setPointerInstance (FilePointer $pointerInstance) {
1441 $this->pointerInstance = $pointerInstance;
1445 * Getter for FilePointer instance
1447 * @return $pointerInstance An instance of an FilePointer class
1449 public final function getPointerInstance () {
1450 return $this->pointerInstance;
1454 * Unsets pointer instance which triggers a call of __destruct() if the
1455 * instance is still there. This is surely not fatal on already "closed"
1456 * file pointer instances.
1458 * I don't want to mess around with above setter by giving it a default
1459 * value NULL as setter should always explicitly only set (existing) object
1460 * instances and NULL is NULL.
1464 protected final function unsetPointerInstance () {
1465 // Simply it to NULL
1466 $this->pointerInstance = NULL;
1470 * Setter for Indexable instance
1472 * @param $indexInstance An instance of an Indexable class
1475 protected final function setIndexInstance (Indexable $indexInstance) {
1476 $this->indexInstance = $indexInstance;
1480 * Getter for Indexable instance
1482 * @return $indexInstance An instance of an Indexable class
1484 public final function getIndexInstance () {
1485 return $this->indexInstance;
1489 * Setter for Block instance
1491 * @param $blockInstance An instance of an Block class
1494 protected final function setBlockInstance (Block $blockInstance) {
1495 $this->blockInstance = $blockInstance;
1499 * Getter for Block instance
1501 * @return $blockInstance An instance of an Block class
1503 public final function getBlockInstance () {
1504 return $this->blockInstance;
1508 * Setter for Minable instance
1510 * @param $minableInstance A Minable instance
1513 protected final function setMinableInstance (Minable $minableInstance) {
1514 $this->minableInstance = $minableInstance;
1518 * Getter for minable instance
1520 * @return $minableInstance A Minable instance
1522 protected final function getMinableInstance () {
1523 return $this->minableInstance;
1527 * Setter for FrameworkDirectory instance
1529 * @param $directoryInstance A FrameworkDirectoryPointer instance
1532 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1533 $this->directoryInstance = $directoryInstance;
1537 * Getter for FrameworkDirectory instance
1539 * @return $directoryInstance A FrameworkDirectory instance
1541 protected final function getDirectoryInstance () {
1542 return $this->directoryInstance;
1546 * Setter for listener instance
1548 * @param $listenerInstance A Listenable instance
1551 protected final function setListenerInstance (Listenable $listenerInstance) {
1552 $this->listenerInstance = $listenerInstance;
1556 * Getter for listener instance
1558 * @return $listenerInstance A Listenable instance
1560 protected final function getListenerInstance () {
1561 return $this->listenerInstance;
1565 * Getter for communicator instance
1567 * @return $communicatorInstance An instance of a Communicator class
1569 public final function getCommunicatorInstance () {
1570 return $this->communicatorInstance;
1574 * Setter for communicator instance
1576 * @param $communicatorInstance An instance of a Communicator class
1579 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1580 $this->communicatorInstance = $communicatorInstance;
1584 * Setter for state instance
1586 * @param $stateInstance A Stateable instance
1589 public final function setStateInstance (Stateable $stateInstance) {
1590 $this->stateInstance = $stateInstance;
1594 * Getter for state instance
1596 * @return $stateInstance A Stateable instance
1598 public final function getStateInstance () {
1599 return $this->stateInstance;
1603 * Setter for output instance
1605 * @param $outputInstance The debug output instance
1608 public final function setOutputInstance (OutputStreamer $outputInstance) {
1609 $this->outputInstance = $outputInstance;
1613 * Getter for output instance
1615 * @return $outputInstance The debug output instance
1617 public final function getOutputInstance () {
1618 return $this->outputInstance;
1622 * Setter for command name
1624 * @param $commandName Last validated command name
1627 protected final function setCommandName ($commandName) {
1628 $this->commandName = $commandName;
1632 * Getter for command name
1634 * @return $commandName Last validated command name
1636 protected final function getCommandName () {
1637 return $this->commandName;
1641 * Setter for controller name
1643 * @param $controllerName Last validated controller name
1646 protected final function setControllerName ($controllerName) {
1647 $this->controllerName = $controllerName;
1651 * Getter for controller name
1653 * @return $controllerName Last validated controller name
1655 protected final function getControllerName () {
1656 return $this->controllerName;
1660 * Getter for protocol name
1662 * @return $protocolName Name of used protocol
1664 public final function getProtocolName () {
1665 return $this->protocolName;
1669 * Setter for protocol name
1671 * @param $protocolName Name of used protocol
1674 protected final function setProtocolName ($protocolName) {
1675 $this->protocolName = $protocolName;
1679 * Checks whether an object equals this object. You should overwrite this
1680 * method to implement own equality checks
1682 * @param $objectInstance An instance of a FrameworkInterface object
1683 * @return $equals Whether both objects equals
1685 public function equals (FrameworkInterface $objectInstance) {
1688 $this->__toString() == $objectInstance->__toString()
1690 $this->hashCode() == $objectInstance->hashCode()
1693 // Return the result
1698 * Generates a generic hash code of this class. You should really overwrite
1699 * this method with your own hash code generator code. But keep KISS in mind.
1701 * @return $hashCode A generic hash code respresenting this whole class
1703 public function hashCode () {
1705 return crc32($this->__toString());
1709 * Formats computer generated price values into human-understandable formats
1710 * with thousand and decimal separators.
1712 * @param $value The in computer format value for a price
1713 * @param $currency The currency symbol (use HTML-valid characters!)
1714 * @param $decNum Number of decimals after commata
1715 * @return $price The for the current language formated price string
1716 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1717 * thousands separator
1720 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1721 // Are all required attriutes set?
1722 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1723 // Throw an exception
1724 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1728 $value = (float) $value;
1730 // Reformat the US number
1731 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1733 // Return as string...
1738 * Appends a trailing slash to a string
1740 * @param $str A string (maybe) without trailing slash
1741 * @return $str A string with an auto-appended trailing slash
1743 public final function addMissingTrailingSlash ($str) {
1744 // Is there a trailing slash?
1745 if (substr($str, -1, 1) != '/') {
1749 // Return string with trailing slash
1754 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1755 * application helper instance (ApplicationHelper by default).
1757 * @param $applicationInstance An application helper instance or
1758 * null if we shall use the default
1759 * @return $templateInstance The template engine instance
1760 * @throws NullPointerException If the discovered application
1761 * instance is still null
1763 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1764 // Is the application instance set?
1765 if (is_null($applicationInstance)) {
1766 // Get the current instance
1767 $applicationInstance = $this->getApplicationInstance();
1770 if (is_null($applicationInstance)) {
1771 // Thrown an exception
1772 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1776 // Initialize the template engine
1777 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1779 // Return the prepared instance
1780 return $templateInstance;
1784 * Debugs this instance by putting out it's full content
1786 * @param $message Optional message to show in debug output
1789 public final function debugInstance ($message = '') {
1790 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1791 restore_error_handler();
1796 // Is a message set?
1797 if (!empty($message)) {
1798 // Construct message
1799 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1802 // Generate the output
1803 $content .= sprintf('<pre>%s</pre>',
1806 print_r($this, TRUE)
1812 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>',
1813 $this->__toString(),
1815 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1820 * Replaces control characters with printable output
1822 * @param $str String with control characters
1823 * @return $str Replaced string
1825 protected function replaceControlCharacters ($str) {
1828 chr(13), '[r]', str_replace(
1829 chr(10), '[n]', str_replace(
1839 * Output a partial stub message for the caller method
1841 * @param $message An optional message to display
1844 protected function partialStub ($message = '') {
1845 // Get the backtrace
1846 $backtrace = debug_backtrace();
1848 // Generate the class::method string
1849 $methodName = 'UnknownClass->unknownMethod';
1850 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1851 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1854 // Construct the full message
1855 $stubMessage = sprintf('[%s:] Partial stub!',
1859 // Is the extra message given?
1860 if (!empty($message)) {
1861 // Then add it as well
1862 $stubMessage .= ' Message: ' . $message;
1865 // Debug instance is there?
1866 if (!is_null($this->getDebugInstance())) {
1867 // Output stub message
1868 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1871 trigger_error($stubMessage);
1877 * Outputs a debug backtrace and stops further script execution
1879 * @param $message An optional message to output
1880 * @param $doExit Whether exit the program (TRUE is default)
1883 public function debugBackTrace ($message = '', $doExit = TRUE) {
1884 // Sorry, there is no other way getting this nice backtrace
1885 if (!empty($message)) {
1887 printf('Message: %s<br />' . PHP_EOL, $message);
1891 debug_print_backtrace();
1895 if ($doExit === TRUE) {
1901 * Creates an instance of a debugger instance
1903 * @param $className Name of the class (currently unsupported)
1904 * @param $lineNumber Line number where the call was made
1905 * @return $debugInstance An instance of a debugger class
1906 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1908 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1909 // Is the instance set?
1910 if (!Registry::getRegistry()->instanceExists('debug')) {
1911 // Init debug instance
1912 $debugInstance = NULL;
1916 // Get a debugger instance
1917 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1918 } catch (NullPointerException $e) {
1919 // Didn't work, no instance there
1920 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1923 // Empty string should be ignored and used for testing the middleware
1924 DebugMiddleware::getSelfInstance()->output('');
1926 // Set it in its own class. This will set it in the registry
1927 $debugInstance->setDebugInstance($debugInstance);
1929 // Get instance from registry
1930 $debugInstance = Registry::getRegistry()->getDebugInstance();
1934 return $debugInstance;
1938 * Simple output of a message with line-break
1940 * @param $message Message to output
1943 public function outputLine ($message) {
1945 print($message . PHP_EOL);
1949 * Outputs a debug message whether to debug instance (should be set!) or
1950 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1951 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1953 * @param $message Message we shall send out...
1954 * @param $doPrint Whether print or die here (default: print)
1955 * @paran $stripTags Whether to strip tags (default: FALSE)
1958 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1959 // Set debug instance to NULL
1960 $debugInstance = NULL;
1964 // Get debug instance
1965 $debugInstance = $this->getDebugInstance();
1966 } catch (NullPointerException $e) {
1967 // The debug instance is not set (yet)
1970 // Is the debug instance there?
1971 if (is_object($debugInstance)) {
1972 // Use debug output handler
1973 $debugInstance->output($message, $stripTags);
1975 if ($doPrint === FALSE) {
1976 // Die here if not printed
1980 // Are debug times enabled?
1981 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1983 $message = $this->getPrintableExecutionTime() . $message;
1987 if ($doPrint === TRUE) {
1989 $this->outputLine($message);
1998 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2000 * @param $str The string, what ever it is needs to be converted
2001 * @return $className Generated class name
2003 public static final function convertToClassName ($str) {
2007 // Convert all dashes in underscores
2008 $str = self::convertDashesToUnderscores($str);
2010 // Now use that underscores to get classname parts for hungarian style
2011 foreach (explode('_', $str) as $strPart) {
2012 // Make the class name part lower case and first upper case
2013 $className .= ucfirst(strtolower($strPart));
2016 // Return class name
2021 * Converts dashes to underscores, e.g. useable for configuration entries
2023 * @param $str The string with maybe dashes inside
2024 * @return $str The converted string with no dashed, but underscores
2026 public static final function convertDashesToUnderscores ($str) {
2028 $str = str_replace('-', '_', $str);
2030 // Return converted string
2035 * Marks up the code by adding e.g. line numbers
2037 * @param $phpCode Unmarked PHP code
2038 * @return $markedCode Marked PHP code
2040 public function markupCode ($phpCode) {
2045 $errorArray = error_get_last();
2047 // Init the code with error message
2048 if (is_array($errorArray)) {
2050 $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>',
2051 basename($errorArray['file']),
2052 $errorArray['line'],
2053 $errorArray['message'],
2058 // Add line number to the code
2059 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2061 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2063 htmlentities($code, ENT_QUOTES)
2072 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2073 * beatiful for web-based front-ends. If null is given a message id
2074 * null_timestamp will be resolved and returned.
2076 * @param $timestamp Timestamp to prepare (filter) for display
2077 * @return $readable A readable timestamp
2079 public function doFilterFormatTimestamp ($timestamp) {
2080 // Default value to return
2083 // Is the timestamp null?
2084 if (is_null($timestamp)) {
2085 // Get a message string
2086 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2088 switch ($this->getLanguageInstance()->getLanguageCode()) {
2089 case 'de': // German format is a bit different to default
2090 // Split the GMT stamp up
2091 $dateTime = explode(' ', $timestamp );
2092 $dateArray = explode('-', $dateTime[0]);
2093 $timeArray = explode(':', $dateTime[1]);
2095 // Construct the timestamp
2096 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2106 default: // Default is pass-through
2107 $readable = $timestamp;
2117 * Filter a given number into a localized number
2119 * @param $value The raw value from e.g. database
2120 * @return $localized Localized value
2122 public function doFilterFormatNumber ($value) {
2123 // Generate it from config and localize dependencies
2124 switch ($this->getLanguageInstance()->getLanguageCode()) {
2125 case 'de': // German format is a bit different to default
2126 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2129 default: // US, etc.
2130 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2139 * "Getter" for databse entry
2141 * @return $entry An array with database entries
2142 * @throws NullPointerException If the database result is not found
2143 * @throws InvalidDatabaseResultException If the database result is invalid
2145 protected final function getDatabaseEntry () {
2146 // Is there an instance?
2147 if (!$this->getResultInstance() instanceof SearchableResult) {
2148 // Throw an exception here
2149 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2153 $this->getResultInstance()->rewind();
2155 // Do we have an entry?
2156 if ($this->getResultInstance()->valid() === FALSE) {
2157 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2158 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2162 $this->getResultInstance()->next();
2165 $entry = $this->getResultInstance()->current();
2172 * Getter for field name
2174 * @param $fieldName Field name which we shall get
2175 * @return $fieldValue Field value from the user
2176 * @throws NullPointerException If the result instance is null
2178 public final function getField ($fieldName) {
2179 // Default field value
2182 // Get result instance
2183 $resultInstance = $this->getResultInstance();
2185 // Is this instance null?
2186 if (is_null($resultInstance)) {
2187 // Then the user instance is no longer valid (expired cookies?)
2188 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2191 // Get current array
2192 $fieldArray = $resultInstance->current();
2193 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2195 // Convert dashes to underscore
2196 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2198 // Does the field exist?
2199 if ($this->isFieldSet($fieldName)) {
2201 $fieldValue = $fieldArray[$fieldName2];
2202 } elseif (defined('DEVELOPER')) {
2203 // Missing field entry, may require debugging
2204 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2206 // Missing field entry, may require debugging
2207 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2215 * Checks if given field is set
2217 * @param $fieldName Field name to check
2218 * @return $isSet Whether the given field name is set
2219 * @throws NullPointerException If the result instance is null
2221 public function isFieldSet ($fieldName) {
2222 // Get result instance
2223 $resultInstance = $this->getResultInstance();
2225 // Is this instance null?
2226 if (is_null($resultInstance)) {
2227 // Then the user instance is no longer valid (expired cookies?)
2228 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2231 // Get current array
2232 $fieldArray = $resultInstance->current();
2233 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2235 // Convert dashes to underscore
2236 $fieldName = self::convertDashesToUnderscores($fieldName);
2239 $isSet = isset($fieldArray[$fieldName]);
2246 * Flushs all pending updates to the database layer
2250 public function flushPendingUpdates () {
2251 // Get result instance
2252 $resultInstance = $this->getResultInstance();
2254 // Do we have data to update?
2255 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2256 // Get wrapper class name config entry
2257 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2259 // Create object instance
2260 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2262 // Yes, then send the whole result to the database layer
2263 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2268 * Outputs a deprecation warning to the developer.
2270 * @param $message The message we shall output to the developer
2272 * @todo Write a logging mechanism for productive mode
2274 public function deprecationWarning ($message) {
2275 // Is developer mode active?
2276 if (defined('DEVELOPER')) {
2277 // Debug instance is there?
2278 if (!is_null($this->getDebugInstance())) {
2279 // Output stub message
2280 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2283 trigger_error($message . "<br />\n");
2287 // @TODO Finish this part!
2288 $this->partialStub('Developer mode inactive. Message:' . $message);
2293 * Checks whether the given PHP extension is loaded
2295 * @param $phpExtension The PHP extension we shall check
2296 * @return $isLoaded Whether the PHP extension is loaded
2298 public final function isPhpExtensionLoaded ($phpExtension) {
2300 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2307 * "Getter" as a time() replacement but with milliseconds. You should use this
2308 * method instead of the encapsulated getimeofday() function.
2310 * @return $milliTime Timestamp with milliseconds
2312 public function getMilliTime () {
2313 // Get the time of day as float
2314 $milliTime = gettimeofday(TRUE);
2321 * Idles (sleeps) for given milliseconds
2323 * @return $hasSlept Whether it goes fine
2325 public function idle ($milliSeconds) {
2326 // Sleep is fine by default
2329 // Idle so long with found function
2330 if (function_exists('time_sleep_until')) {
2331 // Get current time and add idle time
2332 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2334 // New PHP 5.1.0 function found, ignore errors
2335 $hasSlept = @time_sleep_until($sleepUntil);
2338 * My Sun station doesn't have that function even with latest PHP
2341 usleep($milliSeconds * 1000);
2348 * Converts a hexadecimal string, even with negative sign as first string to
2349 * a decimal number using BC functions.
2351 * This work is based on comment #86673 on php.net documentation page at:
2352 * <http://de.php.net/manual/en/function.dechex.php#86673>
2354 * @param $hex Hexadecimal string
2355 * @return $dec Decimal number
2357 protected function hex2dec ($hex) {
2358 // Convert to all lower-case
2359 $hex = strtolower($hex);
2361 // Detect sign (negative/positive numbers)
2363 if (substr($hex, 0, 1) == '-') {
2365 $hex = substr($hex, 1);
2368 // Decode the hexadecimal string into a decimal number
2370 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2371 $factor = self::$hexdec[substr($hex, $i, 1)];
2372 $dec = bcadd($dec, bcmul($factor, $e));
2375 // Return the decimal number
2376 return $sign . $dec;
2380 * Converts even very large decimal numbers, also signed, to a hexadecimal
2383 * This work is based on comment #97756 on php.net documentation page at:
2384 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2386 * @param $dec Decimal number, even with negative sign
2387 * @param $maxLength Optional maximum length of the string
2388 * @return $hex Hexadecimal string
2390 protected function dec2hex ($dec, $maxLength = 0) {
2391 // maxLength can be zero or devideable by 2
2392 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2394 // Detect sign (negative/positive numbers)
2401 // Encode the decimal number into a hexadecimal string
2404 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2406 } while ($dec >= 1);
2409 * Leading zeros are required for hex-decimal "numbers". In some
2410 * situations more leading zeros are wanted, so check for both
2413 if ($maxLength > 0) {
2414 // Prepend more zeros
2415 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2416 } elseif ((strlen($hex) % 2) != 0) {
2417 // Only make string's length dividable by 2
2421 // Return the hexadecimal string
2422 return $sign . $hex;
2426 * Converts a ASCII string (0 to 255) into a decimal number.
2428 * @param $asc The ASCII string to be converted
2429 * @return $dec Decimal number
2431 protected function asc2dec ($asc) {
2432 // Convert it into a hexadecimal number
2433 $hex = bin2hex($asc);
2435 // And back into a decimal number
2436 $dec = $this->hex2dec($hex);
2443 * Converts a decimal number into an ASCII string.
2445 * @param $dec Decimal number
2446 * @return $asc An ASCII string
2448 protected function dec2asc ($dec) {
2449 // First convert the number into a hexadecimal string
2450 $hex = $this->dec2hex($dec);
2452 // Then convert it into the ASCII string
2453 $asc = $this->hex2asc($hex);
2460 * Converts a hexadecimal number into an ASCII string. Negative numbers
2463 * @param $hex Hexadecimal string
2464 * @return $asc An ASCII string
2466 protected function hex2asc ($hex) {
2467 // Check for length, it must be devideable by 2
2468 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2469 assert((strlen($hex) % 2) == 0);
2473 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2474 // Get the decimal number of the chunk
2475 $part = hexdec(substr($hex, $idx, 2));
2477 // Add it to the final string
2481 // Return the final string
2486 * Checks whether the given encoded data was encoded with Base64
2488 * @param $encodedData Encoded data we shall check
2489 * @return $isBase64 Whether the encoded data is Base64
2491 protected function isBase64Encoded ($encodedData) {
2493 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2500 * "Getter" to get response/request type from analysis of the system.
2502 * @return $responseType Analyzed response type
2504 protected static function getResponseTypeFromSystem () {
2505 // Default is console
2506 $responseType = 'console';
2508 // Is 'HTTP_HOST' set?
2509 if (isset($_SERVER['HTTP_HOST'])) {
2511 * Then it is a HTML response/request as RSS and so on may be
2512 * transfered over HTTP as well.
2514 $responseType = 'html';
2518 return $responseType;
2522 * Gets a cache key from Criteria instance
2524 * @param $criteriaInstance An instance of a Criteria class
2525 * @param $onlyKeys Only use these keys for a cache key
2526 * @return $cacheKey A cache key suitable for lookup/storage purposes
2528 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2530 $cacheKey = sprintf('%s@%s',
2531 $this->__toString(),
2532 $criteriaInstance->getCacheKey($onlyKeys)
2536 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2541 * Getter for startup time in miliseconds
2543 * @return $startupTime Startup time in miliseconds
2545 protected function getStartupTime () {
2546 return self::$startupTime;
2550 * "Getter" for a printable currently execution time in nice braces
2552 * @return $executionTime Current execution time in nice braces
2554 protected function getPrintableExecutionTime () {
2555 // Caculate the execution time
2556 $executionTime = microtime(TRUE) - $this->getStartupTime();
2558 // Pack it in nice braces
2559 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2562 return $executionTime;
2566 * Hashes a given string with a simple but stronger hash function (no salt)
2567 * and hex-encode it.
2569 * @param $str The string to be hashed
2570 * @return $hash The hash from string $str
2572 public static final function hash ($str) {
2573 // Hash given string with (better secure) hasher
2574 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2581 * "Getter" for length of hash() output. This will be "cached" to speed up
2584 * @return $length Length of hash() output
2586 public static final function getHashLength () {
2588 if (is_null(self::$hashLength)) {
2589 // No, then hash a string and save its length.
2590 self::$hashLength = strlen(self::hash('abc123'));
2594 return self::$hashLength;
2598 * Checks whether the given number is really a number (only chars 0-9).
2600 * @param $num A string consisting only chars between 0 and 9
2601 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2602 * @param $assertMismatch Whether to assert mismatches
2603 * @return $ret The (hopefully) secured numbered value
2605 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2606 // Filter all numbers out
2607 $ret = preg_replace('/[^0123456789]/', '', $num);
2610 if ($castValue === TRUE) {
2611 // Cast to biggest numeric type
2612 $ret = (double) $ret;
2615 // Assert only if requested
2616 if ($assertMismatch === TRUE) {
2617 // Has the whole value changed?
2618 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2626 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2628 * @param $num A string consisting only chars between 0 and 9
2629 * @param $assertMismatch Whether to assert mismatches
2630 * @return $ret The (hopefully) secured hext-numbered value
2632 public function hexval ($num, $assertMismatch = FALSE) {
2633 // Filter all numbers out
2634 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2636 // Assert only if requested
2637 if ($assertMismatch === TRUE) {
2638 // Has the whole value changed?
2639 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2647 * Checks whether start/end marker are set
2649 * @param $data Data to be checked
2650 * @return $isset Whether start/end marker are set
2652 public final function ifStartEndMarkersSet ($data) {
2654 $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));
2656 // ... and return it
2661 * Determines if an element is set in the generic array
2663 * @param $keyGroup Main group for the key
2664 * @param $subGroup Sub group for the key
2665 * @param $key Key to check
2666 * @param $element Element to check
2667 * @return $isset Whether the given key is set
2669 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2671 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2674 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2680 * Determines if a key is set in the generic array
2682 * @param $keyGroup Main group for the key
2683 * @param $subGroup Sub group for the key
2684 * @param $key Key to check
2685 * @return $isset Whether the given key is set
2687 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2689 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2692 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2700 * Determines if a group is set in the generic array
2702 * @param $keyGroup Main group
2703 * @param $subGroup Sub group
2704 * @return $isset Whether the given group is set
2706 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2708 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2711 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2718 * Getter for sub key group
2720 * @param $keyGroup Main key group
2721 * @param $subGroup Sub key group
2722 * @return $array An array with all array elements
2724 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2726 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2727 // No, then abort here
2728 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2733 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2736 return $this->genericArray[$keyGroup][$subGroup];
2740 * Unsets a given key in generic array
2742 * @param $keyGroup Main group for the key
2743 * @param $subGroup Sub group for the key
2744 * @param $key Key to unset
2747 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2749 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2752 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2756 * Unsets a given element in generic array
2758 * @param $keyGroup Main group for the key
2759 * @param $subGroup Sub group for the key
2760 * @param $key Key to unset
2761 * @param $element Element to unset
2764 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2766 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2769 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2773 * Append a string to a given generic array key
2775 * @param $keyGroup Main group for the key
2776 * @param $subGroup Sub group for the key
2777 * @param $key Key to unset
2778 * @param $value Value to add/append
2781 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2783 //* 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);
2785 // Is it already there?
2786 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2788 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2791 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2796 * Append a string to a given generic array element
2798 * @param $keyGroup Main group for the key
2799 * @param $subGroup Sub group for the key
2800 * @param $key Key to unset
2801 * @param $element Element to check
2802 * @param $value Value to add/append
2805 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2807 //* 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);
2809 // Is it already there?
2810 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2812 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2815 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2820 * Sets a string in a given generic array element
2822 * @param $keyGroup Main group for the key
2823 * @param $subGroup Sub group for the key
2824 * @param $key Key to unset
2825 * @param $element Element to check
2826 * @param $value Value to add/append
2829 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2831 //* 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);
2834 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2838 * Initializes given generic array group
2840 * @param $keyGroup Main group for the key
2841 * @param $subGroup Sub group for the key
2842 * @param $key Key to use
2843 * @param $forceInit Optionally force initialization
2846 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2848 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2850 // Is it already set?
2851 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2852 // Already initialized
2853 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2858 $this->genericArray[$keyGroup][$subGroup] = array();
2862 * Initializes given generic array key
2864 * @param $keyGroup Main group for the key
2865 * @param $subGroup Sub group for the key
2866 * @param $key Key to use
2867 * @param $forceInit Optionally force initialization
2870 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2872 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2874 // Is it already set?
2875 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2876 // Already initialized
2877 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2882 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2886 * Initializes given generic array element
2888 * @param $keyGroup Main group for the key
2889 * @param $subGroup Sub group for the key
2890 * @param $key Key to use
2891 * @param $element Element to use
2892 * @param $forceInit Optionally force initialization
2895 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2897 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2899 // Is it already set?
2900 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2901 // Already initialized
2902 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2907 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2911 * Pushes an element to a generic key
2913 * @param $keyGroup Main group for the key
2914 * @param $subGroup Sub group for the key
2915 * @param $key Key to use
2916 * @param $value Value to add/append
2917 * @return $count Number of array elements
2919 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2921 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2924 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2926 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2930 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2933 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2934 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2939 * Pushes an element to a generic array element
2941 * @param $keyGroup Main group for the key
2942 * @param $subGroup Sub group for the key
2943 * @param $key Key to use
2944 * @param $element Element to check
2945 * @param $value Value to add/append
2946 * @return $count Number of array elements
2948 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2950 //* 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));
2953 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2955 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2959 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2962 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2963 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2968 * Pops an element from a generic group
2970 * @param $keyGroup Main group for the key
2971 * @param $subGroup Sub group for the key
2972 * @param $key Key to unset
2973 * @return $value Last "popped" value
2975 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2977 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2980 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2982 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2987 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2990 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2991 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2996 * Shifts an element from a generic group
2998 * @param $keyGroup Main group for the key
2999 * @param $subGroup Sub group for the key
3000 * @param $key Key to unset
3001 * @return $value Last "popped" value
3003 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3005 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3008 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3010 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3015 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3018 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3019 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3024 * Count generic array group
3026 * @param $keyGroup Main group for the key
3027 * @return $count Count of given group
3029 protected final function countGenericArray ($keyGroup) {
3031 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3034 if (!isset($this->genericArray[$keyGroup])) {
3036 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3041 $count = count($this->genericArray[$keyGroup]);
3044 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3051 * Count generic array sub group
3053 * @param $keyGroup Main group for the key
3054 * @param $subGroup Sub group for the key
3055 * @return $count Count of given group
3057 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3059 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3062 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3064 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3069 $count = count($this->genericArray[$keyGroup][$subGroup]);
3072 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3079 * Count generic array elements
3081 * @param $keyGroup Main group for the key
3082 * @param $subGroup Sub group for the key
3083 * @para $key Key to count
3084 * @return $count Count of given key
3086 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3088 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3091 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3093 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3095 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3097 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3102 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3105 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3112 * Getter for whole generic group array
3114 * @param $keyGroup Key group to get
3115 * @return $array Whole generic array group
3117 protected final function getGenericArray ($keyGroup) {
3119 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3122 if (!isset($this->genericArray[$keyGroup])) {
3124 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3129 return $this->genericArray[$keyGroup];
3133 * Setter for generic array key
3135 * @param $keyGroup Key group to get
3136 * @param $subGroup Sub group for the key
3137 * @param $key Key to unset
3138 * @param $value Mixed value from generic array element
3141 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3143 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3146 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3150 * Getter for generic array key
3152 * @param $keyGroup Key group to get
3153 * @param $subGroup Sub group for the key
3154 * @param $key Key to unset
3155 * @return $value Mixed value from generic array element
3157 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3159 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3162 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3164 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3169 return $this->genericArray[$keyGroup][$subGroup][$key];
3173 * Sets a value in given generic array key/element
3175 * @param $keyGroup Main group for the key
3176 * @param $subGroup Sub group for the key
3177 * @param $key Key to set
3178 * @param $element Element to set
3179 * @param $value Value to set
3182 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3184 //* 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));
3187 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3191 * Getter for generic array element
3193 * @param $keyGroup Key group to get
3194 * @param $subGroup Sub group for the key
3195 * @param $key Key to look for
3196 * @param $element Element to look for
3197 * @return $value Mixed value from generic array element
3199 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3201 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3204 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3206 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3211 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3215 * Checks if a given sub group is valid (array)
3217 * @param $keyGroup Key group to get
3218 * @param $subGroup Sub group for the key
3219 * @return $isValid Whether given sub group is valid
3221 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3223 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3226 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3233 * Checks if a given key is valid (array)
3235 * @param $keyGroup Key group to get
3236 * @param $subGroup Sub group for the key
3237 * @param $key Key to check
3238 * @return $isValid Whether given sub group is valid
3240 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3242 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3245 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3252 * Initializes the web output instance
3256 protected function initWebOutputInstance () {
3257 // Get application instance
3258 $applicationInstance = Registry::getRegistry()->getInstance('app');
3260 // Is this a response instance?
3261 if ($this instanceof Responseable) {
3262 // Then set it in application instance
3263 $applicationInstance->setResponseInstance($this);
3266 // Init web output instance
3267 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3270 $this->setWebOutputInstance($outputInstance);
3274 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3276 * @param $boolean Boolean value
3277 * @return $translated Translated boolean value
3279 public static final function translateBooleanToYesNo ($boolean) {
3280 // Make sure it is really boolean
3281 assert(is_bool($boolean));
3284 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3286 // ... and return it
3291 * Encodes raw data (almost any type) by "serializing" it and then pack it
3292 * into a "binary format".
3294 * @param $rawData Raw data (almost any type)
3295 * @return $encoded Encoded data
3297 protected function encodeData ($rawData) {
3298 // Make sure no objects or resources pass through
3299 assert(!is_object($rawData));
3300 assert(!is_resource($rawData));
3302 // First "serialize" it (json_encode() is faster than serialize())
3303 $encoded = $this->packString(json_encode($rawData));
3310 * Pack a string into a "binary format". Please execuse me that this is
3311 * widely undocumented. :-(
3313 * @param $str Unpacked string
3314 * @return $packed Packed string
3315 * @todo Improve documentation
3317 protected function packString ($str) {
3319 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3321 // First compress the string (gzcompress is okay)
3322 $str = gzcompress($str);
3327 // And start the "encoding" loop
3328 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3330 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3331 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3333 if (($idx + $i) <= strlen($str)) {
3334 $ord = ord(substr($str, ($idx + $i), 1));
3336 $add = $ord * pow(256, $factor);
3340 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3344 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3345 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3347 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3348 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3354 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3359 * Checks whether the given file/path is in open_basedir(). This does not
3360 * gurantee that the file is actually readable and/or writeable. If you need
3361 * such gurantee then please use isReadableFile() instead.
3363 * @param $filePathName Name of the file/path to be checked
3364 * @return $isReachable Whether it is within open_basedir()
3366 protected static function isReachableFilePath ($filePathName) {
3367 // Is not reachable by default
3368 $isReachable = FALSE;
3370 // Get open_basedir parameter
3371 $openBaseDir = ini_get('open_basedir');
3374 if (!empty($openBaseDir)) {
3375 // Check all entries
3376 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3377 // Check on existence
3378 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3380 $isReachable = TRUE;
3384 // If open_basedir is not set, all is allowed
3385 $isReachable = TRUE;
3389 return $isReachable;
3393 * Checks whether the give file is within open_basedir() (done by
3394 * isReachableFilePath()), is actually a file and is readable.
3396 * @param $fileName Name of the file to be checked
3397 * @return $isReadable Whether the file is readable (and therefor exists)
3399 public static function isReadableFile ($fileName) {
3400 // Default is not readable
3401 $isReadable = FALSE;
3403 // Is within parameters, so check if it is a file and readable
3404 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3411 * Creates a full-qualified file name (FQFN) for given file name by adding
3412 * a configured temporary file path to it.
3414 * @param $fileName Name for temporary file
3415 * @return $fqfn Full-qualified file name
3416 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3417 * @throws FileIoException If the file cannot be written
3419 protected static function createTempPathForFile ($fileName) {
3421 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3423 // Is the path writeable?
3424 if (!is_writable($basePath)) {
3425 // Path is write-protected
3426 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3430 $fqfn = $basePath . '/' . $fileName;
3433 if (!self::isReachableFilePath($fqfn)) {
3435 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3443 * "Getter" for a printable state name
3445 * @return $stateName Name of the node's state in a printable format
3447 public final function getPrintableState () {
3448 // Default is 'null'
3449 $stateName = 'null';
3451 // Get the state instance
3452 $stateInstance = $this->getStateInstance();
3454 // Is it an instance of Stateable?
3455 if ($stateInstance instanceof Stateable) {
3456 // Then use that state name
3457 $stateName = $stateInstance->getStateName();
3465 * Handles socket error for given socket resource and peer data. This method
3466 * validates $socketResource if it is a valid resource (see is_resource())
3467 * but assumes valid data in array $recipientData, except that
3468 * count($recipientData) is always 2.
3470 * @param $method Value of __METHOD__ from calling method
3471 * @param $line Value of __LINE__ from calling method
3472 * @param $socketResource A valid socket resource
3473 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3475 * @throws InvalidSocketException If $socketResource is no socket resource
3476 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3477 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3479 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3480 // This method handles only socket resources
3481 if (!is_resource($socketResource)) {
3482 // No resource, abort here
3483 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3486 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3487 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3488 assert(isset($socketData[0]));
3489 assert(isset($socketData[1]));
3491 // Get error code for first validation (0 is not an error)
3492 $errorCode = socket_last_error($socketResource);
3494 // If the error code is zero, someone called this method without an error
3495 if ($errorCode == 0) {
3496 // No error detected (or previously cleared outside this method)
3497 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3500 // Get handler (method) name
3501 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3503 // Call-back the error handler method
3504 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3506 // Finally clear the error because it has been handled
3507 socket_clear_error($socketResource);