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\Loader\ClassLoader;
10 use CoreFramework\Manager\ManageableApplication;
11 use CoreFramework\Middleware\Debug\DebugMiddleware;
12 use CoreFramework\Registry\Register;
13 use CoreFramework\Registry\Generic\Registry;
14 use CoreFramework\Template\CompileableTemplate;
20 * The simulator system class is the super class of all other classes. This
21 * class handles saving of games etc.
23 * @author Roland Haeder <webmaster@shipsimu.org>
25 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
26 * @license GNU GPL 3.0 or any newer version
27 * @link http://www.shipsimu.org
29 * This program is free software: you can redistribute it and/or modify
30 * it under the terms of the GNU General Public License as published by
31 * the Free Software Foundation, either version 3 of the License, or
32 * (at your option) any later version.
34 * This program is distributed in the hope that it will be useful,
35 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 * GNU General Public License for more details.
39 * You should have received a copy of the GNU General Public License
40 * along with this program. If not, see <http://www.gnu.org/licenses/>.
42 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
44 * Length of output from hash()
46 private static $hashLength = NULL;
51 private $realClass = 'BaseFrameworkSystem';
54 * Instance of a request class
56 private $requestInstance = NULL;
59 * Instance of a response class
61 private $responseInstance = NULL;
64 * Search criteria instance
66 private $searchInstance = NULL;
69 * Update criteria instance
71 private $updateInstance = NULL;
74 * The file I/O instance for the template loader
76 private $fileIoInstance = NULL;
81 private $resolverInstance = NULL;
84 * Template engine instance
86 private $templateInstance = NULL;
89 * Database result instance
91 private $resultInstance = NULL;
94 * Instance for user class
96 private $userInstance = NULL;
99 * A controller instance
101 private $controllerInstance = NULL;
106 private $rngInstance = NULL;
109 * Instance of a crypto helper
111 private $cryptoInstance = NULL;
114 * Instance of an Iterator class
116 private $iteratorInstance = NULL;
119 * Instance of the list
121 private $listInstance = NULL;
126 private $menuInstance = NULL;
129 * Instance of the image
131 private $imageInstance = NULL;
134 * Instance of the stacker
136 private $stackInstance = NULL;
139 * A Compressor instance
141 private $compressorInstance = NULL;
144 * A Parseable instance
146 private $parserInstance = NULL;
149 * A HandleableProtocol instance
151 private $protocolInstance = NULL;
154 * A database wrapper instance
156 private $databaseInstance = NULL;
159 * A helper instance for the form
161 private $helperInstance = NULL;
164 * An instance of a Source class
166 private $sourceInstance = NULL;
169 * An instance of a UrlSource class
171 private $urlSourceInstance = NULL;
174 * An instance of a InputStream class
176 private $inputStreamInstance = NULL;
179 * An instance of a OutputStream class
181 private $outputStreamInstance = NULL;
184 * Networkable handler instance
186 private $handlerInstance = NULL;
189 * Visitor handler instance
191 private $visitorInstance = NULL;
196 private $dhtInstance = NULL;
199 * An instance of a database wrapper class
201 private $wrapperInstance = NULL;
204 * An instance of a file I/O pointer class (not handler)
206 private $pointerInstance = NULL;
209 * An instance of an Indexable class
211 private $indexInstance = NULL;
214 * An instance of a Block class
216 private $blockInstance = NULL;
221 private $minableInstance = NULL;
224 * A FrameworkDirectory instance
226 private $directoryInstance = NULL;
231 private $listenerInstance = NULL;
234 * An instance of a communicator
236 private $communicatorInstance = NULL;
239 * The concrete output instance
241 private $outputInstance = NULL;
246 private $stateInstance = NULL;
249 * Thousands separator
251 private $thousands = '.'; // German
256 private $decimals = ','; // German
261 private $socketResource = FALSE;
264 * Regular expression to use for validation
266 private $regularExpression = '';
271 private $packageData = array();
276 private $genericArray = array();
281 private $commandName = '';
286 private $controllerName = '';
289 * Name of used protocol
291 private $protocolName = 'invalid';
294 * Array with bitmasks and such for pack/unpack methods to support both
295 * 32-bit and 64-bit systems
297 private $packingData = array(
300 'left' => 0xffff0000,
301 'right' => 0x0000ffff,
307 'left' => 0xffffffff00000000,
308 'right' => 0x00000000ffffffff,
315 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
317 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
319 private $archArrayElement = FALSE;
321 /***********************
322 * Exception codes.... *
323 ***********************/
325 // @todo Try to clean these constants up
326 const EXCEPTION_IS_NULL_POINTER = 0x001;
327 const EXCEPTION_IS_NO_OBJECT = 0x002;
328 const EXCEPTION_IS_NO_ARRAY = 0x003;
329 const EXCEPTION_MISSING_METHOD = 0x004;
330 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
331 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
332 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
333 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
334 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
335 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
336 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
337 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
338 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
339 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
340 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
341 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
342 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
343 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
344 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
345 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
346 const EXCEPTION_PATH_NOT_FOUND = 0x015;
347 const EXCEPTION_INVALID_PATH_NAME = 0x016;
348 const EXCEPTION_READ_PROTECED_PATH = 0x017;
349 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
350 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
351 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
352 const EXCEPTION_INVALID_RESOURCE = 0x01b;
353 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
354 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
355 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
356 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
357 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
358 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
359 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
360 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
361 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
362 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
363 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
364 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
365 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
366 const EXCEPTION_INVALID_STRING = 0x029;
367 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
368 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
369 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
370 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
371 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
372 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
373 const EXCEPTION_MISSING_ELEMENT = 0x030;
374 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
375 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
376 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
377 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
378 const EXCEPTION_FATAL_ERROR = 0x035;
379 const EXCEPTION_FILE_NOT_FOUND = 0x036;
380 const EXCEPTION_ASSERTION_FAILED = 0x037;
381 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
382 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
383 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
384 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
385 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
386 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
389 * Hexadecimal->Decimal translation array
391 private static $hexdec = array(
411 * Decimal->hexadecimal translation array
413 private static $dechex = array(
433 * Startup time in miliseconds
435 private static $startupTime = 0;
438 * Protected super constructor
440 * @param $className Name of the class
443 protected function __construct ($className) {
445 $this->setRealClass($className);
447 // Set configuration instance if no registry ...
448 if (!$this instanceof Register) {
449 // ... because registries doesn't need to be configured
450 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
453 // Is the startup time set? (0 cannot be TRUE anymore)
454 if (self::$startupTime == 0) {
456 self::$startupTime = microtime(TRUE);
460 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
464 * Destructor for all classes. You should not call this method on your own.
468 public function __destruct () {
469 // Flush any updated entries to the database
470 $this->flushPendingUpdates();
472 // Is this object already destroyed?
473 if ($this->__toString() != 'DestructedObject') {
474 // Destroy all informations about this class but keep some text about it alive
475 $this->setRealClass('DestructedObject');
476 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
477 // Already destructed object
478 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
483 // Do not call this twice
484 trigger_error(__METHOD__ . ': Called twice.');
490 * The __call() method where all non-implemented methods end up
492 * @param $methodName Name of the missing method
493 * @args $args Arguments passed to the method
496 public final function __call ($methodName, $args) {
497 return self::__callStatic($methodName, $args);
501 * The __callStatic() method where all non-implemented static methods end up
503 * @param $methodName Name of the missing method
504 * @args $args Arguments passed to the method
507 public static final function __callStatic ($methodName, $args) {
508 // Init argument string
511 // Is it NULL, empty or an array?
512 if (is_null($args)) {
514 $argsString = 'NULL';
515 } elseif (is_array($args)) {
519 // Some arguments are there
520 foreach ($args as $arg) {
521 // Add data about the argument
522 $argsString .= gettype($arg) . ':';
525 // Found a NULL argument
526 $argsString .= 'NULL';
527 } elseif (is_string($arg)) {
528 // Add length for strings
529 $argsString .= strlen($arg);
530 } elseif ((is_int($arg)) || (is_float($arg))) {
533 } elseif (is_array($arg)) {
534 // .. or size if array
535 $argsString .= count($arg);
536 } elseif (is_object($arg)) {
538 $reflection = new ReflectionClass($arg);
540 // Is an other object, maybe no __toString() available
541 $argsString .= $reflection->getName();
542 } elseif ($arg === TRUE) {
543 // ... is boolean 'TRUE'
544 $argsString .= 'TRUE';
545 } elseif ($arg === FALSE) {
546 // ... is boolean 'FALSE'
547 $argsString .= 'FALSE';
550 // Comma for next one
555 if (substr($argsString, -2, 1) == ',') {
556 $argsString = substr($argsString, 0, -2);
562 // Invalid arguments!
563 $argsString = '!INVALID:' . gettype($args) . '!';
566 // Output stub message
567 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
568 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
578 * Getter for $realClass
580 * @return $realClass The name of the real class (not BaseFrameworkSystem)
582 public function __toString () {
583 return $this->realClass;
587 * Magic method to catch setting of missing but set class fields/attributes
589 * @param $name Name of the field/attribute
590 * @param $value Value to store
593 public final function __set ($name, $value) {
594 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
597 print_r($value, TRUE)
602 * Magic method to catch getting of missing fields/attributes
604 * @param $name Name of the field/attribute
607 public final function __get ($name) {
608 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
614 * Magic method to catch unsetting of missing fields/attributes
616 * @param $name Name of the field/attribute
619 public final function __unset ($name) {
620 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
626 * Magic method to catch object serialization
628 * @return $unsupported Unsupported method
629 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
631 public final function __sleep () {
632 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
636 * Magic method to catch object deserialization
638 * @return $unsupported Unsupported method
639 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
641 public final function __wakeup () {
642 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
646 * Magic method to catch calls when an object instance is called
648 * @return $unsupported Unsupported method
649 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
651 public final function __invoke () {
652 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
656 * Setter for the real class name
658 * @param $realClass Class name (string)
661 public final function setRealClass ($realClass) {
663 $this->realClass = (string) $realClass;
667 * Setter for database result instance
669 * @param $resultInstance An instance of a database result class
671 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
673 protected final function setResultInstance (SearchableResult $resultInstance) {
674 $this->resultInstance = $resultInstance;
678 * Getter for database result instance
680 * @return $resultInstance An instance of a database result class
682 public final function getResultInstance () {
683 return $this->resultInstance;
687 * Setter for template engine instances
689 * @param $templateInstance An instance of a template engine class
692 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
693 $this->templateInstance = $templateInstance;
697 * Getter for template engine instances
699 * @return $templateInstance An instance of a template engine class
701 protected final function getTemplateInstance () {
702 return $this->templateInstance;
706 * Setter for search instance
708 * @param $searchInstance Searchable criteria instance
711 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
712 $this->searchInstance = $searchInstance;
716 * Getter for search instance
718 * @return $searchInstance Searchable criteria instance
720 public final function getSearchInstance () {
721 return $this->searchInstance;
725 * Setter for update instance
727 * @param $updateInstance Searchable criteria instance
730 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
731 $this->updateInstance = $updateInstance;
735 * Getter for update instance
737 * @return $updateInstance Updateable criteria instance
739 public final function getUpdateInstance () {
740 return $this->updateInstance;
744 * Setter for resolver instance
746 * @param $resolverInstance Instance of a command resolver class
749 public final function setResolverInstance (Resolver $resolverInstance) {
750 $this->resolverInstance = $resolverInstance;
754 * Getter for resolver instance
756 * @return $resolverInstance Instance of a command resolver class
758 public final function getResolverInstance () {
759 return $this->resolverInstance;
763 * Setter for language instance
765 * @param $configInstance The configuration instance which shall
766 * be FrameworkConfiguration
769 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
770 Registry::getRegistry()->addInstance('config', $configInstance);
774 * Getter for configuration instance
776 * @return $configInstance Configuration instance
778 public final function getConfigInstance () {
779 $configInstance = Registry::getRegistry()->getInstance('config');
780 return $configInstance;
784 * Setter for debug instance
786 * @param $debugInstance The instance for debug output class
789 public final function setDebugInstance (DebugMiddleware $debugInstance) {
790 Registry::getRegistry()->addInstance('debug', $debugInstance);
794 * Getter for debug instance
796 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
798 public final function getDebugInstance () {
799 // Get debug instance
800 $debugInstance = Registry::getRegistry()->getInstance('debug');
803 return $debugInstance;
807 * Setter for web output instance
809 * @param $webInstance The instance for web output class
812 public final function setWebOutputInstance (OutputStreamer $webInstance) {
813 Registry::getRegistry()->addInstance('web_output', $webInstance);
817 * Getter for web output instance
819 * @return $webOutputInstance - Instance to class WebOutput
821 public final function getWebOutputInstance () {
822 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
823 return $webOutputInstance;
827 * Setter for database instance
829 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
832 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
833 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
837 * Getter for database layer
839 * @return $databaseInstance The database layer instance
841 public final function getDatabaseInstance () {
843 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
846 return $databaseInstance;
850 * Setter for compressor channel
852 * @param $compressorInstance An instance of CompressorChannel
855 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
856 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
860 * Getter for compressor channel
862 * @return $compressorInstance The compressor channel
864 public final function getCompressorChannel () {
865 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
866 return $compressorInstance;
870 * Protected getter for a manageable application helper class
872 * @return $applicationInstance An instance of a manageable application helper class
874 protected final function getApplicationInstance () {
875 $applicationInstance = Registry::getRegistry()->getInstance('application');
876 return $applicationInstance;
880 * Setter for a manageable application helper class
882 * @param $applicationInstance An instance of a manageable application helper class
885 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
886 Registry::getRegistry()->addInstance('application', $applicationInstance);
890 * Setter for request instance
892 * @param $requestInstance An instance of a Requestable class
895 public final function setRequestInstance (Requestable $requestInstance) {
896 $this->requestInstance = $requestInstance;
900 * Getter for request instance
902 * @return $requestInstance An instance of a Requestable class
904 public final function getRequestInstance () {
905 return $this->requestInstance;
909 * Setter for response instance
911 * @param $responseInstance An instance of a Responseable class
914 public final function setResponseInstance (Responseable $responseInstance) {
915 $this->responseInstance = $responseInstance;
919 * Getter for response instance
921 * @return $responseInstance An instance of a Responseable class
923 public final function getResponseInstance () {
924 return $this->responseInstance;
928 * Private getter for language instance
930 * @return $langInstance An instance to the language sub-system
932 protected final function getLanguageInstance () {
933 $langInstance = Registry::getRegistry()->getInstance('language');
934 return $langInstance;
938 * Setter for language instance
940 * @param $langInstance An instance to the language sub-system
942 * @see LanguageSystem
944 public final function setLanguageInstance (ManageableLanguage $langInstance) {
945 Registry::getRegistry()->addInstance('language', $langInstance);
949 * Private getter for file IO instance
951 * @return $fileIoInstance An instance to the file I/O sub-system
953 protected final function getFileIoInstance () {
954 return $this->fileIoInstance;
958 * Setter for file I/O instance
960 * @param $fileIoInstance An instance to the file I/O sub-system
963 public final function setFileIoInstance (IoHandler $fileIoInstance) {
964 $this->fileIoInstance = $fileIoInstance;
968 * Protected setter for user instance
970 * @param $userInstance An instance of a user class
973 protected final function setUserInstance (ManageableAccount $userInstance) {
974 $this->userInstance = $userInstance;
978 * Getter for user instance
980 * @return $userInstance An instance of a user class
982 public final function getUserInstance () {
983 return $this->userInstance;
987 * Setter for controller instance (this surely breaks a bit the MVC patterm)
989 * @param $controllerInstance An instance of the controller
992 public final function setControllerInstance (Controller $controllerInstance) {
993 $this->controllerInstance = $controllerInstance;
997 * Getter for controller instance (this surely breaks a bit the MVC patterm)
999 * @return $controllerInstance An instance of the controller
1001 public final function getControllerInstance () {
1002 return $this->controllerInstance;
1006 * Setter for RNG instance
1008 * @param $rngInstance An instance of a random number generator (RNG)
1011 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1012 $this->rngInstance = $rngInstance;
1016 * Getter for RNG instance
1018 * @return $rngInstance An instance of a random number generator (RNG)
1020 public final function getRngInstance () {
1021 return $this->rngInstance;
1025 * Setter for Cryptable instance
1027 * @param $cryptoInstance An instance of a Cryptable class
1030 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1031 $this->cryptoInstance = $cryptoInstance;
1035 * Getter for Cryptable instance
1037 * @return $cryptoInstance An instance of a Cryptable class
1039 public final function getCryptoInstance () {
1040 return $this->cryptoInstance;
1044 * Setter for the list instance
1046 * @param $listInstance A list of Listable
1049 protected final function setListInstance (Listable $listInstance) {
1050 $this->listInstance = $listInstance;
1054 * Getter for the list instance
1056 * @return $listInstance A list of Listable
1058 protected final function getListInstance () {
1059 return $this->listInstance;
1063 * Setter for the menu instance
1065 * @param $menuInstance A RenderableMenu instance
1068 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1069 $this->menuInstance = $menuInstance;
1073 * Getter for the menu instance
1075 * @return $menuInstance A RenderableMenu instance
1077 protected final function getMenuInstance () {
1078 return $this->menuInstance;
1082 * Setter for image instance
1084 * @param $imageInstance An instance of an image
1087 public final function setImageInstance (BaseImage $imageInstance) {
1088 $this->imageInstance = $imageInstance;
1092 * Getter for image instance
1094 * @return $imageInstance An instance of an image
1096 public final function getImageInstance () {
1097 return $this->imageInstance;
1101 * Setter for stacker instance
1103 * @param $stackInstance An instance of an stacker
1106 public final function setStackInstance (Stackable $stackInstance) {
1107 $this->stackInstance = $stackInstance;
1111 * Getter for stacker instance
1113 * @return $stackInstance An instance of an stacker
1115 public final function getStackInstance () {
1116 return $this->stackInstance;
1120 * Setter for compressor instance
1122 * @param $compressorInstance An instance of an compressor
1125 public final function setCompressorInstance (Compressor $compressorInstance) {
1126 $this->compressorInstance = $compressorInstance;
1130 * Getter for compressor instance
1132 * @return $compressorInstance An instance of an compressor
1134 public final function getCompressorInstance () {
1135 return $this->compressorInstance;
1139 * Setter for Parseable instance
1141 * @param $parserInstance An instance of an Parseable
1144 public final function setParserInstance (Parseable $parserInstance) {
1145 $this->parserInstance = $parserInstance;
1149 * Getter for Parseable instance
1151 * @return $parserInstance An instance of an Parseable
1153 public final function getParserInstance () {
1154 return $this->parserInstance;
1158 * Setter for HandleableProtocol instance
1160 * @param $protocolInstance An instance of an HandleableProtocol
1163 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1164 $this->protocolInstance = $protocolInstance;
1168 * Getter for HandleableProtocol instance
1170 * @return $protocolInstance An instance of an HandleableProtocol
1172 public final function getProtocolInstance () {
1173 return $this->protocolInstance;
1177 * Setter for DatabaseWrapper instance
1179 * @param $wrapperInstance An instance of an DatabaseWrapper
1182 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1183 $this->wrapperInstance = $wrapperInstance;
1187 * Getter for DatabaseWrapper instance
1189 * @return $wrapperInstance An instance of an DatabaseWrapper
1191 public final function getWrapperInstance () {
1192 return $this->wrapperInstance;
1196 * Setter for socket resource
1198 * @param $socketResource A valid socket resource
1201 public final function setSocketResource ($socketResource) {
1202 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1203 $this->socketResource = $socketResource;
1207 * Getter for socket resource
1209 * @return $socketResource A valid socket resource
1211 public final function getSocketResource () {
1212 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1213 return $this->socketResource;
1217 * Setter for regular expression
1219 * @param $regularExpression A valid regular expression
1222 public final function setRegularExpression ($regularExpression) {
1223 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1224 $this->regularExpression = $regularExpression;
1228 * Getter for regular expression
1230 * @return $regularExpression A valid regular expression
1232 public final function getRegularExpression () {
1233 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1234 return $this->regularExpression;
1238 * Setter for helper instance
1240 * @param $helperInstance An instance of a helper class
1243 protected final function setHelperInstance (Helper $helperInstance) {
1244 $this->helperInstance = $helperInstance;
1248 * Getter for helper instance
1250 * @return $helperInstance An instance of a helper class
1252 public final function getHelperInstance () {
1253 return $this->helperInstance;
1257 * Setter for a Source instance
1259 * @param $sourceInstance An instance of a Source class
1262 protected final function setSourceInstance (Source $sourceInstance) {
1263 $this->sourceInstance = $sourceInstance;
1267 * Getter for a Source instance
1269 * @return $sourceInstance An instance of a Source class
1271 protected final function getSourceInstance () {
1272 return $this->sourceInstance;
1276 * Setter for a UrlSource instance
1278 * @param $sourceInstance An instance of a UrlSource class
1281 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1282 $this->urlSourceInstance = $urlSourceInstance;
1286 * Getter for a UrlSource instance
1288 * @return $urlSourceInstance An instance of a UrlSource class
1290 protected final function getUrlSourceInstance () {
1291 return $this->urlSourceInstance;
1295 * Getter for a InputStream instance
1297 * @param $inputStreamInstance The InputStream instance
1299 protected final function getInputStreamInstance () {
1300 return $this->inputStreamInstance;
1304 * Setter for a InputStream instance
1306 * @param $inputStreamInstance The InputStream instance
1309 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1310 $this->inputStreamInstance = $inputStreamInstance;
1314 * Getter for a OutputStream instance
1316 * @param $outputStreamInstance The OutputStream instance
1318 protected final function getOutputStreamInstance () {
1319 return $this->outputStreamInstance;
1323 * Setter for a OutputStream instance
1325 * @param $outputStreamInstance The OutputStream instance
1328 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1329 $this->outputStreamInstance = $outputStreamInstance;
1333 * Setter for handler instance
1335 * @param $handlerInstance An instance of a Handleable class
1338 protected final function setHandlerInstance (Handleable $handlerInstance) {
1339 $this->handlerInstance = $handlerInstance;
1343 * Getter for handler instance
1345 * @return $handlerInstance A Networkable instance
1347 protected final function getHandlerInstance () {
1348 return $this->handlerInstance;
1352 * Setter for visitor instance
1354 * @param $visitorInstance A Visitor instance
1357 protected final function setVisitorInstance (Visitor $visitorInstance) {
1358 $this->visitorInstance = $visitorInstance;
1362 * Getter for visitor instance
1364 * @return $visitorInstance A Visitor instance
1366 protected final function getVisitorInstance () {
1367 return $this->visitorInstance;
1371 * Setter for DHT instance
1373 * @param $dhtInstance A Distributable instance
1376 protected final function setDhtInstance (Distributable $dhtInstance) {
1377 $this->dhtInstance = $dhtInstance;
1381 * Getter for DHT instance
1383 * @return $dhtInstance A Distributable instance
1385 protected final function getDhtInstance () {
1386 return $this->dhtInstance;
1390 * Setter for raw package Data
1392 * @param $packageData Raw package Data
1395 public final function setPackageData (array $packageData) {
1396 $this->packageData = $packageData;
1400 * Getter for raw package Data
1402 * @return $packageData Raw package Data
1404 public function getPackageData () {
1405 return $this->packageData;
1410 * Setter for Iterator instance
1412 * @param $iteratorInstance An instance of an Iterator
1415 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1416 $this->iteratorInstance = $iteratorInstance;
1420 * Getter for Iterator instance
1422 * @return $iteratorInstance An instance of an Iterator
1424 public final function getIteratorInstance () {
1425 return $this->iteratorInstance;
1429 * Setter for FilePointer instance
1431 * @param $pointerInstance An instance of an FilePointer class
1434 protected final function setPointerInstance (FilePointer $pointerInstance) {
1435 $this->pointerInstance = $pointerInstance;
1439 * Getter for FilePointer instance
1441 * @return $pointerInstance An instance of an FilePointer class
1443 public final function getPointerInstance () {
1444 return $this->pointerInstance;
1448 * Unsets pointer instance which triggers a call of __destruct() if the
1449 * instance is still there. This is surely not fatal on already "closed"
1450 * file pointer instances.
1452 * I don't want to mess around with above setter by giving it a default
1453 * value NULL as setter should always explicitly only set (existing) object
1454 * instances and NULL is NULL.
1458 protected final function unsetPointerInstance () {
1459 // Simply it to NULL
1460 $this->pointerInstance = NULL;
1464 * Setter for Indexable instance
1466 * @param $indexInstance An instance of an Indexable class
1469 protected final function setIndexInstance (Indexable $indexInstance) {
1470 $this->indexInstance = $indexInstance;
1474 * Getter for Indexable instance
1476 * @return $indexInstance An instance of an Indexable class
1478 public final function getIndexInstance () {
1479 return $this->indexInstance;
1483 * Setter for Block instance
1485 * @param $blockInstance An instance of an Block class
1488 protected final function setBlockInstance (Block $blockInstance) {
1489 $this->blockInstance = $blockInstance;
1493 * Getter for Block instance
1495 * @return $blockInstance An instance of an Block class
1497 public final function getBlockInstance () {
1498 return $this->blockInstance;
1502 * Setter for Minable instance
1504 * @param $minableInstance A Minable instance
1507 protected final function setMinableInstance (Minable $minableInstance) {
1508 $this->minableInstance = $minableInstance;
1512 * Getter for minable instance
1514 * @return $minableInstance A Minable instance
1516 protected final function getMinableInstance () {
1517 return $this->minableInstance;
1521 * Setter for FrameworkDirectory instance
1523 * @param $directoryInstance A FrameworkDirectoryPointer instance
1526 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1527 $this->directoryInstance = $directoryInstance;
1531 * Getter for FrameworkDirectory instance
1533 * @return $directoryInstance A FrameworkDirectory instance
1535 protected final function getDirectoryInstance () {
1536 return $this->directoryInstance;
1540 * Setter for listener instance
1542 * @param $listenerInstance A Listenable instance
1545 protected final function setListenerInstance (Listenable $listenerInstance) {
1546 $this->listenerInstance = $listenerInstance;
1550 * Getter for listener instance
1552 * @return $listenerInstance A Listenable instance
1554 protected final function getListenerInstance () {
1555 return $this->listenerInstance;
1559 * Getter for communicator instance
1561 * @return $communicatorInstance An instance of a Communicator class
1563 public final function getCommunicatorInstance () {
1564 return $this->communicatorInstance;
1568 * Setter for communicator instance
1570 * @param $communicatorInstance An instance of a Communicator class
1573 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1574 $this->communicatorInstance = $communicatorInstance;
1578 * Setter for state instance
1580 * @param $stateInstance A Stateable instance
1583 public final function setStateInstance (Stateable $stateInstance) {
1584 $this->stateInstance = $stateInstance;
1588 * Getter for state instance
1590 * @return $stateInstance A Stateable instance
1592 public final function getStateInstance () {
1593 return $this->stateInstance;
1597 * Setter for output instance
1599 * @param $outputInstance The debug output instance
1602 public final function setOutputInstance (OutputStreamer $outputInstance) {
1603 $this->outputInstance = $outputInstance;
1607 * Getter for output instance
1609 * @return $outputInstance The debug output instance
1611 public final function getOutputInstance () {
1612 return $this->outputInstance;
1616 * Setter for command name
1618 * @param $commandName Last validated command name
1621 protected final function setCommandName ($commandName) {
1622 $this->commandName = $commandName;
1626 * Getter for command name
1628 * @return $commandName Last validated command name
1630 protected final function getCommandName () {
1631 return $this->commandName;
1635 * Setter for controller name
1637 * @param $controllerName Last validated controller name
1640 protected final function setControllerName ($controllerName) {
1641 $this->controllerName = $controllerName;
1645 * Getter for controller name
1647 * @return $controllerName Last validated controller name
1649 protected final function getControllerName () {
1650 return $this->controllerName;
1654 * Getter for protocol name
1656 * @return $protocolName Name of used protocol
1658 public final function getProtocolName () {
1659 return $this->protocolName;
1663 * Setter for protocol name
1665 * @param $protocolName Name of used protocol
1668 protected final function setProtocolName ($protocolName) {
1669 $this->protocolName = $protocolName;
1673 * Checks whether an object equals this object. You should overwrite this
1674 * method to implement own equality checks
1676 * @param $objectInstance An instance of a FrameworkInterface object
1677 * @return $equals Whether both objects equals
1679 public function equals (FrameworkInterface $objectInstance) {
1682 $this->__toString() == $objectInstance->__toString()
1684 $this->hashCode() == $objectInstance->hashCode()
1687 // Return the result
1692 * Generates a generic hash code of this class. You should really overwrite
1693 * this method with your own hash code generator code. But keep KISS in mind.
1695 * @return $hashCode A generic hash code respresenting this whole class
1697 public function hashCode () {
1699 return crc32($this->__toString());
1703 * Formats computer generated price values into human-understandable formats
1704 * with thousand and decimal separators.
1706 * @param $value The in computer format value for a price
1707 * @param $currency The currency symbol (use HTML-valid characters!)
1708 * @param $decNum Number of decimals after commata
1709 * @return $price The for the current language formated price string
1710 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1711 * thousands separator
1714 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1715 // Are all required attriutes set?
1716 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1717 // Throw an exception
1718 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1722 $value = (float) $value;
1724 // Reformat the US number
1725 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1727 // Return as string...
1732 * Appends a trailing slash to a string
1734 * @param $str A string (maybe) without trailing slash
1735 * @return $str A string with an auto-appended trailing slash
1737 public final function addMissingTrailingSlash ($str) {
1738 // Is there a trailing slash?
1739 if (substr($str, -1, 1) != '/') {
1743 // Return string with trailing slash
1748 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1749 * application helper instance (ApplicationHelper by default).
1751 * @param $applicationInstance An application helper instance or
1752 * null if we shall use the default
1753 * @return $templateInstance The template engine instance
1754 * @throws NullPointerException If the discovered application
1755 * instance is still null
1757 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1758 // Is the application instance set?
1759 if (is_null($applicationInstance)) {
1760 // Get the current instance
1761 $applicationInstance = $this->getApplicationInstance();
1764 if (is_null($applicationInstance)) {
1765 // Thrown an exception
1766 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1770 // Initialize the template engine
1771 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1773 // Return the prepared instance
1774 return $templateInstance;
1778 * Debugs this instance by putting out it's full content
1780 * @param $message Optional message to show in debug output
1783 public final function debugInstance ($message = '') {
1784 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1785 restore_error_handler();
1790 // Is a message set?
1791 if (!empty($message)) {
1792 // Construct message
1793 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1796 // Generate the output
1797 $content .= sprintf('<pre>%s</pre>',
1800 print_r($this, TRUE)
1806 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>',
1807 $this->__toString(),
1809 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1814 * Replaces control characters with printable output
1816 * @param $str String with control characters
1817 * @return $str Replaced string
1819 protected function replaceControlCharacters ($str) {
1822 chr(13), '[r]', str_replace(
1823 chr(10), '[n]', str_replace(
1833 * Output a partial stub message for the caller method
1835 * @param $message An optional message to display
1838 protected function partialStub ($message = '') {
1839 // Get the backtrace
1840 $backtrace = debug_backtrace();
1842 // Generate the class::method string
1843 $methodName = 'UnknownClass->unknownMethod';
1844 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1845 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1848 // Construct the full message
1849 $stubMessage = sprintf('[%s:] Partial stub!',
1853 // Is the extra message given?
1854 if (!empty($message)) {
1855 // Then add it as well
1856 $stubMessage .= ' Message: ' . $message;
1859 // Debug instance is there?
1860 if (!is_null($this->getDebugInstance())) {
1861 // Output stub message
1862 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1865 trigger_error($stubMessage);
1871 * Outputs a debug backtrace and stops further script execution
1873 * @param $message An optional message to output
1874 * @param $doExit Whether exit the program (TRUE is default)
1877 public function debugBackTrace ($message = '', $doExit = TRUE) {
1878 // Sorry, there is no other way getting this nice backtrace
1879 if (!empty($message)) {
1881 printf('Message: %s<br />' . PHP_EOL, $message);
1885 debug_print_backtrace();
1889 if ($doExit === TRUE) {
1895 * Creates an instance of a debugger instance
1897 * @param $className Name of the class (currently unsupported)
1898 * @return $debugInstance An instance of a debugger class
1899 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1901 public final static function createDebugInstance ($className) {
1902 // Is the instance set?
1903 if (!Registry::getRegistry()->instanceExists('debug')) {
1904 // Init debug instance
1905 $debugInstance = NULL;
1909 // Get a debugger instance
1910 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1911 } catch (NullPointerException $e) {
1912 // Didn't work, no instance there
1913 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1916 // Empty string should be ignored and used for testing the middleware
1917 DebugMiddleware::getSelfInstance()->output('');
1919 // Set it in its own class. This will set it in the registry
1920 $debugInstance->setDebugInstance($debugInstance);
1922 // Get instance from registry
1923 $debugInstance = Registry::getRegistry()->getDebugInstance();
1927 return $debugInstance;
1931 * Simple output of a message with line-break
1933 * @param $message Message to output
1936 public function outputLine ($message) {
1938 print($message . PHP_EOL);
1942 * Outputs a debug message whether to debug instance (should be set!) or
1943 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1944 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1946 * @param $message Message we shall send out...
1947 * @param $doPrint Whether print or die here (default: print)
1948 * @paran $stripTags Whether to strip tags (default: FALSE)
1951 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1952 // Set debug instance to NULL
1953 $debugInstance = NULL;
1957 // Get debug instance
1958 $debugInstance = $this->getDebugInstance();
1959 } catch (NullPointerException $e) {
1960 // The debug instance is not set (yet)
1963 // Is the debug instance there?
1964 if (is_object($debugInstance)) {
1965 // Use debug output handler
1966 $debugInstance->output($message, $stripTags);
1968 if ($doPrint === FALSE) {
1969 // Die here if not printed
1973 // Are debug times enabled?
1974 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1976 $message = $this->getPrintableExecutionTime() . $message;
1980 if ($doPrint === TRUE) {
1982 $this->outputLine($message);
1991 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1993 * @param $str The string, what ever it is needs to be converted
1994 * @return $className Generated class name
1996 public static final function convertToClassName ($str) {
2000 // Convert all dashes in underscores
2001 $str = self::convertDashesToUnderscores($str);
2003 // Now use that underscores to get classname parts for hungarian style
2004 foreach (explode('_', $str) as $strPart) {
2005 // Make the class name part lower case and first upper case
2006 $className .= ucfirst(strtolower($strPart));
2009 // Return class name
2014 * Converts dashes to underscores, e.g. useable for configuration entries
2016 * @param $str The string with maybe dashes inside
2017 * @return $str The converted string with no dashed, but underscores
2019 public static final function convertDashesToUnderscores ($str) {
2021 $str = str_replace('-', '_', $str);
2023 // Return converted string
2028 * Marks up the code by adding e.g. line numbers
2030 * @param $phpCode Unmarked PHP code
2031 * @return $markedCode Marked PHP code
2033 public function markupCode ($phpCode) {
2038 $errorArray = error_get_last();
2040 // Init the code with error message
2041 if (is_array($errorArray)) {
2043 $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>',
2044 basename($errorArray['file']),
2045 $errorArray['line'],
2046 $errorArray['message'],
2051 // Add line number to the code
2052 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2054 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2056 htmlentities($code, ENT_QUOTES)
2065 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2066 * beatiful for web-based front-ends. If null is given a message id
2067 * null_timestamp will be resolved and returned.
2069 * @param $timestamp Timestamp to prepare (filter) for display
2070 * @return $readable A readable timestamp
2072 public function doFilterFormatTimestamp ($timestamp) {
2073 // Default value to return
2076 // Is the timestamp null?
2077 if (is_null($timestamp)) {
2078 // Get a message string
2079 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2081 switch ($this->getLanguageInstance()->getLanguageCode()) {
2082 case 'de': // German format is a bit different to default
2083 // Split the GMT stamp up
2084 $dateTime = explode(' ', $timestamp );
2085 $dateArray = explode('-', $dateTime[0]);
2086 $timeArray = explode(':', $dateTime[1]);
2088 // Construct the timestamp
2089 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2099 default: // Default is pass-through
2100 $readable = $timestamp;
2110 * Filter a given number into a localized number
2112 * @param $value The raw value from e.g. database
2113 * @return $localized Localized value
2115 public function doFilterFormatNumber ($value) {
2116 // Generate it from config and localize dependencies
2117 switch ($this->getLanguageInstance()->getLanguageCode()) {
2118 case 'de': // German format is a bit different to default
2119 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2122 default: // US, etc.
2123 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2132 * "Getter" for databse entry
2134 * @return $entry An array with database entries
2135 * @throws NullPointerException If the database result is not found
2136 * @throws InvalidDatabaseResultException If the database result is invalid
2138 protected final function getDatabaseEntry () {
2139 // Is there an instance?
2140 if (!$this->getResultInstance() instanceof SearchableResult) {
2141 // Throw an exception here
2142 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2146 $this->getResultInstance()->rewind();
2148 // Do we have an entry?
2149 if ($this->getResultInstance()->valid() === FALSE) {
2150 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2151 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2155 $this->getResultInstance()->next();
2158 $entry = $this->getResultInstance()->current();
2165 * Getter for field name
2167 * @param $fieldName Field name which we shall get
2168 * @return $fieldValue Field value from the user
2169 * @throws NullPointerException If the result instance is null
2171 public final function getField ($fieldName) {
2172 // Default field value
2175 // Get result instance
2176 $resultInstance = $this->getResultInstance();
2178 // Is this instance null?
2179 if (is_null($resultInstance)) {
2180 // Then the user instance is no longer valid (expired cookies?)
2181 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2184 // Get current array
2185 $fieldArray = $resultInstance->current();
2186 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2188 // Convert dashes to underscore
2189 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2191 // Does the field exist?
2192 if ($this->isFieldSet($fieldName)) {
2194 $fieldValue = $fieldArray[$fieldName2];
2195 } elseif (defined('DEVELOPER')) {
2196 // Missing field entry, may require debugging
2197 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2199 // Missing field entry, may require debugging
2200 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2208 * Checks if given field is set
2210 * @param $fieldName Field name to check
2211 * @return $isSet Whether the given field name is set
2212 * @throws NullPointerException If the result instance is null
2214 public function isFieldSet ($fieldName) {
2215 // Get result instance
2216 $resultInstance = $this->getResultInstance();
2218 // Is this instance null?
2219 if (is_null($resultInstance)) {
2220 // Then the user instance is no longer valid (expired cookies?)
2221 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2224 // Get current array
2225 $fieldArray = $resultInstance->current();
2226 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2228 // Convert dashes to underscore
2229 $fieldName = self::convertDashesToUnderscores($fieldName);
2232 $isSet = isset($fieldArray[$fieldName]);
2239 * Flushs all pending updates to the database layer
2243 public function flushPendingUpdates () {
2244 // Get result instance
2245 $resultInstance = $this->getResultInstance();
2247 // Do we have data to update?
2248 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2249 // Get wrapper class name config entry
2250 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2252 // Create object instance
2253 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2255 // Yes, then send the whole result to the database layer
2256 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2261 * Outputs a deprecation warning to the developer.
2263 * @param $message The message we shall output to the developer
2265 * @todo Write a logging mechanism for productive mode
2267 public function deprecationWarning ($message) {
2268 // Is developer mode active?
2269 if (defined('DEVELOPER')) {
2270 // Debug instance is there?
2271 if (!is_null($this->getDebugInstance())) {
2272 // Output stub message
2273 self::createDebugInstance(__CLASS__)->debugOutput($message);
2276 trigger_error($message . "<br />\n");
2280 // @TODO Finish this part!
2281 $this->partialStub('Developer mode inactive. Message:' . $message);
2286 * Checks whether the given PHP extension is loaded
2288 * @param $phpExtension The PHP extension we shall check
2289 * @return $isLoaded Whether the PHP extension is loaded
2291 public final function isPhpExtensionLoaded ($phpExtension) {
2293 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2300 * "Getter" as a time() replacement but with milliseconds. You should use this
2301 * method instead of the encapsulated getimeofday() function.
2303 * @return $milliTime Timestamp with milliseconds
2305 public function getMilliTime () {
2306 // Get the time of day as float
2307 $milliTime = gettimeofday(TRUE);
2314 * Idles (sleeps) for given milliseconds
2316 * @return $hasSlept Whether it goes fine
2318 public function idle ($milliSeconds) {
2319 // Sleep is fine by default
2322 // Idle so long with found function
2323 if (function_exists('time_sleep_until')) {
2324 // Get current time and add idle time
2325 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2327 // New PHP 5.1.0 function found, ignore errors
2328 $hasSlept = @time_sleep_until($sleepUntil);
2331 * My Sun station doesn't have that function even with latest PHP
2334 usleep($milliSeconds * 1000);
2341 * Converts a hexadecimal string, even with negative sign as first string to
2342 * a decimal number using BC functions.
2344 * This work is based on comment #86673 on php.net documentation page at:
2345 * <http://de.php.net/manual/en/function.dechex.php#86673>
2347 * @param $hex Hexadecimal string
2348 * @return $dec Decimal number
2350 protected function hex2dec ($hex) {
2351 // Convert to all lower-case
2352 $hex = strtolower($hex);
2354 // Detect sign (negative/positive numbers)
2356 if (substr($hex, 0, 1) == '-') {
2358 $hex = substr($hex, 1);
2361 // Decode the hexadecimal string into a decimal number
2363 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2364 $factor = self::$hexdec[substr($hex, $i, 1)];
2365 $dec = bcadd($dec, bcmul($factor, $e));
2368 // Return the decimal number
2369 return $sign . $dec;
2373 * Converts even very large decimal numbers, also signed, to a hexadecimal
2376 * This work is based on comment #97756 on php.net documentation page at:
2377 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2379 * @param $dec Decimal number, even with negative sign
2380 * @param $maxLength Optional maximum length of the string
2381 * @return $hex Hexadecimal string
2383 protected function dec2hex ($dec, $maxLength = 0) {
2384 // maxLength can be zero or devideable by 2
2385 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2387 // Detect sign (negative/positive numbers)
2394 // Encode the decimal number into a hexadecimal string
2397 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2399 } while ($dec >= 1);
2402 * Leading zeros are required for hex-decimal "numbers". In some
2403 * situations more leading zeros are wanted, so check for both
2406 if ($maxLength > 0) {
2407 // Prepend more zeros
2408 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2409 } elseif ((strlen($hex) % 2) != 0) {
2410 // Only make string's length dividable by 2
2414 // Return the hexadecimal string
2415 return $sign . $hex;
2419 * Converts a ASCII string (0 to 255) into a decimal number.
2421 * @param $asc The ASCII string to be converted
2422 * @return $dec Decimal number
2424 protected function asc2dec ($asc) {
2425 // Convert it into a hexadecimal number
2426 $hex = bin2hex($asc);
2428 // And back into a decimal number
2429 $dec = $this->hex2dec($hex);
2436 * Converts a decimal number into an ASCII string.
2438 * @param $dec Decimal number
2439 * @return $asc An ASCII string
2441 protected function dec2asc ($dec) {
2442 // First convert the number into a hexadecimal string
2443 $hex = $this->dec2hex($dec);
2445 // Then convert it into the ASCII string
2446 $asc = $this->hex2asc($hex);
2453 * Converts a hexadecimal number into an ASCII string. Negative numbers
2456 * @param $hex Hexadecimal string
2457 * @return $asc An ASCII string
2459 protected function hex2asc ($hex) {
2460 // Check for length, it must be devideable by 2
2461 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2462 assert((strlen($hex) % 2) == 0);
2466 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2467 // Get the decimal number of the chunk
2468 $part = hexdec(substr($hex, $idx, 2));
2470 // Add it to the final string
2474 // Return the final string
2479 * Checks whether the given encoded data was encoded with Base64
2481 * @param $encodedData Encoded data we shall check
2482 * @return $isBase64 Whether the encoded data is Base64
2484 protected function isBase64Encoded ($encodedData) {
2486 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2493 * "Getter" to get response/request type from analysis of the system.
2495 * @return $responseType Analyzed response type
2497 protected static function getResponseTypeFromSystem () {
2498 // Default is console
2499 $responseType = 'console';
2501 // Is 'HTTP_HOST' set?
2502 if (isset($_SERVER['HTTP_HOST'])) {
2504 * Then it is a HTML response/request as RSS and so on may be
2505 * transfered over HTTP as well.
2507 $responseType = 'html';
2511 return $responseType;
2515 * Gets a cache key from Criteria instance
2517 * @param $criteriaInstance An instance of a Criteria class
2518 * @param $onlyKeys Only use these keys for a cache key
2519 * @return $cacheKey A cache key suitable for lookup/storage purposes
2521 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2523 $cacheKey = sprintf('%s@%s',
2524 $this->__toString(),
2525 $criteriaInstance->getCacheKey($onlyKeys)
2529 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2534 * Getter for startup time in miliseconds
2536 * @return $startupTime Startup time in miliseconds
2538 protected function getStartupTime () {
2539 return self::$startupTime;
2543 * "Getter" for a printable currently execution time in nice braces
2545 * @return $executionTime Current execution time in nice braces
2547 protected function getPrintableExecutionTime () {
2548 // Caculate the execution time
2549 $executionTime = microtime(TRUE) - $this->getStartupTime();
2551 // Pack it in nice braces
2552 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2555 return $executionTime;
2559 * Hashes a given string with a simple but stronger hash function (no salt)
2560 * and hex-encode it.
2562 * @param $str The string to be hashed
2563 * @return $hash The hash from string $str
2565 public static final function hash ($str) {
2566 // Hash given string with (better secure) hasher
2567 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2574 * "Getter" for length of hash() output. This will be "cached" to speed up
2577 * @return $length Length of hash() output
2579 public static final function getHashLength () {
2581 if (is_null(self::$hashLength)) {
2582 // No, then hash a string and save its length.
2583 self::$hashLength = strlen(self::hash('abc123'));
2587 return self::$hashLength;
2591 * Checks whether the given number is really a number (only chars 0-9).
2593 * @param $num A string consisting only chars between 0 and 9
2594 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2595 * @param $assertMismatch Whether to assert mismatches
2596 * @return $ret The (hopefully) secured numbered value
2598 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2599 // Filter all numbers out
2600 $ret = preg_replace('/[^0123456789]/', '', $num);
2603 if ($castValue === TRUE) {
2604 // Cast to biggest numeric type
2605 $ret = (double) $ret;
2608 // Assert only if requested
2609 if ($assertMismatch === TRUE) {
2610 // Has the whole value changed?
2611 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2619 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2621 * @param $num A string consisting only chars between 0 and 9
2622 * @param $assertMismatch Whether to assert mismatches
2623 * @return $ret The (hopefully) secured hext-numbered value
2625 public function hexval ($num, $assertMismatch = FALSE) {
2626 // Filter all numbers out
2627 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2629 // Assert only if requested
2630 if ($assertMismatch === TRUE) {
2631 // Has the whole value changed?
2632 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2640 * Checks whether start/end marker are set
2642 * @param $data Data to be checked
2643 * @return $isset Whether start/end marker are set
2645 public final function ifStartEndMarkersSet ($data) {
2647 $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));
2649 // ... and return it
2654 * Determines if an element is set in the generic array
2656 * @param $keyGroup Main group for the key
2657 * @param $subGroup Sub group for the key
2658 * @param $key Key to check
2659 * @param $element Element to check
2660 * @return $isset Whether the given key is set
2662 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2664 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2667 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2673 * Determines if a key is set in the generic array
2675 * @param $keyGroup Main group for the key
2676 * @param $subGroup Sub group for the key
2677 * @param $key Key to check
2678 * @return $isset Whether the given key is set
2680 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2682 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2685 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2693 * Determines if a group is set in the generic array
2695 * @param $keyGroup Main group
2696 * @param $subGroup Sub group
2697 * @return $isset Whether the given group is set
2699 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2701 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2704 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2711 * Getter for sub key group
2713 * @param $keyGroup Main key group
2714 * @param $subGroup Sub key group
2715 * @return $array An array with all array elements
2717 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2719 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2720 // No, then abort here
2721 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2726 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2729 return $this->genericArray[$keyGroup][$subGroup];
2733 * Unsets a given key in generic array
2735 * @param $keyGroup Main group for the key
2736 * @param $subGroup Sub group for the key
2737 * @param $key Key to unset
2740 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2742 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2745 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2749 * Unsets a given element in generic array
2751 * @param $keyGroup Main group for the key
2752 * @param $subGroup Sub group for the key
2753 * @param $key Key to unset
2754 * @param $element Element to unset
2757 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2759 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2762 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2766 * Append a string to a given generic array key
2768 * @param $keyGroup Main group for the key
2769 * @param $subGroup Sub group for the key
2770 * @param $key Key to unset
2771 * @param $value Value to add/append
2774 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2776 //* 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);
2778 // Is it already there?
2779 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2781 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2784 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2789 * Append a string to a given generic array element
2791 * @param $keyGroup Main group for the key
2792 * @param $subGroup Sub group for the key
2793 * @param $key Key to unset
2794 * @param $element Element to check
2795 * @param $value Value to add/append
2798 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2800 //* 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);
2802 // Is it already there?
2803 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2805 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2808 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2813 * Sets a string in a given generic array element
2815 * @param $keyGroup Main group for the key
2816 * @param $subGroup Sub group for the key
2817 * @param $key Key to unset
2818 * @param $element Element to check
2819 * @param $value Value to add/append
2822 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2824 //* 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);
2827 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2831 * Initializes given generic array group
2833 * @param $keyGroup Main group for the key
2834 * @param $subGroup Sub group for the key
2835 * @param $key Key to use
2836 * @param $forceInit Optionally force initialization
2839 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2841 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2843 // Is it already set?
2844 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2845 // Already initialized
2846 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2851 $this->genericArray[$keyGroup][$subGroup] = array();
2855 * Initializes given generic array key
2857 * @param $keyGroup Main group for the key
2858 * @param $subGroup Sub group for the key
2859 * @param $key Key to use
2860 * @param $forceInit Optionally force initialization
2863 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2865 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2867 // Is it already set?
2868 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2869 // Already initialized
2870 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2875 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2879 * Initializes given generic array element
2881 * @param $keyGroup Main group for the key
2882 * @param $subGroup Sub group for the key
2883 * @param $key Key to use
2884 * @param $element Element to use
2885 * @param $forceInit Optionally force initialization
2888 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2890 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2892 // Is it already set?
2893 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2894 // Already initialized
2895 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2900 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2904 * Pushes an element to a generic key
2906 * @param $keyGroup Main group for the key
2907 * @param $subGroup Sub group for the key
2908 * @param $key Key to use
2909 * @param $value Value to add/append
2910 * @return $count Number of array elements
2912 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2914 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2917 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2919 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2923 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2926 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2927 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2932 * Pushes an element to a generic array element
2934 * @param $keyGroup Main group for the key
2935 * @param $subGroup Sub group for the key
2936 * @param $key Key to use
2937 * @param $element Element to check
2938 * @param $value Value to add/append
2939 * @return $count Number of array elements
2941 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2943 //* 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));
2946 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2948 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2952 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2955 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2956 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2961 * Pops an element from a generic group
2963 * @param $keyGroup Main group for the key
2964 * @param $subGroup Sub group for the key
2965 * @param $key Key to unset
2966 * @return $value Last "popped" value
2968 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2970 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2973 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2975 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2980 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2983 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2984 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2989 * Shifts an element from a generic group
2991 * @param $keyGroup Main group for the key
2992 * @param $subGroup Sub group for the key
2993 * @param $key Key to unset
2994 * @return $value Last "popped" value
2996 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2998 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3001 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3003 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3008 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3011 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3012 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3017 * Count generic array group
3019 * @param $keyGroup Main group for the key
3020 * @return $count Count of given group
3022 protected final function countGenericArray ($keyGroup) {
3024 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3027 if (!isset($this->genericArray[$keyGroup])) {
3029 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3034 $count = count($this->genericArray[$keyGroup]);
3037 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3044 * Count generic array sub group
3046 * @param $keyGroup Main group for the key
3047 * @param $subGroup Sub group for the key
3048 * @return $count Count of given group
3050 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3052 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3055 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3057 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3062 $count = count($this->genericArray[$keyGroup][$subGroup]);
3065 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3072 * Count generic array elements
3074 * @param $keyGroup Main group for the key
3075 * @param $subGroup Sub group for the key
3076 * @para $key Key to count
3077 * @return $count Count of given key
3079 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3081 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3084 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3086 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3088 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3090 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3095 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3098 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3105 * Getter for whole generic group array
3107 * @param $keyGroup Key group to get
3108 * @return $array Whole generic array group
3110 protected final function getGenericArray ($keyGroup) {
3112 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3115 if (!isset($this->genericArray[$keyGroup])) {
3117 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3122 return $this->genericArray[$keyGroup];
3126 * Setter for generic array key
3128 * @param $keyGroup Key group to get
3129 * @param $subGroup Sub group for the key
3130 * @param $key Key to unset
3131 * @param $value Mixed value from generic array element
3134 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3136 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3139 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3143 * Getter for generic array key
3145 * @param $keyGroup Key group to get
3146 * @param $subGroup Sub group for the key
3147 * @param $key Key to unset
3148 * @return $value Mixed value from generic array element
3150 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3152 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3155 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3157 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3162 return $this->genericArray[$keyGroup][$subGroup][$key];
3166 * Sets a value in given generic array key/element
3168 * @param $keyGroup Main group for the key
3169 * @param $subGroup Sub group for the key
3170 * @param $key Key to set
3171 * @param $element Element to set
3172 * @param $value Value to set
3175 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3177 //* 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));
3180 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3184 * Getter for generic array element
3186 * @param $keyGroup Key group to get
3187 * @param $subGroup Sub group for the key
3188 * @param $key Key to look for
3189 * @param $element Element to look for
3190 * @return $value Mixed value from generic array element
3192 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3194 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3197 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3199 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3204 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3208 * Checks if a given sub group is valid (array)
3210 * @param $keyGroup Key group to get
3211 * @param $subGroup Sub group for the key
3212 * @return $isValid Whether given sub group is valid
3214 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3216 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3219 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3226 * Checks if a given key is valid (array)
3228 * @param $keyGroup Key group to get
3229 * @param $subGroup Sub group for the key
3230 * @param $key Key to check
3231 * @return $isValid Whether given sub group is valid
3233 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3235 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3238 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3245 * Initializes the web output instance
3249 protected function initWebOutputInstance () {
3250 // Get application instance
3251 $applicationInstance = Registry::getRegistry()->getInstance('app');
3253 // Is this a response instance?
3254 if ($this instanceof Responseable) {
3255 // Then set it in application instance
3256 $applicationInstance->setResponseInstance($this);
3259 // Init web output instance
3260 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3263 $this->setWebOutputInstance($outputInstance);
3267 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3269 * @param $boolean Boolean value
3270 * @return $translated Translated boolean value
3272 public static final function translateBooleanToYesNo ($boolean) {
3273 // Make sure it is really boolean
3274 assert(is_bool($boolean));
3277 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3279 // ... and return it
3284 * Encodes raw data (almost any type) by "serializing" it and then pack it
3285 * into a "binary format".
3287 * @param $rawData Raw data (almost any type)
3288 * @return $encoded Encoded data
3290 protected function encodeData ($rawData) {
3291 // Make sure no objects or resources pass through
3292 assert(!is_object($rawData));
3293 assert(!is_resource($rawData));
3295 // First "serialize" it (json_encode() is faster than serialize())
3296 $encoded = $this->packString(json_encode($rawData));
3303 * Pack a string into a "binary format". Please execuse me that this is
3304 * widely undocumented. :-(
3306 * @param $str Unpacked string
3307 * @return $packed Packed string
3308 * @todo Improve documentation
3310 protected function packString ($str) {
3312 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3314 // First compress the string (gzcompress is okay)
3315 $str = gzcompress($str);
3320 // And start the "encoding" loop
3321 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3323 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3324 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3326 if (($idx + $i) <= strlen($str)) {
3327 $ord = ord(substr($str, ($idx + $i), 1));
3329 $add = $ord * pow(256, $factor);
3333 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3337 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3338 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3340 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3341 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3347 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');
3352 * Checks whether the given file/path is in open_basedir(). This does not
3353 * gurantee that the file is actually readable and/or writeable. If you need
3354 * such gurantee then please use isReadableFile() instead.
3356 * @param $filePathName Name of the file/path to be checked
3357 * @return $isReachable Whether it is within open_basedir()
3359 protected static function isReachableFilePath ($filePathName) {
3360 // Is not reachable by default
3361 $isReachable = FALSE;
3363 // Get open_basedir parameter
3364 $openBaseDir = ini_get('open_basedir');
3367 if (!empty($openBaseDir)) {
3368 // Check all entries
3369 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3370 // Check on existence
3371 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3373 $isReachable = TRUE;
3377 // If open_basedir is not set, all is allowed
3378 $isReachable = TRUE;
3382 return $isReachable;
3386 * Checks whether the give file is within open_basedir() (done by
3387 * isReachableFilePath()), is actually a file and is readable.
3389 * @param $fileName Name of the file to be checked
3390 * @return $isReadable Whether the file is readable (and therefor exists)
3392 public static function isReadableFile ($fileName) {
3393 // Default is not readable
3394 $isReadable = FALSE;
3396 // Is within parameters, so check if it is a file and readable
3397 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3404 * Creates a full-qualified file name (FQFN) for given file name by adding
3405 * a configured temporary file path to it.
3407 * @param $fileName Name for temporary file
3408 * @return $fqfn Full-qualified file name
3409 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3410 * @throws FileIoException If the file cannot be written
3412 protected static function createTempPathForFile ($fileName) {
3414 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3416 // Is the path writeable?
3417 if (!is_writable($basePath)) {
3418 // Path is write-protected
3419 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3423 $fqfn = $basePath . '/' . $fileName;
3426 if (!self::isReachableFilePath($fqfn)) {
3428 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3436 * "Getter" for a printable state name
3438 * @return $stateName Name of the node's state in a printable format
3440 public final function getPrintableState () {
3441 // Default is 'null'
3442 $stateName = 'null';
3444 // Get the state instance
3445 $stateInstance = $this->getStateInstance();
3447 // Is it an instance of Stateable?
3448 if ($stateInstance instanceof Stateable) {
3449 // Then use that state name
3450 $stateName = $stateInstance->getStateName();
3458 * Handles socket error for given socket resource and peer data. This method
3459 * validates $socketResource if it is a valid resource (see is_resource())
3460 * but assumes valid data in array $recipientData, except that
3461 * count($recipientData) is always 2.
3463 * @param $method Value of __METHOD__ from calling method
3464 * @param $line Value of __LINE__ from calling method
3465 * @param $socketResource A valid socket resource
3466 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3468 * @throws InvalidSocketException If $socketResource is no socket resource
3469 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3470 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3472 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3473 // This method handles only socket resources
3474 if (!is_resource($socketResource)) {
3475 // No resource, abort here
3476 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3479 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3480 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3481 assert(isset($socketData[0]));
3482 assert(isset($socketData[1]));
3484 // Get error code for first validation (0 is not an error)
3485 $errorCode = socket_last_error($socketResource);
3487 // If the error code is zero, someone called this method without an error
3488 if ($errorCode == 0) {
3489 // No error detected (or previously cleared outside this method)
3490 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3493 // Get handler (method) name
3494 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3496 // Call-back the error handler method
3497 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3499 // Finally clear the error because it has been handled
3500 socket_clear_error($socketResource);