3 * The simulator system class is the super class of all other classes. This
4 * class handles saving of games etc.
6 * @author Roland Haeder <webmaster@shipsimu.org>
8 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
9 * @license GNU GPL 3.0 or any newer version
10 * @link http://www.shipsimu.org
12 * This program is free software: you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation, either version 3 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
27 * Length of output from hash()
29 private static $hashLength = NULL;
34 private $realClass = 'BaseFrameworkSystem';
37 * Instance of a request class
39 private $requestInstance = NULL;
42 * Instance of a response class
44 private $responseInstance = NULL;
47 * Search criteria instance
49 private $searchInstance = NULL;
52 * Update criteria instance
54 private $updateInstance = NULL;
57 * The file I/O instance for the template loader
59 private $fileIoInstance = NULL;
64 private $resolverInstance = NULL;
67 * Template engine instance
69 private $templateInstance = NULL;
72 * Database result instance
74 private $resultInstance = NULL;
77 * Instance for user class
79 private $userInstance = NULL;
82 * A controller instance
84 private $controllerInstance = NULL;
89 private $rngInstance = NULL;
92 * Instance of a crypto helper
94 private $cryptoInstance = NULL;
97 * Instance of an Iterator class
99 private $iteratorInstance = NULL;
102 * Instance of the list
104 private $listInstance = NULL;
109 private $menuInstance = NULL;
112 * Instance of the image
114 private $imageInstance = NULL;
117 * Instance of the stacker
119 private $stackInstance = NULL;
122 * A Compressor instance
124 private $compressorInstance = NULL;
127 * A Parseable instance
129 private $parserInstance = NULL;
132 * A HandleableProtocol instance
134 private $protocolInstance = NULL;
137 * A database wrapper instance
139 private $databaseInstance = NULL;
142 * A helper instance for the form
144 private $helperInstance = NULL;
147 * An instance of a Source class
149 private $sourceInstance = NULL;
152 * An instance of a UrlSource class
154 private $urlSourceInstance = NULL;
157 * An instance of a InputStream class
159 private $inputStreamInstance = NULL;
162 * An instance of a OutputStream class
164 private $outputStreamInstance = NULL;
167 * Networkable handler instance
169 private $handlerInstance = NULL;
172 * Visitor handler instance
174 private $visitorInstance = NULL;
179 private $dhtInstance = NULL;
182 * An instance of a database wrapper class
184 private $wrapperInstance = NULL;
187 * An instance of a file I/O pointer class (not handler)
189 private $pointerInstance = NULL;
192 * An instance of an Indexable class
194 private $indexInstance = NULL;
197 * An instance of a Block class
199 private $blockInstance = NULL;
204 private $minableInstance = NULL;
207 * A FrameworkDirectory instance
209 private $directoryInstance = NULL;
214 private $listenerInstance = NULL;
217 * An instance of a communicator
219 private $communicatorInstance = NULL;
222 * The concrete output instance
224 private $outputInstance = NULL;
229 private $stateInstance = NULL;
232 * Thousands separator
234 private $thousands = '.'; // German
239 private $decimals = ','; // German
244 private $socketResource = FALSE;
247 * Regular expression to use for validation
249 private $regularExpression = '';
254 private $packageData = array();
259 private $genericArray = array();
264 private $commandName = '';
269 private $controllerName = '';
272 * Name of used protocol
274 private $protocolName = 'invalid';
277 * Array with bitmasks and such for pack/unpack methods to support both
278 * 32-bit and 64-bit systems
280 private $packingData = array(
283 'left' => 0xffff0000,
284 'right' => 0x0000ffff,
290 'left' => 0xffffffff00000000,
291 'right' => 0x00000000ffffffff,
298 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
300 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
302 private $archArrayElement = FALSE;
304 /***********************
305 * Exception codes.... *
306 ***********************/
308 // @todo Try to clean these constants up
309 const EXCEPTION_IS_NULL_POINTER = 0x001;
310 const EXCEPTION_IS_NO_OBJECT = 0x002;
311 const EXCEPTION_IS_NO_ARRAY = 0x003;
312 const EXCEPTION_MISSING_METHOD = 0x004;
313 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
314 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
315 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
316 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
317 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
318 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
319 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
320 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
321 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
322 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
323 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
324 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
325 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
326 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
327 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
328 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
329 const EXCEPTION_PATH_NOT_FOUND = 0x015;
330 const EXCEPTION_INVALID_PATH_NAME = 0x016;
331 const EXCEPTION_READ_PROTECED_PATH = 0x017;
332 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
333 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
334 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
335 const EXCEPTION_INVALID_RESOURCE = 0x01b;
336 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
337 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
338 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
339 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
340 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
341 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
342 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
343 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
344 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
345 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
346 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
347 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
348 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
349 const EXCEPTION_INVALID_STRING = 0x029;
350 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
351 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
352 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
353 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
354 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
355 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
356 const EXCEPTION_MISSING_ELEMENT = 0x030;
357 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
358 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
359 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
360 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
361 const EXCEPTION_FATAL_ERROR = 0x035;
362 const EXCEPTION_FILE_NOT_FOUND = 0x036;
363 const EXCEPTION_ASSERTION_FAILED = 0x037;
364 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
365 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
366 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
367 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
368 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
369 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
372 * Hexadecimal->Decimal translation array
374 private static $hexdec = array(
394 * Decimal->hexadecimal translation array
396 private static $dechex = array(
416 * Startup time in miliseconds
418 private static $startupTime = 0;
421 * Protected super constructor
423 * @param $className Name of the class
426 protected function __construct ($className) {
428 $this->setRealClass($className);
430 // Set configuration instance if no registry ...
431 if (!$this instanceof Register) {
432 // ... because registries doesn't need to be configured
433 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
436 // Is the startup time set? (0 cannot be TRUE anymore)
437 if (self::$startupTime == 0) {
439 self::$startupTime = microtime(TRUE);
443 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
447 * Destructor for all classes. You should not call this method on your own.
451 public function __destruct () {
452 // Flush any updated entries to the database
453 $this->flushPendingUpdates();
455 // Is this object already destroyed?
456 if ($this->__toString() != 'DestructedObject') {
457 // Destroy all informations about this class but keep some text about it alive
458 $this->setRealClass('DestructedObject');
459 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
460 // Already destructed object
461 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
466 // Do not call this twice
467 trigger_error(__METHOD__ . ': Called twice.');
473 * The __call() method where all non-implemented methods end up
475 * @param $methodName Name of the missing method
476 * @args $args Arguments passed to the method
479 public final function __call ($methodName, $args) {
480 return self::__callStatic($methodName, $args);
484 * The __callStatic() method where all non-implemented static methods end up
486 * @param $methodName Name of the missing method
487 * @args $args Arguments passed to the method
490 public static final function __callStatic ($methodName, $args) {
491 // Init argument string
494 // Is it NULL, empty or an array?
495 if (is_null($args)) {
497 $argsString = 'NULL';
498 } elseif (is_array($args)) {
502 // Some arguments are there
503 foreach ($args as $arg) {
504 // Add data about the argument
505 $argsString .= gettype($arg) . ':';
508 // Found a NULL argument
509 $argsString .= 'NULL';
510 } elseif (is_string($arg)) {
511 // Add length for strings
512 $argsString .= strlen($arg);
513 } elseif ((is_int($arg)) || (is_float($arg))) {
516 } elseif (is_array($arg)) {
517 // .. or size if array
518 $argsString .= count($arg);
519 } elseif (is_object($arg)) {
521 $reflection = new ReflectionClass($arg);
523 // Is an other object, maybe no __toString() available
524 $argsString .= $reflection->getName();
525 } elseif ($arg === TRUE) {
526 // ... is boolean 'TRUE'
527 $argsString .= 'TRUE';
528 } elseif ($arg === FALSE) {
529 // ... is boolean 'FALSE'
530 $argsString .= 'FALSE';
533 // Comma for next one
538 if (substr($argsString, -2, 1) == ',') {
539 $argsString = substr($argsString, 0, -2);
545 // Invalid arguments!
546 $argsString = '!INVALID:' . gettype($args) . '!';
549 // Output stub message
550 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
551 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
561 * Getter for $realClass
563 * @return $realClass The name of the real class (not BaseFrameworkSystem)
565 public function __toString () {
566 return $this->realClass;
570 * Magic method to catch setting of missing but set class fields/attributes
572 * @param $name Name of the field/attribute
573 * @param $value Value to store
576 public final function __set ($name, $value) {
577 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
580 print_r($value, TRUE)
585 * Magic method to catch getting of missing fields/attributes
587 * @param $name Name of the field/attribute
590 public final function __get ($name) {
591 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
597 * Magic method to catch unsetting of missing fields/attributes
599 * @param $name Name of the field/attribute
602 public final function __unset ($name) {
603 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
609 * Magic method to catch object serialization
611 * @return $unsupported Unsupported method
612 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
614 public final function __sleep () {
615 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
619 * Magic method to catch object deserialization
621 * @return $unsupported Unsupported method
622 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
624 public final function __wakeup () {
625 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
629 * Magic method to catch calls when an object instance is called
631 * @return $unsupported Unsupported method
632 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
634 public final function __invoke () {
635 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
639 * Setter for the real class name
641 * @param $realClass Class name (string)
644 public final function setRealClass ($realClass) {
646 $this->realClass = (string) $realClass;
650 * Setter for database result instance
652 * @param $resultInstance An instance of a database result class
654 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
656 protected final function setResultInstance (SearchableResult $resultInstance) {
657 $this->resultInstance = $resultInstance;
661 * Getter for database result instance
663 * @return $resultInstance An instance of a database result class
665 public final function getResultInstance () {
666 return $this->resultInstance;
670 * Setter for template engine instances
672 * @param $templateInstance An instance of a template engine class
675 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
676 $this->templateInstance = $templateInstance;
680 * Getter for template engine instances
682 * @return $templateInstance An instance of a template engine class
684 protected final function getTemplateInstance () {
685 return $this->templateInstance;
689 * Setter for search instance
691 * @param $searchInstance Searchable criteria instance
694 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
695 $this->searchInstance = $searchInstance;
699 * Getter for search instance
701 * @return $searchInstance Searchable criteria instance
703 public final function getSearchInstance () {
704 return $this->searchInstance;
708 * Setter for update instance
710 * @param $updateInstance Searchable criteria instance
713 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
714 $this->updateInstance = $updateInstance;
718 * Getter for update instance
720 * @return $updateInstance Updateable criteria instance
722 public final function getUpdateInstance () {
723 return $this->updateInstance;
727 * Setter for resolver instance
729 * @param $resolverInstance Instance of a command resolver class
732 public final function setResolverInstance (Resolver $resolverInstance) {
733 $this->resolverInstance = $resolverInstance;
737 * Getter for resolver instance
739 * @return $resolverInstance Instance of a command resolver class
741 public final function getResolverInstance () {
742 return $this->resolverInstance;
746 * Setter for language instance
748 * @param $configInstance The configuration instance which shall
749 * be FrameworkConfiguration
752 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
753 Registry::getRegistry()->addInstance('config', $configInstance);
757 * Getter for configuration instance
759 * @return $configInstance Configuration instance
761 public final function getConfigInstance () {
762 $configInstance = Registry::getRegistry()->getInstance('config');
763 return $configInstance;
767 * Setter for debug instance
769 * @param $debugInstance The instance for debug output class
772 public final function setDebugInstance (DebugMiddleware $debugInstance) {
773 Registry::getRegistry()->addInstance('debug', $debugInstance);
777 * Getter for debug instance
779 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
781 public final function getDebugInstance () {
782 // Get debug instance
783 $debugInstance = Registry::getRegistry()->getInstance('debug');
786 return $debugInstance;
790 * Setter for web output instance
792 * @param $webInstance The instance for web output class
795 public final function setWebOutputInstance (OutputStreamer $webInstance) {
796 Registry::getRegistry()->addInstance('web_output', $webInstance);
800 * Getter for web output instance
802 * @return $webOutputInstance - Instance to class WebOutput
804 public final function getWebOutputInstance () {
805 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
806 return $webOutputInstance;
810 * Setter for database instance
812 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
815 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
816 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
820 * Getter for database layer
822 * @return $databaseInstance The database layer instance
824 public final function getDatabaseInstance () {
826 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
829 return $databaseInstance;
833 * Setter for compressor channel
835 * @param $compressorInstance An instance of CompressorChannel
838 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
839 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
843 * Getter for compressor channel
845 * @return $compressorInstance The compressor channel
847 public final function getCompressorChannel () {
848 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
849 return $compressorInstance;
853 * Protected getter for a manageable application helper class
855 * @return $applicationInstance An instance of a manageable application helper class
857 protected final function getApplicationInstance () {
858 $applicationInstance = Registry::getRegistry()->getInstance('application');
859 return $applicationInstance;
863 * Setter for a manageable application helper class
865 * @param $applicationInstance An instance of a manageable application helper class
868 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
869 Registry::getRegistry()->addInstance('application', $applicationInstance);
873 * Setter for request instance
875 * @param $requestInstance An instance of a Requestable class
878 public final function setRequestInstance (Requestable $requestInstance) {
879 $this->requestInstance = $requestInstance;
883 * Getter for request instance
885 * @return $requestInstance An instance of a Requestable class
887 public final function getRequestInstance () {
888 return $this->requestInstance;
892 * Setter for response instance
894 * @param $responseInstance An instance of a Responseable class
897 public final function setResponseInstance (Responseable $responseInstance) {
898 $this->responseInstance = $responseInstance;
902 * Getter for response instance
904 * @return $responseInstance An instance of a Responseable class
906 public final function getResponseInstance () {
907 return $this->responseInstance;
911 * Private getter for language instance
913 * @return $langInstance An instance to the language sub-system
915 protected final function getLanguageInstance () {
916 $langInstance = Registry::getRegistry()->getInstance('language');
917 return $langInstance;
921 * Setter for language instance
923 * @param $langInstance An instance to the language sub-system
925 * @see LanguageSystem
927 public final function setLanguageInstance (ManageableLanguage $langInstance) {
928 Registry::getRegistry()->addInstance('language', $langInstance);
932 * Private getter for file IO instance
934 * @return $fileIoInstance An instance to the file I/O sub-system
936 protected final function getFileIoInstance () {
937 return $this->fileIoInstance;
941 * Setter for file I/O instance
943 * @param $fileIoInstance An instance to the file I/O sub-system
946 public final function setFileIoInstance (IoHandler $fileIoInstance) {
947 $this->fileIoInstance = $fileIoInstance;
951 * Protected setter for user instance
953 * @param $userInstance An instance of a user class
956 protected final function setUserInstance (ManageableAccount $userInstance) {
957 $this->userInstance = $userInstance;
961 * Getter for user instance
963 * @return $userInstance An instance of a user class
965 public final function getUserInstance () {
966 return $this->userInstance;
970 * Setter for controller instance (this surely breaks a bit the MVC patterm)
972 * @param $controllerInstance An instance of the controller
975 public final function setControllerInstance (Controller $controllerInstance) {
976 $this->controllerInstance = $controllerInstance;
980 * Getter for controller instance (this surely breaks a bit the MVC patterm)
982 * @return $controllerInstance An instance of the controller
984 public final function getControllerInstance () {
985 return $this->controllerInstance;
989 * Setter for RNG instance
991 * @param $rngInstance An instance of a random number generator (RNG)
994 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
995 $this->rngInstance = $rngInstance;
999 * Getter for RNG instance
1001 * @return $rngInstance An instance of a random number generator (RNG)
1003 public final function getRngInstance () {
1004 return $this->rngInstance;
1008 * Setter for Cryptable instance
1010 * @param $cryptoInstance An instance of a Cryptable class
1013 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1014 $this->cryptoInstance = $cryptoInstance;
1018 * Getter for Cryptable instance
1020 * @return $cryptoInstance An instance of a Cryptable class
1022 public final function getCryptoInstance () {
1023 return $this->cryptoInstance;
1027 * Setter for the list instance
1029 * @param $listInstance A list of Listable
1032 protected final function setListInstance (Listable $listInstance) {
1033 $this->listInstance = $listInstance;
1037 * Getter for the list instance
1039 * @return $listInstance A list of Listable
1041 protected final function getListInstance () {
1042 return $this->listInstance;
1046 * Setter for the menu instance
1048 * @param $menuInstance A RenderableMenu instance
1051 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1052 $this->menuInstance = $menuInstance;
1056 * Getter for the menu instance
1058 * @return $menuInstance A RenderableMenu instance
1060 protected final function getMenuInstance () {
1061 return $this->menuInstance;
1065 * Setter for image instance
1067 * @param $imageInstance An instance of an image
1070 public final function setImageInstance (BaseImage $imageInstance) {
1071 $this->imageInstance = $imageInstance;
1075 * Getter for image instance
1077 * @return $imageInstance An instance of an image
1079 public final function getImageInstance () {
1080 return $this->imageInstance;
1084 * Setter for stacker instance
1086 * @param $stackInstance An instance of an stacker
1089 public final function setStackInstance (Stackable $stackInstance) {
1090 $this->stackInstance = $stackInstance;
1094 * Getter for stacker instance
1096 * @return $stackInstance An instance of an stacker
1098 public final function getStackInstance () {
1099 return $this->stackInstance;
1103 * Setter for compressor instance
1105 * @param $compressorInstance An instance of an compressor
1108 public final function setCompressorInstance (Compressor $compressorInstance) {
1109 $this->compressorInstance = $compressorInstance;
1113 * Getter for compressor instance
1115 * @return $compressorInstance An instance of an compressor
1117 public final function getCompressorInstance () {
1118 return $this->compressorInstance;
1122 * Setter for Parseable instance
1124 * @param $parserInstance An instance of an Parseable
1127 public final function setParserInstance (Parseable $parserInstance) {
1128 $this->parserInstance = $parserInstance;
1132 * Getter for Parseable instance
1134 * @return $parserInstance An instance of an Parseable
1136 public final function getParserInstance () {
1137 return $this->parserInstance;
1141 * Setter for HandleableProtocol instance
1143 * @param $protocolInstance An instance of an HandleableProtocol
1146 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1147 $this->protocolInstance = $protocolInstance;
1151 * Getter for HandleableProtocol instance
1153 * @return $protocolInstance An instance of an HandleableProtocol
1155 public final function getProtocolInstance () {
1156 return $this->protocolInstance;
1160 * Setter for DatabaseWrapper instance
1162 * @param $wrapperInstance An instance of an DatabaseWrapper
1165 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1166 $this->wrapperInstance = $wrapperInstance;
1170 * Getter for DatabaseWrapper instance
1172 * @return $wrapperInstance An instance of an DatabaseWrapper
1174 public final function getWrapperInstance () {
1175 return $this->wrapperInstance;
1179 * Setter for socket resource
1181 * @param $socketResource A valid socket resource
1184 public final function setSocketResource ($socketResource) {
1185 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1186 $this->socketResource = $socketResource;
1190 * Getter for socket resource
1192 * @return $socketResource A valid socket resource
1194 public final function getSocketResource () {
1195 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1196 return $this->socketResource;
1200 * Setter for regular expression
1202 * @param $regularExpression A valid regular expression
1205 public final function setRegularExpression ($regularExpression) {
1206 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1207 $this->regularExpression = $regularExpression;
1211 * Getter for regular expression
1213 * @return $regularExpression A valid regular expression
1215 public final function getRegularExpression () {
1216 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1217 return $this->regularExpression;
1221 * Setter for helper instance
1223 * @param $helperInstance An instance of a helper class
1226 protected final function setHelperInstance (Helper $helperInstance) {
1227 $this->helperInstance = $helperInstance;
1231 * Getter for helper instance
1233 * @return $helperInstance An instance of a helper class
1235 public final function getHelperInstance () {
1236 return $this->helperInstance;
1240 * Setter for a Source instance
1242 * @param $sourceInstance An instance of a Source class
1245 protected final function setSourceInstance (Source $sourceInstance) {
1246 $this->sourceInstance = $sourceInstance;
1250 * Getter for a Source instance
1252 * @return $sourceInstance An instance of a Source class
1254 protected final function getSourceInstance () {
1255 return $this->sourceInstance;
1259 * Setter for a UrlSource instance
1261 * @param $sourceInstance An instance of a UrlSource class
1264 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1265 $this->urlSourceInstance = $urlSourceInstance;
1269 * Getter for a UrlSource instance
1271 * @return $urlSourceInstance An instance of a UrlSource class
1273 protected final function getUrlSourceInstance () {
1274 return $this->urlSourceInstance;
1278 * Getter for a InputStream instance
1280 * @param $inputStreamInstance The InputStream instance
1282 protected final function getInputStreamInstance () {
1283 return $this->inputStreamInstance;
1287 * Setter for a InputStream instance
1289 * @param $inputStreamInstance The InputStream instance
1292 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1293 $this->inputStreamInstance = $inputStreamInstance;
1297 * Getter for a OutputStream instance
1299 * @param $outputStreamInstance The OutputStream instance
1301 protected final function getOutputStreamInstance () {
1302 return $this->outputStreamInstance;
1306 * Setter for a OutputStream instance
1308 * @param $outputStreamInstance The OutputStream instance
1311 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1312 $this->outputStreamInstance = $outputStreamInstance;
1316 * Setter for handler instance
1318 * @param $handlerInstance An instance of a Handleable class
1321 protected final function setHandlerInstance (Handleable $handlerInstance) {
1322 $this->handlerInstance = $handlerInstance;
1326 * Getter for handler instance
1328 * @return $handlerInstance A Networkable instance
1330 protected final function getHandlerInstance () {
1331 return $this->handlerInstance;
1335 * Setter for visitor instance
1337 * @param $visitorInstance A Visitor instance
1340 protected final function setVisitorInstance (Visitor $visitorInstance) {
1341 $this->visitorInstance = $visitorInstance;
1345 * Getter for visitor instance
1347 * @return $visitorInstance A Visitor instance
1349 protected final function getVisitorInstance () {
1350 return $this->visitorInstance;
1354 * Setter for DHT instance
1356 * @param $dhtInstance A Distributable instance
1359 protected final function setDhtInstance (Distributable $dhtInstance) {
1360 $this->dhtInstance = $dhtInstance;
1364 * Getter for DHT instance
1366 * @return $dhtInstance A Distributable instance
1368 protected final function getDhtInstance () {
1369 return $this->dhtInstance;
1373 * Setter for raw package Data
1375 * @param $packageData Raw package Data
1378 public final function setPackageData (array $packageData) {
1379 $this->packageData = $packageData;
1383 * Getter for raw package Data
1385 * @return $packageData Raw package Data
1387 public function getPackageData () {
1388 return $this->packageData;
1393 * Setter for Iterator instance
1395 * @param $iteratorInstance An instance of an Iterator
1398 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1399 $this->iteratorInstance = $iteratorInstance;
1403 * Getter for Iterator instance
1405 * @return $iteratorInstance An instance of an Iterator
1407 public final function getIteratorInstance () {
1408 return $this->iteratorInstance;
1412 * Setter for FilePointer instance
1414 * @param $pointerInstance An instance of an FilePointer class
1417 protected final function setPointerInstance (FilePointer $pointerInstance) {
1418 $this->pointerInstance = $pointerInstance;
1422 * Getter for FilePointer instance
1424 * @return $pointerInstance An instance of an FilePointer class
1426 public final function getPointerInstance () {
1427 return $this->pointerInstance;
1431 * Unsets pointer instance which triggers a call of __destruct() if the
1432 * instance is still there. This is surely not fatal on already "closed"
1433 * file pointer instances.
1435 * I don't want to mess around with above setter by giving it a default
1436 * value NULL as setter should always explicitly only set (existing) object
1437 * instances and NULL is NULL.
1441 protected final function unsetPointerInstance () {
1442 // Simply it to NULL
1443 $this->pointerInstance = NULL;
1447 * Setter for Indexable instance
1449 * @param $indexInstance An instance of an Indexable class
1452 protected final function setIndexInstance (Indexable $indexInstance) {
1453 $this->indexInstance = $indexInstance;
1457 * Getter for Indexable instance
1459 * @return $indexInstance An instance of an Indexable class
1461 public final function getIndexInstance () {
1462 return $this->indexInstance;
1466 * Setter for Block instance
1468 * @param $blockInstance An instance of an Block class
1471 protected final function setBlockInstance (Block $blockInstance) {
1472 $this->blockInstance = $blockInstance;
1476 * Getter for Block instance
1478 * @return $blockInstance An instance of an Block class
1480 public final function getBlockInstance () {
1481 return $this->blockInstance;
1485 * Setter for Minable instance
1487 * @param $minableInstance A Minable instance
1490 protected final function setMinableInstance (Minable $minableInstance) {
1491 $this->minableInstance = $minableInstance;
1495 * Getter for minable instance
1497 * @return $minableInstance A Minable instance
1499 protected final function getMinableInstance () {
1500 return $this->minableInstance;
1504 * Setter for FrameworkDirectory instance
1506 * @param $directoryInstance A FrameworkDirectoryPointer instance
1509 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1510 $this->directoryInstance = $directoryInstance;
1514 * Getter for FrameworkDirectory instance
1516 * @return $directoryInstance A FrameworkDirectory instance
1518 protected final function getDirectoryInstance () {
1519 return $this->directoryInstance;
1523 * Setter for listener instance
1525 * @param $listenerInstance A Listenable instance
1528 protected final function setListenerInstance (Listenable $listenerInstance) {
1529 $this->listenerInstance = $listenerInstance;
1533 * Getter for listener instance
1535 * @return $listenerInstance A Listenable instance
1537 protected final function getListenerInstance () {
1538 return $this->listenerInstance;
1542 * Getter for communicator instance
1544 * @return $communicatorInstance An instance of a Communicator class
1546 public final function getCommunicatorInstance () {
1547 return $this->communicatorInstance;
1551 * Setter for communicator instance
1553 * @param $communicatorInstance An instance of a Communicator class
1556 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1557 $this->communicatorInstance = $communicatorInstance;
1561 * Setter for state instance
1563 * @param $stateInstance A Stateable instance
1566 public final function setStateInstance (Stateable $stateInstance) {
1567 $this->stateInstance = $stateInstance;
1571 * Getter for state instance
1573 * @return $stateInstance A Stateable instance
1575 public final function getStateInstance () {
1576 return $this->stateInstance;
1580 * Setter for output instance
1582 * @param $outputInstance The debug output instance
1585 public final function setOutputInstance (OutputStreamer $outputInstance) {
1586 $this->outputInstance = $outputInstance;
1590 * Getter for output instance
1592 * @return $outputInstance The debug output instance
1594 public final function getOutputInstance () {
1595 return $this->outputInstance;
1599 * Setter for command name
1601 * @param $commandName Last validated command name
1604 protected final function setCommandName ($commandName) {
1605 $this->commandName = $commandName;
1609 * Getter for command name
1611 * @return $commandName Last validated command name
1613 protected final function getCommandName () {
1614 return $this->commandName;
1618 * Setter for controller name
1620 * @param $controllerName Last validated controller name
1623 protected final function setControllerName ($controllerName) {
1624 $this->controllerName = $controllerName;
1628 * Getter for controller name
1630 * @return $controllerName Last validated controller name
1632 protected final function getControllerName () {
1633 return $this->controllerName;
1637 * Getter for protocol name
1639 * @return $protocolName Name of used protocol
1641 public final function getProtocolName () {
1642 return $this->protocolName;
1646 * Setter for protocol name
1648 * @param $protocolName Name of used protocol
1651 protected final function setProtocolName ($protocolName) {
1652 $this->protocolName = $protocolName;
1656 * Checks whether an object equals this object. You should overwrite this
1657 * method to implement own equality checks
1659 * @param $objectInstance An instance of a FrameworkInterface object
1660 * @return $equals Whether both objects equals
1662 public function equals (FrameworkInterface $objectInstance) {
1665 $this->__toString() == $objectInstance->__toString()
1667 $this->hashCode() == $objectInstance->hashCode()
1670 // Return the result
1675 * Generates a generic hash code of this class. You should really overwrite
1676 * this method with your own hash code generator code. But keep KISS in mind.
1678 * @return $hashCode A generic hash code respresenting this whole class
1680 public function hashCode () {
1682 return crc32($this->__toString());
1686 * Formats computer generated price values into human-understandable formats
1687 * with thousand and decimal separators.
1689 * @param $value The in computer format value for a price
1690 * @param $currency The currency symbol (use HTML-valid characters!)
1691 * @param $decNum Number of decimals after commata
1692 * @return $price The for the current language formated price string
1693 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1694 * thousands separator
1697 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1698 // Are all required attriutes set?
1699 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1700 // Throw an exception
1701 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1705 $value = (float) $value;
1707 // Reformat the US number
1708 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1710 // Return as string...
1715 * Appends a trailing slash to a string
1717 * @param $str A string (maybe) without trailing slash
1718 * @return $str A string with an auto-appended trailing slash
1720 public final function addMissingTrailingSlash ($str) {
1721 // Is there a trailing slash?
1722 if (substr($str, -1, 1) != '/') {
1726 // Return string with trailing slash
1731 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1732 * application helper instance (ApplicationHelper by default).
1734 * @param $applicationInstance An application helper instance or
1735 * null if we shall use the default
1736 * @return $templateInstance The template engine instance
1737 * @throws NullPointerException If the discovered application
1738 * instance is still null
1740 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1741 // Is the application instance set?
1742 if (is_null($applicationInstance)) {
1743 // Get the current instance
1744 $applicationInstance = $this->getApplicationInstance();
1747 if (is_null($applicationInstance)) {
1748 // Thrown an exception
1749 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1753 // Initialize the template engine
1754 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1756 // Return the prepared instance
1757 return $templateInstance;
1761 * Debugs this instance by putting out it's full content
1763 * @param $message Optional message to show in debug output
1766 public final function debugInstance ($message = '') {
1767 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1768 restore_error_handler();
1773 // Is a message set?
1774 if (!empty($message)) {
1775 // Construct message
1776 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1779 // Generate the output
1780 $content .= sprintf('<pre>%s</pre>',
1783 print_r($this, TRUE)
1789 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>',
1790 $this->__toString(),
1792 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1797 * Replaces control characters with printable output
1799 * @param $str String with control characters
1800 * @return $str Replaced string
1802 protected function replaceControlCharacters ($str) {
1805 chr(13), '[r]', str_replace(
1806 chr(10), '[n]', str_replace(
1816 * Output a partial stub message for the caller method
1818 * @param $message An optional message to display
1821 protected function partialStub ($message = '') {
1822 // Get the backtrace
1823 $backtrace = debug_backtrace();
1825 // Generate the class::method string
1826 $methodName = 'UnknownClass->unknownMethod';
1827 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1828 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1831 // Construct the full message
1832 $stubMessage = sprintf('[%s:] Partial stub!',
1836 // Is the extra message given?
1837 if (!empty($message)) {
1838 // Then add it as well
1839 $stubMessage .= ' Message: ' . $message;
1842 // Debug instance is there?
1843 if (!is_null($this->getDebugInstance())) {
1844 // Output stub message
1845 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1848 trigger_error($stubMessage);
1854 * Outputs a debug backtrace and stops further script execution
1856 * @param $message An optional message to output
1857 * @param $doExit Whether exit the program (TRUE is default)
1860 public function debugBackTrace ($message = '', $doExit = TRUE) {
1861 // Sorry, there is no other way getting this nice backtrace
1862 if (!empty($message)) {
1864 printf('Message: %s<br />' . PHP_EOL, $message);
1868 debug_print_backtrace();
1872 if ($doExit === TRUE) {
1878 * Creates an instance of a debugger instance
1880 * @param $className Name of the class (currently unsupported)
1881 * @return $debugInstance An instance of a debugger class
1882 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1884 public final static function createDebugInstance ($className) {
1885 // Is the instance set?
1886 if (!Registry::getRegistry()->instanceExists('debug')) {
1887 // Init debug instance
1888 $debugInstance = NULL;
1892 // Get a debugger instance
1893 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1894 } catch (NullPointerException $e) {
1895 // Didn't work, no instance there
1896 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1899 // Empty string should be ignored and used for testing the middleware
1900 DebugMiddleware::getSelfInstance()->output('');
1902 // Set it in its own class. This will set it in the registry
1903 $debugInstance->setDebugInstance($debugInstance);
1905 // Get instance from registry
1906 $debugInstance = Registry::getRegistry()->getDebugInstance();
1910 return $debugInstance;
1914 * Simple output of a message with line-break
1916 * @param $message Message to output
1919 public function outputLine ($message) {
1921 print($message . PHP_EOL);
1925 * Outputs a debug message whether to debug instance (should be set!) or
1926 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1927 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1929 * @param $message Message we shall send out...
1930 * @param $doPrint Whether print or die here (default: print)
1931 * @paran $stripTags Whether to strip tags (default: FALSE)
1934 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1935 // Set debug instance to NULL
1936 $debugInstance = NULL;
1940 // Get debug instance
1941 $debugInstance = $this->getDebugInstance();
1942 } catch (NullPointerException $e) {
1943 // The debug instance is not set (yet)
1946 // Is the debug instance there?
1947 if (is_object($debugInstance)) {
1948 // Use debug output handler
1949 $debugInstance->output($message, $stripTags);
1951 if ($doPrint === FALSE) {
1952 // Die here if not printed
1956 // Are debug times enabled?
1957 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1959 $message = $this->getPrintableExecutionTime() . $message;
1963 if ($doPrint === TRUE) {
1965 $this->outputLine($message);
1974 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1976 * @param $str The string, what ever it is needs to be converted
1977 * @return $className Generated class name
1979 public static final function convertToClassName ($str) {
1983 // Convert all dashes in underscores
1984 $str = self::convertDashesToUnderscores($str);
1986 // Now use that underscores to get classname parts for hungarian style
1987 foreach (explode('_', $str) as $strPart) {
1988 // Make the class name part lower case and first upper case
1989 $className .= ucfirst(strtolower($strPart));
1992 // Return class name
1997 * Converts dashes to underscores, e.g. useable for configuration entries
1999 * @param $str The string with maybe dashes inside
2000 * @return $str The converted string with no dashed, but underscores
2002 public static final function convertDashesToUnderscores ($str) {
2004 $str = str_replace('-', '_', $str);
2006 // Return converted string
2011 * Marks up the code by adding e.g. line numbers
2013 * @param $phpCode Unmarked PHP code
2014 * @return $markedCode Marked PHP code
2016 public function markupCode ($phpCode) {
2021 $errorArray = error_get_last();
2023 // Init the code with error message
2024 if (is_array($errorArray)) {
2026 $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>',
2027 basename($errorArray['file']),
2028 $errorArray['line'],
2029 $errorArray['message'],
2034 // Add line number to the code
2035 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2037 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2039 htmlentities($code, ENT_QUOTES)
2048 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2049 * beatiful for web-based front-ends. If null is given a message id
2050 * null_timestamp will be resolved and returned.
2052 * @param $timestamp Timestamp to prepare (filter) for display
2053 * @return $readable A readable timestamp
2055 public function doFilterFormatTimestamp ($timestamp) {
2056 // Default value to return
2059 // Is the timestamp null?
2060 if (is_null($timestamp)) {
2061 // Get a message string
2062 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2064 switch ($this->getLanguageInstance()->getLanguageCode()) {
2065 case 'de': // German format is a bit different to default
2066 // Split the GMT stamp up
2067 $dateTime = explode(' ', $timestamp );
2068 $dateArray = explode('-', $dateTime[0]);
2069 $timeArray = explode(':', $dateTime[1]);
2071 // Construct the timestamp
2072 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2082 default: // Default is pass-through
2083 $readable = $timestamp;
2093 * Filter a given number into a localized number
2095 * @param $value The raw value from e.g. database
2096 * @return $localized Localized value
2098 public function doFilterFormatNumber ($value) {
2099 // Generate it from config and localize dependencies
2100 switch ($this->getLanguageInstance()->getLanguageCode()) {
2101 case 'de': // German format is a bit different to default
2102 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2105 default: // US, etc.
2106 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2115 * "Getter" for databse entry
2117 * @return $entry An array with database entries
2118 * @throws NullPointerException If the database result is not found
2119 * @throws InvalidDatabaseResultException If the database result is invalid
2121 protected final function getDatabaseEntry () {
2122 // Is there an instance?
2123 if (!$this->getResultInstance() instanceof SearchableResult) {
2124 // Throw an exception here
2125 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2129 $this->getResultInstance()->rewind();
2131 // Do we have an entry?
2132 if ($this->getResultInstance()->valid() === FALSE) {
2133 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2134 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2138 $this->getResultInstance()->next();
2141 $entry = $this->getResultInstance()->current();
2148 * Getter for field name
2150 * @param $fieldName Field name which we shall get
2151 * @return $fieldValue Field value from the user
2152 * @throws NullPointerException If the result instance is null
2154 public final function getField ($fieldName) {
2155 // Default field value
2158 // Get result instance
2159 $resultInstance = $this->getResultInstance();
2161 // Is this instance null?
2162 if (is_null($resultInstance)) {
2163 // Then the user instance is no longer valid (expired cookies?)
2164 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2167 // Get current array
2168 $fieldArray = $resultInstance->current();
2169 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2171 // Convert dashes to underscore
2172 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2174 // Does the field exist?
2175 if ($this->isFieldSet($fieldName)) {
2177 $fieldValue = $fieldArray[$fieldName2];
2178 } elseif (defined('DEVELOPER')) {
2179 // Missing field entry, may require debugging
2180 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2182 // Missing field entry, may require debugging
2183 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2191 * Checks if given field is set
2193 * @param $fieldName Field name to check
2194 * @return $isSet Whether the given field name is set
2195 * @throws NullPointerException If the result instance is null
2197 public function isFieldSet ($fieldName) {
2198 // Get result instance
2199 $resultInstance = $this->getResultInstance();
2201 // Is this instance null?
2202 if (is_null($resultInstance)) {
2203 // Then the user instance is no longer valid (expired cookies?)
2204 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2207 // Get current array
2208 $fieldArray = $resultInstance->current();
2209 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2211 // Convert dashes to underscore
2212 $fieldName = self::convertDashesToUnderscores($fieldName);
2215 $isSet = isset($fieldArray[$fieldName]);
2222 * Flushs all pending updates to the database layer
2226 public function flushPendingUpdates () {
2227 // Get result instance
2228 $resultInstance = $this->getResultInstance();
2230 // Do we have data to update?
2231 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2232 // Get wrapper class name config entry
2233 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2235 // Create object instance
2236 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2238 // Yes, then send the whole result to the database layer
2239 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2244 * Outputs a deprecation warning to the developer.
2246 * @param $message The message we shall output to the developer
2248 * @todo Write a logging mechanism for productive mode
2250 public function deprecationWarning ($message) {
2251 // Is developer mode active?
2252 if (defined('DEVELOPER')) {
2253 // Debug instance is there?
2254 if (!is_null($this->getDebugInstance())) {
2255 // Output stub message
2256 self::createDebugInstance(__CLASS__)->debugOutput($message);
2259 trigger_error($message . "<br />\n");
2263 // @TODO Finish this part!
2264 $this->partialStub('Developer mode inactive. Message:' . $message);
2269 * Checks whether the given PHP extension is loaded
2271 * @param $phpExtension The PHP extension we shall check
2272 * @return $isLoaded Whether the PHP extension is loaded
2274 public final function isPhpExtensionLoaded ($phpExtension) {
2276 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2283 * "Getter" as a time() replacement but with milliseconds. You should use this
2284 * method instead of the encapsulated getimeofday() function.
2286 * @return $milliTime Timestamp with milliseconds
2288 public function getMilliTime () {
2289 // Get the time of day as float
2290 $milliTime = gettimeofday(TRUE);
2297 * Idles (sleeps) for given milliseconds
2299 * @return $hasSlept Whether it goes fine
2301 public function idle ($milliSeconds) {
2302 // Sleep is fine by default
2305 // Idle so long with found function
2306 if (function_exists('time_sleep_until')) {
2307 // Get current time and add idle time
2308 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2310 // New PHP 5.1.0 function found, ignore errors
2311 $hasSlept = @time_sleep_until($sleepUntil);
2314 * My Sun station doesn't have that function even with latest PHP
2317 usleep($milliSeconds * 1000);
2324 * Converts a hexadecimal string, even with negative sign as first string to
2325 * a decimal number using BC functions.
2327 * This work is based on comment #86673 on php.net documentation page at:
2328 * <http://de.php.net/manual/en/function.dechex.php#86673>
2330 * @param $hex Hexadecimal string
2331 * @return $dec Decimal number
2333 protected function hex2dec ($hex) {
2334 // Convert to all lower-case
2335 $hex = strtolower($hex);
2337 // Detect sign (negative/positive numbers)
2339 if (substr($hex, 0, 1) == '-') {
2341 $hex = substr($hex, 1);
2344 // Decode the hexadecimal string into a decimal number
2346 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2347 $factor = self::$hexdec[substr($hex, $i, 1)];
2348 $dec = bcadd($dec, bcmul($factor, $e));
2351 // Return the decimal number
2352 return $sign . $dec;
2356 * Converts even very large decimal numbers, also signed, to a hexadecimal
2359 * This work is based on comment #97756 on php.net documentation page at:
2360 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2362 * @param $dec Decimal number, even with negative sign
2363 * @param $maxLength Optional maximum length of the string
2364 * @return $hex Hexadecimal string
2366 protected function dec2hex ($dec, $maxLength = 0) {
2367 // maxLength can be zero or devideable by 2
2368 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2370 // Detect sign (negative/positive numbers)
2377 // Encode the decimal number into a hexadecimal string
2380 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2382 } while ($dec >= 1);
2385 * Leading zeros are required for hex-decimal "numbers". In some
2386 * situations more leading zeros are wanted, so check for both
2389 if ($maxLength > 0) {
2390 // Prepend more zeros
2391 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2392 } elseif ((strlen($hex) % 2) != 0) {
2393 // Only make string's length dividable by 2
2397 // Return the hexadecimal string
2398 return $sign . $hex;
2402 * Converts a ASCII string (0 to 255) into a decimal number.
2404 * @param $asc The ASCII string to be converted
2405 * @return $dec Decimal number
2407 protected function asc2dec ($asc) {
2408 // Convert it into a hexadecimal number
2409 $hex = bin2hex($asc);
2411 // And back into a decimal number
2412 $dec = $this->hex2dec($hex);
2419 * Converts a decimal number into an ASCII string.
2421 * @param $dec Decimal number
2422 * @return $asc An ASCII string
2424 protected function dec2asc ($dec) {
2425 // First convert the number into a hexadecimal string
2426 $hex = $this->dec2hex($dec);
2428 // Then convert it into the ASCII string
2429 $asc = $this->hex2asc($hex);
2436 * Converts a hexadecimal number into an ASCII string. Negative numbers
2439 * @param $hex Hexadecimal string
2440 * @return $asc An ASCII string
2442 protected function hex2asc ($hex) {
2443 // Check for length, it must be devideable by 2
2444 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2445 assert((strlen($hex) % 2) == 0);
2449 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2450 // Get the decimal number of the chunk
2451 $part = hexdec(substr($hex, $idx, 2));
2453 // Add it to the final string
2457 // Return the final string
2462 * Checks whether the given encoded data was encoded with Base64
2464 * @param $encodedData Encoded data we shall check
2465 * @return $isBase64 Whether the encoded data is Base64
2467 protected function isBase64Encoded ($encodedData) {
2469 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2476 * "Getter" to get response/request type from analysis of the system.
2478 * @return $responseType Analyzed response type
2480 protected static function getResponseTypeFromSystem () {
2481 // Default is console
2482 $responseType = 'console';
2484 // Is 'HTTP_HOST' set?
2485 if (isset($_SERVER['HTTP_HOST'])) {
2487 * Then it is a HTML response/request as RSS and so on may be
2488 * transfered over HTTP as well.
2490 $responseType = 'html';
2494 return $responseType;
2498 * Gets a cache key from Criteria instance
2500 * @param $criteriaInstance An instance of a Criteria class
2501 * @param $onlyKeys Only use these keys for a cache key
2502 * @return $cacheKey A cache key suitable for lookup/storage purposes
2504 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2506 $cacheKey = sprintf('%s@%s',
2507 $this->__toString(),
2508 $criteriaInstance->getCacheKey($onlyKeys)
2512 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2517 * Getter for startup time in miliseconds
2519 * @return $startupTime Startup time in miliseconds
2521 protected function getStartupTime () {
2522 return self::$startupTime;
2526 * "Getter" for a printable currently execution time in nice braces
2528 * @return $executionTime Current execution time in nice braces
2530 protected function getPrintableExecutionTime () {
2531 // Caculate the execution time
2532 $executionTime = microtime(TRUE) - $this->getStartupTime();
2534 // Pack it in nice braces
2535 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2538 return $executionTime;
2542 * Hashes a given string with a simple but stronger hash function (no salt)
2543 * and hex-encode it.
2545 * @param $str The string to be hashed
2546 * @return $hash The hash from string $str
2548 public static final function hash ($str) {
2549 // Hash given string with (better secure) hasher
2550 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2557 * "Getter" for length of hash() output. This will be "cached" to speed up
2560 * @return $length Length of hash() output
2562 public static final function getHashLength () {
2564 if (is_null(self::$hashLength)) {
2565 // No, then hash a string and save its length.
2566 self::$hashLength = strlen(self::hash('abc123'));
2570 return self::$hashLength;
2574 * Checks whether the given number is really a number (only chars 0-9).
2576 * @param $num A string consisting only chars between 0 and 9
2577 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2578 * @param $assertMismatch Whether to assert mismatches
2579 * @return $ret The (hopefully) secured numbered value
2581 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2582 // Filter all numbers out
2583 $ret = preg_replace('/[^0123456789]/', '', $num);
2586 if ($castValue === TRUE) {
2587 // Cast to biggest numeric type
2588 $ret = (double) $ret;
2591 // Assert only if requested
2592 if ($assertMismatch === TRUE) {
2593 // Has the whole value changed?
2594 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2602 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2604 * @param $num A string consisting only chars between 0 and 9
2605 * @param $assertMismatch Whether to assert mismatches
2606 * @return $ret The (hopefully) secured hext-numbered value
2608 public function hexval ($num, $assertMismatch = FALSE) {
2609 // Filter all numbers out
2610 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2612 // Assert only if requested
2613 if ($assertMismatch === TRUE) {
2614 // Has the whole value changed?
2615 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2623 * Checks whether start/end marker are set
2625 * @param $data Data to be checked
2626 * @return $isset Whether start/end marker are set
2628 public final function ifStartEndMarkersSet ($data) {
2630 $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));
2632 // ... and return it
2637 * Determines if an element is set in the generic array
2639 * @param $keyGroup Main group for the key
2640 * @param $subGroup Sub group for the key
2641 * @param $key Key to check
2642 * @param $element Element to check
2643 * @return $isset Whether the given key is set
2645 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2647 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2650 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2656 * Determines if a key is set in the generic array
2658 * @param $keyGroup Main group for the key
2659 * @param $subGroup Sub group for the key
2660 * @param $key Key to check
2661 * @return $isset Whether the given key is set
2663 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2665 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2668 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2676 * Determines if a group is set in the generic array
2678 * @param $keyGroup Main group
2679 * @param $subGroup Sub group
2680 * @return $isset Whether the given group is set
2682 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2684 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2687 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2694 * Getter for sub key group
2696 * @param $keyGroup Main key group
2697 * @param $subGroup Sub key group
2698 * @return $array An array with all array elements
2700 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2702 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2703 // No, then abort here
2704 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2709 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2712 return $this->genericArray[$keyGroup][$subGroup];
2716 * Unsets a given key in generic array
2718 * @param $keyGroup Main group for the key
2719 * @param $subGroup Sub group for the key
2720 * @param $key Key to unset
2723 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2725 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2728 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2732 * Unsets a given element in generic array
2734 * @param $keyGroup Main group for the key
2735 * @param $subGroup Sub group for the key
2736 * @param $key Key to unset
2737 * @param $element Element to unset
2740 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2742 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2745 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2749 * Append a string to a given generic array key
2751 * @param $keyGroup Main group for the key
2752 * @param $subGroup Sub group for the key
2753 * @param $key Key to unset
2754 * @param $value Value to add/append
2757 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2759 //* 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);
2761 // Is it already there?
2762 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2764 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2767 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2772 * Append a string to a given generic array element
2774 * @param $keyGroup Main group for the key
2775 * @param $subGroup Sub group for the key
2776 * @param $key Key to unset
2777 * @param $element Element to check
2778 * @param $value Value to add/append
2781 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2783 //* 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);
2785 // Is it already there?
2786 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2788 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2791 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2796 * Sets a string in 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 setStringGenericArrayElement ($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);
2810 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2814 * Initializes given generic array group
2816 * @param $keyGroup Main group for the key
2817 * @param $subGroup Sub group for the key
2818 * @param $key Key to use
2819 * @param $forceInit Optionally force initialization
2822 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2824 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2826 // Is it already set?
2827 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2828 // Already initialized
2829 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2834 $this->genericArray[$keyGroup][$subGroup] = array();
2838 * Initializes given generic array key
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 initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2848 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2850 // Is it already set?
2851 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2852 // Already initialized
2853 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2858 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2862 * Initializes given generic array element
2864 * @param $keyGroup Main group for the key
2865 * @param $subGroup Sub group for the key
2866 * @param $key Key to use
2867 * @param $element Element to use
2868 * @param $forceInit Optionally force initialization
2871 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2873 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2875 // Is it already set?
2876 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2877 // Already initialized
2878 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2883 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2887 * Pushes an element to a generic key
2889 * @param $keyGroup Main group for the key
2890 * @param $subGroup Sub group for the key
2891 * @param $key Key to use
2892 * @param $value Value to add/append
2893 * @return $count Number of array elements
2895 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2897 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2900 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2902 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2906 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2909 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2910 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2915 * Pushes an element to a generic array element
2917 * @param $keyGroup Main group for the key
2918 * @param $subGroup Sub group for the key
2919 * @param $key Key to use
2920 * @param $element Element to check
2921 * @param $value Value to add/append
2922 * @return $count Number of array elements
2924 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2926 //* 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));
2929 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2931 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2935 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2938 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2939 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2944 * Pops an element from a generic group
2946 * @param $keyGroup Main group for the key
2947 * @param $subGroup Sub group for the key
2948 * @param $key Key to unset
2949 * @return $value Last "popped" value
2951 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2953 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2956 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2958 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2963 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2966 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2967 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2972 * Shifts an element from a generic group
2974 * @param $keyGroup Main group for the key
2975 * @param $subGroup Sub group for the key
2976 * @param $key Key to unset
2977 * @return $value Last "popped" value
2979 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2981 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2984 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2986 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2991 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2994 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2995 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3000 * Count generic array group
3002 * @param $keyGroup Main group for the key
3003 * @return $count Count of given group
3005 protected final function countGenericArray ($keyGroup) {
3007 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3010 if (!isset($this->genericArray[$keyGroup])) {
3012 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3017 $count = count($this->genericArray[$keyGroup]);
3020 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3027 * Count generic array sub group
3029 * @param $keyGroup Main group for the key
3030 * @param $subGroup Sub group for the key
3031 * @return $count Count of given group
3033 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3035 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3038 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3040 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3045 $count = count($this->genericArray[$keyGroup][$subGroup]);
3048 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3055 * Count generic array elements
3057 * @param $keyGroup Main group for the key
3058 * @param $subGroup Sub group for the key
3059 * @para $key Key to count
3060 * @return $count Count of given key
3062 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3064 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3067 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3069 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3071 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3073 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3078 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3081 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3088 * Getter for whole generic group array
3090 * @param $keyGroup Key group to get
3091 * @return $array Whole generic array group
3093 protected final function getGenericArray ($keyGroup) {
3095 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3098 if (!isset($this->genericArray[$keyGroup])) {
3100 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3105 return $this->genericArray[$keyGroup];
3109 * Setter for generic array key
3111 * @param $keyGroup Key group to get
3112 * @param $subGroup Sub group for the key
3113 * @param $key Key to unset
3114 * @param $value Mixed value from generic array element
3117 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3119 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3122 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3126 * Getter 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 * @return $value Mixed value from generic array element
3133 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3135 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3138 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3140 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3145 return $this->genericArray[$keyGroup][$subGroup][$key];
3149 * Sets a value in given generic array key/element
3151 * @param $keyGroup Main group for the key
3152 * @param $subGroup Sub group for the key
3153 * @param $key Key to set
3154 * @param $element Element to set
3155 * @param $value Value to set
3158 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3160 //* 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));
3163 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3167 * Getter for generic array element
3169 * @param $keyGroup Key group to get
3170 * @param $subGroup Sub group for the key
3171 * @param $key Key to look for
3172 * @param $element Element to look for
3173 * @return $value Mixed value from generic array element
3175 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3177 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3180 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3182 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3187 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3191 * Checks if a given sub group is valid (array)
3193 * @param $keyGroup Key group to get
3194 * @param $subGroup Sub group for the key
3195 * @return $isValid Whether given sub group is valid
3197 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3199 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3202 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3209 * Checks if a given key is valid (array)
3211 * @param $keyGroup Key group to get
3212 * @param $subGroup Sub group for the key
3213 * @param $key Key to check
3214 * @return $isValid Whether given sub group is valid
3216 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3218 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3221 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3228 * Initializes the web output instance
3232 protected function initWebOutputInstance () {
3233 // Get application instance
3234 $applicationInstance = Registry::getRegistry()->getInstance('app');
3236 // Is this a response instance?
3237 if ($this instanceof Responseable) {
3238 // Then set it in application instance
3239 $applicationInstance->setResponseInstance($this);
3242 // Init web output instance
3243 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3246 $this->setWebOutputInstance($outputInstance);
3250 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3252 * @param $boolean Boolean value
3253 * @return $translated Translated boolean value
3255 public static final function translateBooleanToYesNo ($boolean) {
3256 // Make sure it is really boolean
3257 assert(is_bool($boolean));
3260 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3262 // ... and return it
3267 * Encodes raw data (almost any type) by "serializing" it and then pack it
3268 * into a "binary format".
3270 * @param $rawData Raw data (almost any type)
3271 * @return $encoded Encoded data
3273 protected function encodeData ($rawData) {
3274 // Make sure no objects or resources pass through
3275 assert(!is_object($rawData));
3276 assert(!is_resource($rawData));
3278 // First "serialize" it (json_encode() is faster than serialize())
3279 $encoded = $this->packString(json_encode($rawData));
3286 * Pack a string into a "binary format". Please execuse me that this is
3287 * widely undocumented. :-(
3289 * @param $str Unpacked string
3290 * @return $packed Packed string
3291 * @todo Improve documentation
3293 protected function packString ($str) {
3295 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3297 // First compress the string (gzcompress is okay)
3298 $str = gzcompress($str);
3303 // And start the "encoding" loop
3304 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3306 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3307 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3309 if (($idx + $i) <= strlen($str)) {
3310 $ord = ord(substr($str, ($idx + $i), 1));
3312 $add = $ord * pow(256, $factor);
3316 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3320 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3321 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3323 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3324 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3330 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');
3335 * Checks whether the given file/path is in open_basedir(). This does not
3336 * gurantee that the file is actually readable and/or writeable. If you need
3337 * such gurantee then please use isReadableFile() instead.
3339 * @param $filePathName Name of the file/path to be checked
3340 * @return $isReachable Whether it is within open_basedir()
3342 protected static function isReachableFilePath ($filePathName) {
3343 // Is not reachable by default
3344 $isReachable = FALSE;
3346 // Get open_basedir parameter
3347 $openBaseDir = ini_get('open_basedir');
3350 if (!empty($openBaseDir)) {
3351 // Check all entries
3352 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3353 // Check on existence
3354 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3356 $isReachable = TRUE;
3360 // If open_basedir is not set, all is allowed
3361 $isReachable = TRUE;
3365 return $isReachable;
3369 * Checks whether the give file is within open_basedir() (done by
3370 * isReachableFilePath()), is actually a file and is readable.
3372 * @param $fileName Name of the file to be checked
3373 * @return $isReadable Whether the file is readable (and therefor exists)
3375 public static function isReadableFile ($fileName) {
3376 // Default is not readable
3377 $isReadable = FALSE;
3379 // Is within parameters, so check if it is a file and readable
3380 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3387 * Creates a full-qualified file name (FQFN) for given file name by adding
3388 * a configured temporary file path to it.
3390 * @param $fileName Name for temporary file
3391 * @return $fqfn Full-qualified file name
3392 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3393 * @throws FileIoException If the file cannot be written
3395 protected static function createTempPathForFile ($fileName) {
3397 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3399 // Is the path writeable?
3400 if (!is_writable($basePath)) {
3401 // Path is write-protected
3402 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3406 $fqfn = $basePath . '/' . $fileName;
3409 if (!self::isReachableFilePath($fqfn)) {
3411 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3419 * "Getter" for a printable state name
3421 * @return $stateName Name of the node's state in a printable format
3423 public final function getPrintableState () {
3424 // Default is 'null'
3425 $stateName = 'null';
3427 // Get the state instance
3428 $stateInstance = $this->getStateInstance();
3430 // Is it an instance of Stateable?
3431 if ($stateInstance instanceof Stateable) {
3432 // Then use that state name
3433 $stateName = $stateInstance->getStateName();
3441 * Handles socket error for given socket resource and peer data. This method
3442 * validates $socketResource if it is a valid resource (see is_resource())
3443 * but assumes valid data in array $recipientData, except that
3444 * count($recipientData) is always 2.
3446 * @param $method Value of __METHOD__ from calling method
3447 * @param $line Value of __LINE__ from calling method
3448 * @param $socketResource A valid socket resource
3449 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3451 * @throws InvalidSocketException If $socketResource is no socket resource
3452 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3453 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3455 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3456 // This method handles only socket resources
3457 if (!is_resource($socketResource)) {
3458 // No resource, abort here
3459 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3462 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3463 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3464 assert(isset($socketData[0]));
3465 assert(isset($socketData[1]));
3467 // Get error code for first validation (0 is not an error)
3468 $errorCode = socket_last_error($socketResource);
3470 // If the error code is zero, someone called this method without an error
3471 if ($errorCode == 0) {
3472 // No error detected (or previously cleared outside this method)
3473 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3476 // Get handler (method) name
3477 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3479 // Call-back the error handler method
3480 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3482 // Finally clear the error because it has been handled
3483 socket_clear_error($socketResource);