3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Generic\FrameworkInterface;
8 use CoreFramework\Loader\ClassLoader;
9 use CoreFramework\Manager\ManageableApplication;
10 use CoreFramework\Registry\Register;
11 use CoreFramework\Registry\Generic\Registry;
12 use CoreFramework\Template\CompileableTemplate;
18 * The simulator system class is the super class of all other classes. This
19 * class handles saving of games etc.
21 * @author Roland Haeder <webmaster@shipsimu.org>
23 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
24 * @license GNU GPL 3.0 or any newer version
25 * @link http://www.shipsimu.org
27 * This program is free software: you can redistribute it and/or modify
28 * it under the terms of the GNU General Public License as published by
29 * the Free Software Foundation, either version 3 of the License, or
30 * (at your option) any later version.
32 * This program is distributed in the hope that it will be useful,
33 * but WITHOUT ANY WARRANTY; without even the implied warranty of
34 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 * GNU General Public License for more details.
37 * You should have received a copy of the GNU General Public License
38 * along with this program. If not, see <http://www.gnu.org/licenses/>.
40 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
42 * Length of output from hash()
44 private static $hashLength = NULL;
49 private $realClass = 'BaseFrameworkSystem';
52 * Instance of a request class
54 private $requestInstance = NULL;
57 * Instance of a response class
59 private $responseInstance = NULL;
62 * Search criteria instance
64 private $searchInstance = NULL;
67 * Update criteria instance
69 private $updateInstance = NULL;
72 * The file I/O instance for the template loader
74 private $fileIoInstance = NULL;
79 private $resolverInstance = NULL;
82 * Template engine instance
84 private $templateInstance = NULL;
87 * Database result instance
89 private $resultInstance = NULL;
92 * Instance for user class
94 private $userInstance = NULL;
97 * A controller instance
99 private $controllerInstance = NULL;
104 private $rngInstance = NULL;
107 * Instance of a crypto helper
109 private $cryptoInstance = NULL;
112 * Instance of an Iterator class
114 private $iteratorInstance = NULL;
117 * Instance of the list
119 private $listInstance = NULL;
124 private $menuInstance = NULL;
127 * Instance of the image
129 private $imageInstance = NULL;
132 * Instance of the stacker
134 private $stackInstance = NULL;
137 * A Compressor instance
139 private $compressorInstance = NULL;
142 * A Parseable instance
144 private $parserInstance = NULL;
147 * A HandleableProtocol instance
149 private $protocolInstance = NULL;
152 * A database wrapper instance
154 private $databaseInstance = NULL;
157 * A helper instance for the form
159 private $helperInstance = NULL;
162 * An instance of a Source class
164 private $sourceInstance = NULL;
167 * An instance of a UrlSource class
169 private $urlSourceInstance = NULL;
172 * An instance of a InputStream class
174 private $inputStreamInstance = NULL;
177 * An instance of a OutputStream class
179 private $outputStreamInstance = NULL;
182 * Networkable handler instance
184 private $handlerInstance = NULL;
187 * Visitor handler instance
189 private $visitorInstance = NULL;
194 private $dhtInstance = NULL;
197 * An instance of a database wrapper class
199 private $wrapperInstance = NULL;
202 * An instance of a file I/O pointer class (not handler)
204 private $pointerInstance = NULL;
207 * An instance of an Indexable class
209 private $indexInstance = NULL;
212 * An instance of a Block class
214 private $blockInstance = NULL;
219 private $minableInstance = NULL;
222 * A FrameworkDirectory instance
224 private $directoryInstance = NULL;
229 private $listenerInstance = NULL;
232 * An instance of a communicator
234 private $communicatorInstance = NULL;
237 * The concrete output instance
239 private $outputInstance = NULL;
244 private $stateInstance = NULL;
247 * Thousands separator
249 private $thousands = '.'; // German
254 private $decimals = ','; // German
259 private $socketResource = FALSE;
262 * Regular expression to use for validation
264 private $regularExpression = '';
269 private $packageData = array();
274 private $genericArray = array();
279 private $commandName = '';
284 private $controllerName = '';
287 * Name of used protocol
289 private $protocolName = 'invalid';
292 * Array with bitmasks and such for pack/unpack methods to support both
293 * 32-bit and 64-bit systems
295 private $packingData = array(
298 'left' => 0xffff0000,
299 'right' => 0x0000ffff,
305 'left' => 0xffffffff00000000,
306 'right' => 0x00000000ffffffff,
313 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
315 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
317 private $archArrayElement = FALSE;
319 /***********************
320 * Exception codes.... *
321 ***********************/
323 // @todo Try to clean these constants up
324 const EXCEPTION_IS_NULL_POINTER = 0x001;
325 const EXCEPTION_IS_NO_OBJECT = 0x002;
326 const EXCEPTION_IS_NO_ARRAY = 0x003;
327 const EXCEPTION_MISSING_METHOD = 0x004;
328 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
329 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
330 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
331 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
332 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
333 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
334 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
335 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
336 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
337 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
338 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
339 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
340 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
341 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
342 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
343 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
344 const EXCEPTION_PATH_NOT_FOUND = 0x015;
345 const EXCEPTION_INVALID_PATH_NAME = 0x016;
346 const EXCEPTION_READ_PROTECED_PATH = 0x017;
347 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
348 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
349 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
350 const EXCEPTION_INVALID_RESOURCE = 0x01b;
351 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
352 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
353 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
354 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
355 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
356 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
357 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
358 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
359 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
360 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
361 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
362 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
363 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
364 const EXCEPTION_INVALID_STRING = 0x029;
365 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
366 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
367 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
368 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
369 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
370 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
371 const EXCEPTION_MISSING_ELEMENT = 0x030;
372 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
373 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
374 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
375 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
376 const EXCEPTION_FATAL_ERROR = 0x035;
377 const EXCEPTION_FILE_NOT_FOUND = 0x036;
378 const EXCEPTION_ASSERTION_FAILED = 0x037;
379 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
380 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
381 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
382 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
383 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
384 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
387 * Hexadecimal->Decimal translation array
389 private static $hexdec = array(
409 * Decimal->hexadecimal translation array
411 private static $dechex = array(
431 * Startup time in miliseconds
433 private static $startupTime = 0;
436 * Protected super constructor
438 * @param $className Name of the class
441 protected function __construct ($className) {
443 $this->setRealClass($className);
445 // Set configuration instance if no registry ...
446 if (!$this instanceof Register) {
447 // ... because registries doesn't need to be configured
448 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
451 // Is the startup time set? (0 cannot be TRUE anymore)
452 if (self::$startupTime == 0) {
454 self::$startupTime = microtime(TRUE);
458 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
462 * Destructor for all classes. You should not call this method on your own.
466 public function __destruct () {
467 // Flush any updated entries to the database
468 $this->flushPendingUpdates();
470 // Is this object already destroyed?
471 if ($this->__toString() != 'DestructedObject') {
472 // Destroy all informations about this class but keep some text about it alive
473 $this->setRealClass('DestructedObject');
474 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
475 // Already destructed object
476 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
481 // Do not call this twice
482 trigger_error(__METHOD__ . ': Called twice.');
488 * The __call() method where all non-implemented methods end up
490 * @param $methodName Name of the missing method
491 * @args $args Arguments passed to the method
494 public final function __call ($methodName, $args) {
495 return self::__callStatic($methodName, $args);
499 * The __callStatic() method where all non-implemented static methods end up
501 * @param $methodName Name of the missing method
502 * @args $args Arguments passed to the method
505 public static final function __callStatic ($methodName, $args) {
506 // Init argument string
509 // Is it NULL, empty or an array?
510 if (is_null($args)) {
512 $argsString = 'NULL';
513 } elseif (is_array($args)) {
517 // Some arguments are there
518 foreach ($args as $arg) {
519 // Add data about the argument
520 $argsString .= gettype($arg) . ':';
523 // Found a NULL argument
524 $argsString .= 'NULL';
525 } elseif (is_string($arg)) {
526 // Add length for strings
527 $argsString .= strlen($arg);
528 } elseif ((is_int($arg)) || (is_float($arg))) {
531 } elseif (is_array($arg)) {
532 // .. or size if array
533 $argsString .= count($arg);
534 } elseif (is_object($arg)) {
536 $reflection = new ReflectionClass($arg);
538 // Is an other object, maybe no __toString() available
539 $argsString .= $reflection->getName();
540 } elseif ($arg === TRUE) {
541 // ... is boolean 'TRUE'
542 $argsString .= 'TRUE';
543 } elseif ($arg === FALSE) {
544 // ... is boolean 'FALSE'
545 $argsString .= 'FALSE';
548 // Comma for next one
553 if (substr($argsString, -2, 1) == ',') {
554 $argsString = substr($argsString, 0, -2);
560 // Invalid arguments!
561 $argsString = '!INVALID:' . gettype($args) . '!';
564 // Output stub message
565 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
566 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
576 * Getter for $realClass
578 * @return $realClass The name of the real class (not BaseFrameworkSystem)
580 public function __toString () {
581 return $this->realClass;
585 * Magic method to catch setting of missing but set class fields/attributes
587 * @param $name Name of the field/attribute
588 * @param $value Value to store
591 public final function __set ($name, $value) {
592 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
595 print_r($value, TRUE)
600 * Magic method to catch getting of missing fields/attributes
602 * @param $name Name of the field/attribute
605 public final function __get ($name) {
606 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
612 * Magic method to catch unsetting of missing fields/attributes
614 * @param $name Name of the field/attribute
617 public final function __unset ($name) {
618 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
624 * Magic method to catch object serialization
626 * @return $unsupported Unsupported method
627 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
629 public final function __sleep () {
630 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
634 * Magic method to catch object deserialization
636 * @return $unsupported Unsupported method
637 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
639 public final function __wakeup () {
640 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
644 * Magic method to catch calls when an object instance is called
646 * @return $unsupported Unsupported method
647 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
649 public final function __invoke () {
650 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
654 * Setter for the real class name
656 * @param $realClass Class name (string)
659 public final function setRealClass ($realClass) {
661 $this->realClass = (string) $realClass;
665 * Setter for database result instance
667 * @param $resultInstance An instance of a database result class
669 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
671 protected final function setResultInstance (SearchableResult $resultInstance) {
672 $this->resultInstance = $resultInstance;
676 * Getter for database result instance
678 * @return $resultInstance An instance of a database result class
680 public final function getResultInstance () {
681 return $this->resultInstance;
685 * Setter for template engine instances
687 * @param $templateInstance An instance of a template engine class
690 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
691 $this->templateInstance = $templateInstance;
695 * Getter for template engine instances
697 * @return $templateInstance An instance of a template engine class
699 protected final function getTemplateInstance () {
700 return $this->templateInstance;
704 * Setter for search instance
706 * @param $searchInstance Searchable criteria instance
709 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
710 $this->searchInstance = $searchInstance;
714 * Getter for search instance
716 * @return $searchInstance Searchable criteria instance
718 public final function getSearchInstance () {
719 return $this->searchInstance;
723 * Setter for update instance
725 * @param $updateInstance Searchable criteria instance
728 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
729 $this->updateInstance = $updateInstance;
733 * Getter for update instance
735 * @return $updateInstance Updateable criteria instance
737 public final function getUpdateInstance () {
738 return $this->updateInstance;
742 * Setter for resolver instance
744 * @param $resolverInstance Instance of a command resolver class
747 public final function setResolverInstance (Resolver $resolverInstance) {
748 $this->resolverInstance = $resolverInstance;
752 * Getter for resolver instance
754 * @return $resolverInstance Instance of a command resolver class
756 public final function getResolverInstance () {
757 return $this->resolverInstance;
761 * Setter for language instance
763 * @param $configInstance The configuration instance which shall
764 * be FrameworkConfiguration
767 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
768 Registry::getRegistry()->addInstance('config', $configInstance);
772 * Getter for configuration instance
774 * @return $configInstance Configuration instance
776 public final function getConfigInstance () {
777 $configInstance = Registry::getRegistry()->getInstance('config');
778 return $configInstance;
782 * Setter for debug instance
784 * @param $debugInstance The instance for debug output class
787 public final function setDebugInstance (DebugMiddleware $debugInstance) {
788 Registry::getRegistry()->addInstance('debug', $debugInstance);
792 * Getter for debug instance
794 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
796 public final function getDebugInstance () {
797 // Get debug instance
798 $debugInstance = Registry::getRegistry()->getInstance('debug');
801 return $debugInstance;
805 * Setter for web output instance
807 * @param $webInstance The instance for web output class
810 public final function setWebOutputInstance (OutputStreamer $webInstance) {
811 Registry::getRegistry()->addInstance('web_output', $webInstance);
815 * Getter for web output instance
817 * @return $webOutputInstance - Instance to class WebOutput
819 public final function getWebOutputInstance () {
820 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
821 return $webOutputInstance;
825 * Setter for database instance
827 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
830 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
831 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
835 * Getter for database layer
837 * @return $databaseInstance The database layer instance
839 public final function getDatabaseInstance () {
841 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
844 return $databaseInstance;
848 * Setter for compressor channel
850 * @param $compressorInstance An instance of CompressorChannel
853 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
854 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
858 * Getter for compressor channel
860 * @return $compressorInstance The compressor channel
862 public final function getCompressorChannel () {
863 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
864 return $compressorInstance;
868 * Protected getter for a manageable application helper class
870 * @return $applicationInstance An instance of a manageable application helper class
872 protected final function getApplicationInstance () {
873 $applicationInstance = Registry::getRegistry()->getInstance('application');
874 return $applicationInstance;
878 * Setter for a manageable application helper class
880 * @param $applicationInstance An instance of a manageable application helper class
883 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
884 Registry::getRegistry()->addInstance('application', $applicationInstance);
888 * Setter for request instance
890 * @param $requestInstance An instance of a Requestable class
893 public final function setRequestInstance (Requestable $requestInstance) {
894 $this->requestInstance = $requestInstance;
898 * Getter for request instance
900 * @return $requestInstance An instance of a Requestable class
902 public final function getRequestInstance () {
903 return $this->requestInstance;
907 * Setter for response instance
909 * @param $responseInstance An instance of a Responseable class
912 public final function setResponseInstance (Responseable $responseInstance) {
913 $this->responseInstance = $responseInstance;
917 * Getter for response instance
919 * @return $responseInstance An instance of a Responseable class
921 public final function getResponseInstance () {
922 return $this->responseInstance;
926 * Private getter for language instance
928 * @return $langInstance An instance to the language sub-system
930 protected final function getLanguageInstance () {
931 $langInstance = Registry::getRegistry()->getInstance('language');
932 return $langInstance;
936 * Setter for language instance
938 * @param $langInstance An instance to the language sub-system
940 * @see LanguageSystem
942 public final function setLanguageInstance (ManageableLanguage $langInstance) {
943 Registry::getRegistry()->addInstance('language', $langInstance);
947 * Private getter for file IO instance
949 * @return $fileIoInstance An instance to the file I/O sub-system
951 protected final function getFileIoInstance () {
952 return $this->fileIoInstance;
956 * Setter for file I/O instance
958 * @param $fileIoInstance An instance to the file I/O sub-system
961 public final function setFileIoInstance (IoHandler $fileIoInstance) {
962 $this->fileIoInstance = $fileIoInstance;
966 * Protected setter for user instance
968 * @param $userInstance An instance of a user class
971 protected final function setUserInstance (ManageableAccount $userInstance) {
972 $this->userInstance = $userInstance;
976 * Getter for user instance
978 * @return $userInstance An instance of a user class
980 public final function getUserInstance () {
981 return $this->userInstance;
985 * Setter for controller instance (this surely breaks a bit the MVC patterm)
987 * @param $controllerInstance An instance of the controller
990 public final function setControllerInstance (Controller $controllerInstance) {
991 $this->controllerInstance = $controllerInstance;
995 * Getter for controller instance (this surely breaks a bit the MVC patterm)
997 * @return $controllerInstance An instance of the controller
999 public final function getControllerInstance () {
1000 return $this->controllerInstance;
1004 * Setter for RNG instance
1006 * @param $rngInstance An instance of a random number generator (RNG)
1009 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1010 $this->rngInstance = $rngInstance;
1014 * Getter for RNG instance
1016 * @return $rngInstance An instance of a random number generator (RNG)
1018 public final function getRngInstance () {
1019 return $this->rngInstance;
1023 * Setter for Cryptable instance
1025 * @param $cryptoInstance An instance of a Cryptable class
1028 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1029 $this->cryptoInstance = $cryptoInstance;
1033 * Getter for Cryptable instance
1035 * @return $cryptoInstance An instance of a Cryptable class
1037 public final function getCryptoInstance () {
1038 return $this->cryptoInstance;
1042 * Setter for the list instance
1044 * @param $listInstance A list of Listable
1047 protected final function setListInstance (Listable $listInstance) {
1048 $this->listInstance = $listInstance;
1052 * Getter for the list instance
1054 * @return $listInstance A list of Listable
1056 protected final function getListInstance () {
1057 return $this->listInstance;
1061 * Setter for the menu instance
1063 * @param $menuInstance A RenderableMenu instance
1066 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1067 $this->menuInstance = $menuInstance;
1071 * Getter for the menu instance
1073 * @return $menuInstance A RenderableMenu instance
1075 protected final function getMenuInstance () {
1076 return $this->menuInstance;
1080 * Setter for image instance
1082 * @param $imageInstance An instance of an image
1085 public final function setImageInstance (BaseImage $imageInstance) {
1086 $this->imageInstance = $imageInstance;
1090 * Getter for image instance
1092 * @return $imageInstance An instance of an image
1094 public final function getImageInstance () {
1095 return $this->imageInstance;
1099 * Setter for stacker instance
1101 * @param $stackInstance An instance of an stacker
1104 public final function setStackInstance (Stackable $stackInstance) {
1105 $this->stackInstance = $stackInstance;
1109 * Getter for stacker instance
1111 * @return $stackInstance An instance of an stacker
1113 public final function getStackInstance () {
1114 return $this->stackInstance;
1118 * Setter for compressor instance
1120 * @param $compressorInstance An instance of an compressor
1123 public final function setCompressorInstance (Compressor $compressorInstance) {
1124 $this->compressorInstance = $compressorInstance;
1128 * Getter for compressor instance
1130 * @return $compressorInstance An instance of an compressor
1132 public final function getCompressorInstance () {
1133 return $this->compressorInstance;
1137 * Setter for Parseable instance
1139 * @param $parserInstance An instance of an Parseable
1142 public final function setParserInstance (Parseable $parserInstance) {
1143 $this->parserInstance = $parserInstance;
1147 * Getter for Parseable instance
1149 * @return $parserInstance An instance of an Parseable
1151 public final function getParserInstance () {
1152 return $this->parserInstance;
1156 * Setter for HandleableProtocol instance
1158 * @param $protocolInstance An instance of an HandleableProtocol
1161 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1162 $this->protocolInstance = $protocolInstance;
1166 * Getter for HandleableProtocol instance
1168 * @return $protocolInstance An instance of an HandleableProtocol
1170 public final function getProtocolInstance () {
1171 return $this->protocolInstance;
1175 * Setter for DatabaseWrapper instance
1177 * @param $wrapperInstance An instance of an DatabaseWrapper
1180 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1181 $this->wrapperInstance = $wrapperInstance;
1185 * Getter for DatabaseWrapper instance
1187 * @return $wrapperInstance An instance of an DatabaseWrapper
1189 public final function getWrapperInstance () {
1190 return $this->wrapperInstance;
1194 * Setter for socket resource
1196 * @param $socketResource A valid socket resource
1199 public final function setSocketResource ($socketResource) {
1200 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1201 $this->socketResource = $socketResource;
1205 * Getter for socket resource
1207 * @return $socketResource A valid socket resource
1209 public final function getSocketResource () {
1210 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1211 return $this->socketResource;
1215 * Setter for regular expression
1217 * @param $regularExpression A valid regular expression
1220 public final function setRegularExpression ($regularExpression) {
1221 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1222 $this->regularExpression = $regularExpression;
1226 * Getter for regular expression
1228 * @return $regularExpression A valid regular expression
1230 public final function getRegularExpression () {
1231 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1232 return $this->regularExpression;
1236 * Setter for helper instance
1238 * @param $helperInstance An instance of a helper class
1241 protected final function setHelperInstance (Helper $helperInstance) {
1242 $this->helperInstance = $helperInstance;
1246 * Getter for helper instance
1248 * @return $helperInstance An instance of a helper class
1250 public final function getHelperInstance () {
1251 return $this->helperInstance;
1255 * Setter for a Source instance
1257 * @param $sourceInstance An instance of a Source class
1260 protected final function setSourceInstance (Source $sourceInstance) {
1261 $this->sourceInstance = $sourceInstance;
1265 * Getter for a Source instance
1267 * @return $sourceInstance An instance of a Source class
1269 protected final function getSourceInstance () {
1270 return $this->sourceInstance;
1274 * Setter for a UrlSource instance
1276 * @param $sourceInstance An instance of a UrlSource class
1279 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1280 $this->urlSourceInstance = $urlSourceInstance;
1284 * Getter for a UrlSource instance
1286 * @return $urlSourceInstance An instance of a UrlSource class
1288 protected final function getUrlSourceInstance () {
1289 return $this->urlSourceInstance;
1293 * Getter for a InputStream instance
1295 * @param $inputStreamInstance The InputStream instance
1297 protected final function getInputStreamInstance () {
1298 return $this->inputStreamInstance;
1302 * Setter for a InputStream instance
1304 * @param $inputStreamInstance The InputStream instance
1307 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1308 $this->inputStreamInstance = $inputStreamInstance;
1312 * Getter for a OutputStream instance
1314 * @param $outputStreamInstance The OutputStream instance
1316 protected final function getOutputStreamInstance () {
1317 return $this->outputStreamInstance;
1321 * Setter for a OutputStream instance
1323 * @param $outputStreamInstance The OutputStream instance
1326 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1327 $this->outputStreamInstance = $outputStreamInstance;
1331 * Setter for handler instance
1333 * @param $handlerInstance An instance of a Handleable class
1336 protected final function setHandlerInstance (Handleable $handlerInstance) {
1337 $this->handlerInstance = $handlerInstance;
1341 * Getter for handler instance
1343 * @return $handlerInstance A Networkable instance
1345 protected final function getHandlerInstance () {
1346 return $this->handlerInstance;
1350 * Setter for visitor instance
1352 * @param $visitorInstance A Visitor instance
1355 protected final function setVisitorInstance (Visitor $visitorInstance) {
1356 $this->visitorInstance = $visitorInstance;
1360 * Getter for visitor instance
1362 * @return $visitorInstance A Visitor instance
1364 protected final function getVisitorInstance () {
1365 return $this->visitorInstance;
1369 * Setter for DHT instance
1371 * @param $dhtInstance A Distributable instance
1374 protected final function setDhtInstance (Distributable $dhtInstance) {
1375 $this->dhtInstance = $dhtInstance;
1379 * Getter for DHT instance
1381 * @return $dhtInstance A Distributable instance
1383 protected final function getDhtInstance () {
1384 return $this->dhtInstance;
1388 * Setter for raw package Data
1390 * @param $packageData Raw package Data
1393 public final function setPackageData (array $packageData) {
1394 $this->packageData = $packageData;
1398 * Getter for raw package Data
1400 * @return $packageData Raw package Data
1402 public function getPackageData () {
1403 return $this->packageData;
1408 * Setter for Iterator instance
1410 * @param $iteratorInstance An instance of an Iterator
1413 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1414 $this->iteratorInstance = $iteratorInstance;
1418 * Getter for Iterator instance
1420 * @return $iteratorInstance An instance of an Iterator
1422 public final function getIteratorInstance () {
1423 return $this->iteratorInstance;
1427 * Setter for FilePointer instance
1429 * @param $pointerInstance An instance of an FilePointer class
1432 protected final function setPointerInstance (FilePointer $pointerInstance) {
1433 $this->pointerInstance = $pointerInstance;
1437 * Getter for FilePointer instance
1439 * @return $pointerInstance An instance of an FilePointer class
1441 public final function getPointerInstance () {
1442 return $this->pointerInstance;
1446 * Unsets pointer instance which triggers a call of __destruct() if the
1447 * instance is still there. This is surely not fatal on already "closed"
1448 * file pointer instances.
1450 * I don't want to mess around with above setter by giving it a default
1451 * value NULL as setter should always explicitly only set (existing) object
1452 * instances and NULL is NULL.
1456 protected final function unsetPointerInstance () {
1457 // Simply it to NULL
1458 $this->pointerInstance = NULL;
1462 * Setter for Indexable instance
1464 * @param $indexInstance An instance of an Indexable class
1467 protected final function setIndexInstance (Indexable $indexInstance) {
1468 $this->indexInstance = $indexInstance;
1472 * Getter for Indexable instance
1474 * @return $indexInstance An instance of an Indexable class
1476 public final function getIndexInstance () {
1477 return $this->indexInstance;
1481 * Setter for Block instance
1483 * @param $blockInstance An instance of an Block class
1486 protected final function setBlockInstance (Block $blockInstance) {
1487 $this->blockInstance = $blockInstance;
1491 * Getter for Block instance
1493 * @return $blockInstance An instance of an Block class
1495 public final function getBlockInstance () {
1496 return $this->blockInstance;
1500 * Setter for Minable instance
1502 * @param $minableInstance A Minable instance
1505 protected final function setMinableInstance (Minable $minableInstance) {
1506 $this->minableInstance = $minableInstance;
1510 * Getter for minable instance
1512 * @return $minableInstance A Minable instance
1514 protected final function getMinableInstance () {
1515 return $this->minableInstance;
1519 * Setter for FrameworkDirectory instance
1521 * @param $directoryInstance A FrameworkDirectoryPointer instance
1524 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1525 $this->directoryInstance = $directoryInstance;
1529 * Getter for FrameworkDirectory instance
1531 * @return $directoryInstance A FrameworkDirectory instance
1533 protected final function getDirectoryInstance () {
1534 return $this->directoryInstance;
1538 * Setter for listener instance
1540 * @param $listenerInstance A Listenable instance
1543 protected final function setListenerInstance (Listenable $listenerInstance) {
1544 $this->listenerInstance = $listenerInstance;
1548 * Getter for listener instance
1550 * @return $listenerInstance A Listenable instance
1552 protected final function getListenerInstance () {
1553 return $this->listenerInstance;
1557 * Getter for communicator instance
1559 * @return $communicatorInstance An instance of a Communicator class
1561 public final function getCommunicatorInstance () {
1562 return $this->communicatorInstance;
1566 * Setter for communicator instance
1568 * @param $communicatorInstance An instance of a Communicator class
1571 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1572 $this->communicatorInstance = $communicatorInstance;
1576 * Setter for state instance
1578 * @param $stateInstance A Stateable instance
1581 public final function setStateInstance (Stateable $stateInstance) {
1582 $this->stateInstance = $stateInstance;
1586 * Getter for state instance
1588 * @return $stateInstance A Stateable instance
1590 public final function getStateInstance () {
1591 return $this->stateInstance;
1595 * Setter for output instance
1597 * @param $outputInstance The debug output instance
1600 public final function setOutputInstance (OutputStreamer $outputInstance) {
1601 $this->outputInstance = $outputInstance;
1605 * Getter for output instance
1607 * @return $outputInstance The debug output instance
1609 public final function getOutputInstance () {
1610 return $this->outputInstance;
1614 * Setter for command name
1616 * @param $commandName Last validated command name
1619 protected final function setCommandName ($commandName) {
1620 $this->commandName = $commandName;
1624 * Getter for command name
1626 * @return $commandName Last validated command name
1628 protected final function getCommandName () {
1629 return $this->commandName;
1633 * Setter for controller name
1635 * @param $controllerName Last validated controller name
1638 protected final function setControllerName ($controllerName) {
1639 $this->controllerName = $controllerName;
1643 * Getter for controller name
1645 * @return $controllerName Last validated controller name
1647 protected final function getControllerName () {
1648 return $this->controllerName;
1652 * Getter for protocol name
1654 * @return $protocolName Name of used protocol
1656 public final function getProtocolName () {
1657 return $this->protocolName;
1661 * Setter for protocol name
1663 * @param $protocolName Name of used protocol
1666 protected final function setProtocolName ($protocolName) {
1667 $this->protocolName = $protocolName;
1671 * Checks whether an object equals this object. You should overwrite this
1672 * method to implement own equality checks
1674 * @param $objectInstance An instance of a FrameworkInterface object
1675 * @return $equals Whether both objects equals
1677 public function equals (FrameworkInterface $objectInstance) {
1680 $this->__toString() == $objectInstance->__toString()
1682 $this->hashCode() == $objectInstance->hashCode()
1685 // Return the result
1690 * Generates a generic hash code of this class. You should really overwrite
1691 * this method with your own hash code generator code. But keep KISS in mind.
1693 * @return $hashCode A generic hash code respresenting this whole class
1695 public function hashCode () {
1697 return crc32($this->__toString());
1701 * Formats computer generated price values into human-understandable formats
1702 * with thousand and decimal separators.
1704 * @param $value The in computer format value for a price
1705 * @param $currency The currency symbol (use HTML-valid characters!)
1706 * @param $decNum Number of decimals after commata
1707 * @return $price The for the current language formated price string
1708 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1709 * thousands separator
1712 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1713 // Are all required attriutes set?
1714 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1715 // Throw an exception
1716 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1720 $value = (float) $value;
1722 // Reformat the US number
1723 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1725 // Return as string...
1730 * Appends a trailing slash to a string
1732 * @param $str A string (maybe) without trailing slash
1733 * @return $str A string with an auto-appended trailing slash
1735 public final function addMissingTrailingSlash ($str) {
1736 // Is there a trailing slash?
1737 if (substr($str, -1, 1) != '/') {
1741 // Return string with trailing slash
1746 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1747 * application helper instance (ApplicationHelper by default).
1749 * @param $applicationInstance An application helper instance or
1750 * null if we shall use the default
1751 * @return $templateInstance The template engine instance
1752 * @throws NullPointerException If the discovered application
1753 * instance is still null
1755 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1756 // Is the application instance set?
1757 if (is_null($applicationInstance)) {
1758 // Get the current instance
1759 $applicationInstance = $this->getApplicationInstance();
1762 if (is_null($applicationInstance)) {
1763 // Thrown an exception
1764 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1768 // Initialize the template engine
1769 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1771 // Return the prepared instance
1772 return $templateInstance;
1776 * Debugs this instance by putting out it's full content
1778 * @param $message Optional message to show in debug output
1781 public final function debugInstance ($message = '') {
1782 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1783 restore_error_handler();
1788 // Is a message set?
1789 if (!empty($message)) {
1790 // Construct message
1791 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1794 // Generate the output
1795 $content .= sprintf('<pre>%s</pre>',
1798 print_r($this, TRUE)
1804 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>',
1805 $this->__toString(),
1807 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1812 * Replaces control characters with printable output
1814 * @param $str String with control characters
1815 * @return $str Replaced string
1817 protected function replaceControlCharacters ($str) {
1820 chr(13), '[r]', str_replace(
1821 chr(10), '[n]', str_replace(
1831 * Output a partial stub message for the caller method
1833 * @param $message An optional message to display
1836 protected function partialStub ($message = '') {
1837 // Get the backtrace
1838 $backtrace = debug_backtrace();
1840 // Generate the class::method string
1841 $methodName = 'UnknownClass->unknownMethod';
1842 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1843 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1846 // Construct the full message
1847 $stubMessage = sprintf('[%s:] Partial stub!',
1851 // Is the extra message given?
1852 if (!empty($message)) {
1853 // Then add it as well
1854 $stubMessage .= ' Message: ' . $message;
1857 // Debug instance is there?
1858 if (!is_null($this->getDebugInstance())) {
1859 // Output stub message
1860 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1863 trigger_error($stubMessage);
1869 * Outputs a debug backtrace and stops further script execution
1871 * @param $message An optional message to output
1872 * @param $doExit Whether exit the program (TRUE is default)
1875 public function debugBackTrace ($message = '', $doExit = TRUE) {
1876 // Sorry, there is no other way getting this nice backtrace
1877 if (!empty($message)) {
1879 printf('Message: %s<br />' . PHP_EOL, $message);
1883 debug_print_backtrace();
1887 if ($doExit === TRUE) {
1893 * Creates an instance of a debugger instance
1895 * @param $className Name of the class (currently unsupported)
1896 * @return $debugInstance An instance of a debugger class
1897 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1899 public final static function createDebugInstance ($className) {
1900 // Is the instance set?
1901 if (!Registry::getRegistry()->instanceExists('debug')) {
1902 // Init debug instance
1903 $debugInstance = NULL;
1907 // Get a debugger instance
1908 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1909 } catch (NullPointerException $e) {
1910 // Didn't work, no instance there
1911 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1914 // Empty string should be ignored and used for testing the middleware
1915 DebugMiddleware::getSelfInstance()->output('');
1917 // Set it in its own class. This will set it in the registry
1918 $debugInstance->setDebugInstance($debugInstance);
1920 // Get instance from registry
1921 $debugInstance = Registry::getRegistry()->getDebugInstance();
1925 return $debugInstance;
1929 * Simple output of a message with line-break
1931 * @param $message Message to output
1934 public function outputLine ($message) {
1936 print($message . PHP_EOL);
1940 * Outputs a debug message whether to debug instance (should be set!) or
1941 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1942 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1944 * @param $message Message we shall send out...
1945 * @param $doPrint Whether print or die here (default: print)
1946 * @paran $stripTags Whether to strip tags (default: FALSE)
1949 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1950 // Set debug instance to NULL
1951 $debugInstance = NULL;
1955 // Get debug instance
1956 $debugInstance = $this->getDebugInstance();
1957 } catch (NullPointerException $e) {
1958 // The debug instance is not set (yet)
1961 // Is the debug instance there?
1962 if (is_object($debugInstance)) {
1963 // Use debug output handler
1964 $debugInstance->output($message, $stripTags);
1966 if ($doPrint === FALSE) {
1967 // Die here if not printed
1971 // Are debug times enabled?
1972 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1974 $message = $this->getPrintableExecutionTime() . $message;
1978 if ($doPrint === TRUE) {
1980 $this->outputLine($message);
1989 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1991 * @param $str The string, what ever it is needs to be converted
1992 * @return $className Generated class name
1994 public static final function convertToClassName ($str) {
1998 // Convert all dashes in underscores
1999 $str = self::convertDashesToUnderscores($str);
2001 // Now use that underscores to get classname parts for hungarian style
2002 foreach (explode('_', $str) as $strPart) {
2003 // Make the class name part lower case and first upper case
2004 $className .= ucfirst(strtolower($strPart));
2007 // Return class name
2012 * Converts dashes to underscores, e.g. useable for configuration entries
2014 * @param $str The string with maybe dashes inside
2015 * @return $str The converted string with no dashed, but underscores
2017 public static final function convertDashesToUnderscores ($str) {
2019 $str = str_replace('-', '_', $str);
2021 // Return converted string
2026 * Marks up the code by adding e.g. line numbers
2028 * @param $phpCode Unmarked PHP code
2029 * @return $markedCode Marked PHP code
2031 public function markupCode ($phpCode) {
2036 $errorArray = error_get_last();
2038 // Init the code with error message
2039 if (is_array($errorArray)) {
2041 $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>',
2042 basename($errorArray['file']),
2043 $errorArray['line'],
2044 $errorArray['message'],
2049 // Add line number to the code
2050 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2052 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2054 htmlentities($code, ENT_QUOTES)
2063 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2064 * beatiful for web-based front-ends. If null is given a message id
2065 * null_timestamp will be resolved and returned.
2067 * @param $timestamp Timestamp to prepare (filter) for display
2068 * @return $readable A readable timestamp
2070 public function doFilterFormatTimestamp ($timestamp) {
2071 // Default value to return
2074 // Is the timestamp null?
2075 if (is_null($timestamp)) {
2076 // Get a message string
2077 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2079 switch ($this->getLanguageInstance()->getLanguageCode()) {
2080 case 'de': // German format is a bit different to default
2081 // Split the GMT stamp up
2082 $dateTime = explode(' ', $timestamp );
2083 $dateArray = explode('-', $dateTime[0]);
2084 $timeArray = explode(':', $dateTime[1]);
2086 // Construct the timestamp
2087 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2097 default: // Default is pass-through
2098 $readable = $timestamp;
2108 * Filter a given number into a localized number
2110 * @param $value The raw value from e.g. database
2111 * @return $localized Localized value
2113 public function doFilterFormatNumber ($value) {
2114 // Generate it from config and localize dependencies
2115 switch ($this->getLanguageInstance()->getLanguageCode()) {
2116 case 'de': // German format is a bit different to default
2117 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2120 default: // US, etc.
2121 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2130 * "Getter" for databse entry
2132 * @return $entry An array with database entries
2133 * @throws NullPointerException If the database result is not found
2134 * @throws InvalidDatabaseResultException If the database result is invalid
2136 protected final function getDatabaseEntry () {
2137 // Is there an instance?
2138 if (!$this->getResultInstance() instanceof SearchableResult) {
2139 // Throw an exception here
2140 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2144 $this->getResultInstance()->rewind();
2146 // Do we have an entry?
2147 if ($this->getResultInstance()->valid() === FALSE) {
2148 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2149 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2153 $this->getResultInstance()->next();
2156 $entry = $this->getResultInstance()->current();
2163 * Getter for field name
2165 * @param $fieldName Field name which we shall get
2166 * @return $fieldValue Field value from the user
2167 * @throws NullPointerException If the result instance is null
2169 public final function getField ($fieldName) {
2170 // Default field value
2173 // Get result instance
2174 $resultInstance = $this->getResultInstance();
2176 // Is this instance null?
2177 if (is_null($resultInstance)) {
2178 // Then the user instance is no longer valid (expired cookies?)
2179 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2182 // Get current array
2183 $fieldArray = $resultInstance->current();
2184 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2186 // Convert dashes to underscore
2187 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2189 // Does the field exist?
2190 if ($this->isFieldSet($fieldName)) {
2192 $fieldValue = $fieldArray[$fieldName2];
2193 } elseif (defined('DEVELOPER')) {
2194 // Missing field entry, may require debugging
2195 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2197 // Missing field entry, may require debugging
2198 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2206 * Checks if given field is set
2208 * @param $fieldName Field name to check
2209 * @return $isSet Whether the given field name is set
2210 * @throws NullPointerException If the result instance is null
2212 public function isFieldSet ($fieldName) {
2213 // Get result instance
2214 $resultInstance = $this->getResultInstance();
2216 // Is this instance null?
2217 if (is_null($resultInstance)) {
2218 // Then the user instance is no longer valid (expired cookies?)
2219 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2222 // Get current array
2223 $fieldArray = $resultInstance->current();
2224 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2226 // Convert dashes to underscore
2227 $fieldName = self::convertDashesToUnderscores($fieldName);
2230 $isSet = isset($fieldArray[$fieldName]);
2237 * Flushs all pending updates to the database layer
2241 public function flushPendingUpdates () {
2242 // Get result instance
2243 $resultInstance = $this->getResultInstance();
2245 // Do we have data to update?
2246 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2247 // Get wrapper class name config entry
2248 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2250 // Create object instance
2251 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2253 // Yes, then send the whole result to the database layer
2254 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2259 * Outputs a deprecation warning to the developer.
2261 * @param $message The message we shall output to the developer
2263 * @todo Write a logging mechanism for productive mode
2265 public function deprecationWarning ($message) {
2266 // Is developer mode active?
2267 if (defined('DEVELOPER')) {
2268 // Debug instance is there?
2269 if (!is_null($this->getDebugInstance())) {
2270 // Output stub message
2271 self::createDebugInstance(__CLASS__)->debugOutput($message);
2274 trigger_error($message . "<br />\n");
2278 // @TODO Finish this part!
2279 $this->partialStub('Developer mode inactive. Message:' . $message);
2284 * Checks whether the given PHP extension is loaded
2286 * @param $phpExtension The PHP extension we shall check
2287 * @return $isLoaded Whether the PHP extension is loaded
2289 public final function isPhpExtensionLoaded ($phpExtension) {
2291 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2298 * "Getter" as a time() replacement but with milliseconds. You should use this
2299 * method instead of the encapsulated getimeofday() function.
2301 * @return $milliTime Timestamp with milliseconds
2303 public function getMilliTime () {
2304 // Get the time of day as float
2305 $milliTime = gettimeofday(TRUE);
2312 * Idles (sleeps) for given milliseconds
2314 * @return $hasSlept Whether it goes fine
2316 public function idle ($milliSeconds) {
2317 // Sleep is fine by default
2320 // Idle so long with found function
2321 if (function_exists('time_sleep_until')) {
2322 // Get current time and add idle time
2323 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2325 // New PHP 5.1.0 function found, ignore errors
2326 $hasSlept = @time_sleep_until($sleepUntil);
2329 * My Sun station doesn't have that function even with latest PHP
2332 usleep($milliSeconds * 1000);
2339 * Converts a hexadecimal string, even with negative sign as first string to
2340 * a decimal number using BC functions.
2342 * This work is based on comment #86673 on php.net documentation page at:
2343 * <http://de.php.net/manual/en/function.dechex.php#86673>
2345 * @param $hex Hexadecimal string
2346 * @return $dec Decimal number
2348 protected function hex2dec ($hex) {
2349 // Convert to all lower-case
2350 $hex = strtolower($hex);
2352 // Detect sign (negative/positive numbers)
2354 if (substr($hex, 0, 1) == '-') {
2356 $hex = substr($hex, 1);
2359 // Decode the hexadecimal string into a decimal number
2361 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2362 $factor = self::$hexdec[substr($hex, $i, 1)];
2363 $dec = bcadd($dec, bcmul($factor, $e));
2366 // Return the decimal number
2367 return $sign . $dec;
2371 * Converts even very large decimal numbers, also signed, to a hexadecimal
2374 * This work is based on comment #97756 on php.net documentation page at:
2375 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2377 * @param $dec Decimal number, even with negative sign
2378 * @param $maxLength Optional maximum length of the string
2379 * @return $hex Hexadecimal string
2381 protected function dec2hex ($dec, $maxLength = 0) {
2382 // maxLength can be zero or devideable by 2
2383 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2385 // Detect sign (negative/positive numbers)
2392 // Encode the decimal number into a hexadecimal string
2395 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2397 } while ($dec >= 1);
2400 * Leading zeros are required for hex-decimal "numbers". In some
2401 * situations more leading zeros are wanted, so check for both
2404 if ($maxLength > 0) {
2405 // Prepend more zeros
2406 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2407 } elseif ((strlen($hex) % 2) != 0) {
2408 // Only make string's length dividable by 2
2412 // Return the hexadecimal string
2413 return $sign . $hex;
2417 * Converts a ASCII string (0 to 255) into a decimal number.
2419 * @param $asc The ASCII string to be converted
2420 * @return $dec Decimal number
2422 protected function asc2dec ($asc) {
2423 // Convert it into a hexadecimal number
2424 $hex = bin2hex($asc);
2426 // And back into a decimal number
2427 $dec = $this->hex2dec($hex);
2434 * Converts a decimal number into an ASCII string.
2436 * @param $dec Decimal number
2437 * @return $asc An ASCII string
2439 protected function dec2asc ($dec) {
2440 // First convert the number into a hexadecimal string
2441 $hex = $this->dec2hex($dec);
2443 // Then convert it into the ASCII string
2444 $asc = $this->hex2asc($hex);
2451 * Converts a hexadecimal number into an ASCII string. Negative numbers
2454 * @param $hex Hexadecimal string
2455 * @return $asc An ASCII string
2457 protected function hex2asc ($hex) {
2458 // Check for length, it must be devideable by 2
2459 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2460 assert((strlen($hex) % 2) == 0);
2464 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2465 // Get the decimal number of the chunk
2466 $part = hexdec(substr($hex, $idx, 2));
2468 // Add it to the final string
2472 // Return the final string
2477 * Checks whether the given encoded data was encoded with Base64
2479 * @param $encodedData Encoded data we shall check
2480 * @return $isBase64 Whether the encoded data is Base64
2482 protected function isBase64Encoded ($encodedData) {
2484 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2491 * "Getter" to get response/request type from analysis of the system.
2493 * @return $responseType Analyzed response type
2495 protected static function getResponseTypeFromSystem () {
2496 // Default is console
2497 $responseType = 'console';
2499 // Is 'HTTP_HOST' set?
2500 if (isset($_SERVER['HTTP_HOST'])) {
2502 * Then it is a HTML response/request as RSS and so on may be
2503 * transfered over HTTP as well.
2505 $responseType = 'html';
2509 return $responseType;
2513 * Gets a cache key from Criteria instance
2515 * @param $criteriaInstance An instance of a Criteria class
2516 * @param $onlyKeys Only use these keys for a cache key
2517 * @return $cacheKey A cache key suitable for lookup/storage purposes
2519 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2521 $cacheKey = sprintf('%s@%s',
2522 $this->__toString(),
2523 $criteriaInstance->getCacheKey($onlyKeys)
2527 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2532 * Getter for startup time in miliseconds
2534 * @return $startupTime Startup time in miliseconds
2536 protected function getStartupTime () {
2537 return self::$startupTime;
2541 * "Getter" for a printable currently execution time in nice braces
2543 * @return $executionTime Current execution time in nice braces
2545 protected function getPrintableExecutionTime () {
2546 // Caculate the execution time
2547 $executionTime = microtime(TRUE) - $this->getStartupTime();
2549 // Pack it in nice braces
2550 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2553 return $executionTime;
2557 * Hashes a given string with a simple but stronger hash function (no salt)
2558 * and hex-encode it.
2560 * @param $str The string to be hashed
2561 * @return $hash The hash from string $str
2563 public static final function hash ($str) {
2564 // Hash given string with (better secure) hasher
2565 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2572 * "Getter" for length of hash() output. This will be "cached" to speed up
2575 * @return $length Length of hash() output
2577 public static final function getHashLength () {
2579 if (is_null(self::$hashLength)) {
2580 // No, then hash a string and save its length.
2581 self::$hashLength = strlen(self::hash('abc123'));
2585 return self::$hashLength;
2589 * Checks whether the given number is really a number (only chars 0-9).
2591 * @param $num A string consisting only chars between 0 and 9
2592 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2593 * @param $assertMismatch Whether to assert mismatches
2594 * @return $ret The (hopefully) secured numbered value
2596 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2597 // Filter all numbers out
2598 $ret = preg_replace('/[^0123456789]/', '', $num);
2601 if ($castValue === TRUE) {
2602 // Cast to biggest numeric type
2603 $ret = (double) $ret;
2606 // Assert only if requested
2607 if ($assertMismatch === TRUE) {
2608 // Has the whole value changed?
2609 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2617 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2619 * @param $num A string consisting only chars between 0 and 9
2620 * @param $assertMismatch Whether to assert mismatches
2621 * @return $ret The (hopefully) secured hext-numbered value
2623 public function hexval ($num, $assertMismatch = FALSE) {
2624 // Filter all numbers out
2625 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2627 // Assert only if requested
2628 if ($assertMismatch === TRUE) {
2629 // Has the whole value changed?
2630 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2638 * Checks whether start/end marker are set
2640 * @param $data Data to be checked
2641 * @return $isset Whether start/end marker are set
2643 public final function ifStartEndMarkersSet ($data) {
2645 $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));
2647 // ... and return it
2652 * Determines if an element is set in the generic array
2654 * @param $keyGroup Main group for the key
2655 * @param $subGroup Sub group for the key
2656 * @param $key Key to check
2657 * @param $element Element to check
2658 * @return $isset Whether the given key is set
2660 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2662 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2665 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2671 * Determines if a key is set in the generic array
2673 * @param $keyGroup Main group for the key
2674 * @param $subGroup Sub group for the key
2675 * @param $key Key to check
2676 * @return $isset Whether the given key is set
2678 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2680 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2683 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2691 * Determines if a group is set in the generic array
2693 * @param $keyGroup Main group
2694 * @param $subGroup Sub group
2695 * @return $isset Whether the given group is set
2697 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2699 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2702 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2709 * Getter for sub key group
2711 * @param $keyGroup Main key group
2712 * @param $subGroup Sub key group
2713 * @return $array An array with all array elements
2715 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2717 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2718 // No, then abort here
2719 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2724 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2727 return $this->genericArray[$keyGroup][$subGroup];
2731 * Unsets a given key in generic array
2733 * @param $keyGroup Main group for the key
2734 * @param $subGroup Sub group for the key
2735 * @param $key Key to unset
2738 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2740 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2743 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2747 * Unsets a given element in generic array
2749 * @param $keyGroup Main group for the key
2750 * @param $subGroup Sub group for the key
2751 * @param $key Key to unset
2752 * @param $element Element to unset
2755 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2757 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2760 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2764 * Append a string to a given generic array key
2766 * @param $keyGroup Main group for the key
2767 * @param $subGroup Sub group for the key
2768 * @param $key Key to unset
2769 * @param $value Value to add/append
2772 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2774 //* 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);
2776 // Is it already there?
2777 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2779 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2782 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2787 * Append a string to a given generic array element
2789 * @param $keyGroup Main group for the key
2790 * @param $subGroup Sub group for the key
2791 * @param $key Key to unset
2792 * @param $element Element to check
2793 * @param $value Value to add/append
2796 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2798 //* 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);
2800 // Is it already there?
2801 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2803 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2806 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2811 * Sets a string in a given generic array element
2813 * @param $keyGroup Main group for the key
2814 * @param $subGroup Sub group for the key
2815 * @param $key Key to unset
2816 * @param $element Element to check
2817 * @param $value Value to add/append
2820 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2822 //* 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);
2825 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2829 * Initializes given generic array group
2831 * @param $keyGroup Main group for the key
2832 * @param $subGroup Sub group for the key
2833 * @param $key Key to use
2834 * @param $forceInit Optionally force initialization
2837 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2839 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2841 // Is it already set?
2842 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2843 // Already initialized
2844 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2849 $this->genericArray[$keyGroup][$subGroup] = array();
2853 * Initializes given generic array key
2855 * @param $keyGroup Main group for the key
2856 * @param $subGroup Sub group for the key
2857 * @param $key Key to use
2858 * @param $forceInit Optionally force initialization
2861 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2863 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2865 // Is it already set?
2866 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2867 // Already initialized
2868 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2873 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2877 * Initializes given generic array element
2879 * @param $keyGroup Main group for the key
2880 * @param $subGroup Sub group for the key
2881 * @param $key Key to use
2882 * @param $element Element to use
2883 * @param $forceInit Optionally force initialization
2886 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2888 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2890 // Is it already set?
2891 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2892 // Already initialized
2893 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2898 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2902 * Pushes an element to a generic key
2904 * @param $keyGroup Main group for the key
2905 * @param $subGroup Sub group for the key
2906 * @param $key Key to use
2907 * @param $value Value to add/append
2908 * @return $count Number of array elements
2910 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2912 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2915 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2917 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2921 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2924 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2925 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2930 * Pushes an element to a generic array element
2932 * @param $keyGroup Main group for the key
2933 * @param $subGroup Sub group for the key
2934 * @param $key Key to use
2935 * @param $element Element to check
2936 * @param $value Value to add/append
2937 * @return $count Number of array elements
2939 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2941 //* 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));
2944 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2946 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2950 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2953 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2954 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2959 * Pops an element from a generic group
2961 * @param $keyGroup Main group for the key
2962 * @param $subGroup Sub group for the key
2963 * @param $key Key to unset
2964 * @return $value Last "popped" value
2966 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2968 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2971 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2973 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2978 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2981 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2982 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2987 * Shifts an element from a generic group
2989 * @param $keyGroup Main group for the key
2990 * @param $subGroup Sub group for the key
2991 * @param $key Key to unset
2992 * @return $value Last "popped" value
2994 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2996 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2999 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3001 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3006 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3009 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3010 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3015 * Count generic array group
3017 * @param $keyGroup Main group for the key
3018 * @return $count Count of given group
3020 protected final function countGenericArray ($keyGroup) {
3022 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3025 if (!isset($this->genericArray[$keyGroup])) {
3027 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3032 $count = count($this->genericArray[$keyGroup]);
3035 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3042 * Count generic array sub group
3044 * @param $keyGroup Main group for the key
3045 * @param $subGroup Sub group for the key
3046 * @return $count Count of given group
3048 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3050 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3053 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3055 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3060 $count = count($this->genericArray[$keyGroup][$subGroup]);
3063 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3070 * Count generic array elements
3072 * @param $keyGroup Main group for the key
3073 * @param $subGroup Sub group for the key
3074 * @para $key Key to count
3075 * @return $count Count of given key
3077 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3079 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3082 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3084 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3086 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3088 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3093 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3096 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3103 * Getter for whole generic group array
3105 * @param $keyGroup Key group to get
3106 * @return $array Whole generic array group
3108 protected final function getGenericArray ($keyGroup) {
3110 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3113 if (!isset($this->genericArray[$keyGroup])) {
3115 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3120 return $this->genericArray[$keyGroup];
3124 * Setter for generic array key
3126 * @param $keyGroup Key group to get
3127 * @param $subGroup Sub group for the key
3128 * @param $key Key to unset
3129 * @param $value Mixed value from generic array element
3132 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3134 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3137 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3141 * Getter for generic array key
3143 * @param $keyGroup Key group to get
3144 * @param $subGroup Sub group for the key
3145 * @param $key Key to unset
3146 * @return $value Mixed value from generic array element
3148 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3150 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3153 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3155 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3160 return $this->genericArray[$keyGroup][$subGroup][$key];
3164 * Sets a value in given generic array key/element
3166 * @param $keyGroup Main group for the key
3167 * @param $subGroup Sub group for the key
3168 * @param $key Key to set
3169 * @param $element Element to set
3170 * @param $value Value to set
3173 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3175 //* 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));
3178 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3182 * Getter for generic array element
3184 * @param $keyGroup Key group to get
3185 * @param $subGroup Sub group for the key
3186 * @param $key Key to look for
3187 * @param $element Element to look for
3188 * @return $value Mixed value from generic array element
3190 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3192 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3195 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3197 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3202 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3206 * Checks if a given sub group is valid (array)
3208 * @param $keyGroup Key group to get
3209 * @param $subGroup Sub group for the key
3210 * @return $isValid Whether given sub group is valid
3212 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3214 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3217 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3224 * Checks if a given key is valid (array)
3226 * @param $keyGroup Key group to get
3227 * @param $subGroup Sub group for the key
3228 * @param $key Key to check
3229 * @return $isValid Whether given sub group is valid
3231 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3233 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3236 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3243 * Initializes the web output instance
3247 protected function initWebOutputInstance () {
3248 // Get application instance
3249 $applicationInstance = Registry::getRegistry()->getInstance('app');
3251 // Is this a response instance?
3252 if ($this instanceof Responseable) {
3253 // Then set it in application instance
3254 $applicationInstance->setResponseInstance($this);
3257 // Init web output instance
3258 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3261 $this->setWebOutputInstance($outputInstance);
3265 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3267 * @param $boolean Boolean value
3268 * @return $translated Translated boolean value
3270 public static final function translateBooleanToYesNo ($boolean) {
3271 // Make sure it is really boolean
3272 assert(is_bool($boolean));
3275 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3277 // ... and return it
3282 * Encodes raw data (almost any type) by "serializing" it and then pack it
3283 * into a "binary format".
3285 * @param $rawData Raw data (almost any type)
3286 * @return $encoded Encoded data
3288 protected function encodeData ($rawData) {
3289 // Make sure no objects or resources pass through
3290 assert(!is_object($rawData));
3291 assert(!is_resource($rawData));
3293 // First "serialize" it (json_encode() is faster than serialize())
3294 $encoded = $this->packString(json_encode($rawData));
3301 * Pack a string into a "binary format". Please execuse me that this is
3302 * widely undocumented. :-(
3304 * @param $str Unpacked string
3305 * @return $packed Packed string
3306 * @todo Improve documentation
3308 protected function packString ($str) {
3310 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3312 // First compress the string (gzcompress is okay)
3313 $str = gzcompress($str);
3318 // And start the "encoding" loop
3319 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3321 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3322 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3324 if (($idx + $i) <= strlen($str)) {
3325 $ord = ord(substr($str, ($idx + $i), 1));
3327 $add = $ord * pow(256, $factor);
3331 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3335 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3336 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3338 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3339 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3345 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');
3350 * Checks whether the given file/path is in open_basedir(). This does not
3351 * gurantee that the file is actually readable and/or writeable. If you need
3352 * such gurantee then please use isReadableFile() instead.
3354 * @param $filePathName Name of the file/path to be checked
3355 * @return $isReachable Whether it is within open_basedir()
3357 protected static function isReachableFilePath ($filePathName) {
3358 // Is not reachable by default
3359 $isReachable = FALSE;
3361 // Get open_basedir parameter
3362 $openBaseDir = ini_get('open_basedir');
3365 if (!empty($openBaseDir)) {
3366 // Check all entries
3367 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3368 // Check on existence
3369 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3371 $isReachable = TRUE;
3375 // If open_basedir is not set, all is allowed
3376 $isReachable = TRUE;
3380 return $isReachable;
3384 * Checks whether the give file is within open_basedir() (done by
3385 * isReachableFilePath()), is actually a file and is readable.
3387 * @param $fileName Name of the file to be checked
3388 * @return $isReadable Whether the file is readable (and therefor exists)
3390 public static function isReadableFile ($fileName) {
3391 // Default is not readable
3392 $isReadable = FALSE;
3394 // Is within parameters, so check if it is a file and readable
3395 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3402 * Creates a full-qualified file name (FQFN) for given file name by adding
3403 * a configured temporary file path to it.
3405 * @param $fileName Name for temporary file
3406 * @return $fqfn Full-qualified file name
3407 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3408 * @throws FileIoException If the file cannot be written
3410 protected static function createTempPathForFile ($fileName) {
3412 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3414 // Is the path writeable?
3415 if (!is_writable($basePath)) {
3416 // Path is write-protected
3417 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3421 $fqfn = $basePath . '/' . $fileName;
3424 if (!self::isReachableFilePath($fqfn)) {
3426 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3434 * "Getter" for a printable state name
3436 * @return $stateName Name of the node's state in a printable format
3438 public final function getPrintableState () {
3439 // Default is 'null'
3440 $stateName = 'null';
3442 // Get the state instance
3443 $stateInstance = $this->getStateInstance();
3445 // Is it an instance of Stateable?
3446 if ($stateInstance instanceof Stateable) {
3447 // Then use that state name
3448 $stateName = $stateInstance->getStateName();
3456 * Handles socket error for given socket resource and peer data. This method
3457 * validates $socketResource if it is a valid resource (see is_resource())
3458 * but assumes valid data in array $recipientData, except that
3459 * count($recipientData) is always 2.
3461 * @param $method Value of __METHOD__ from calling method
3462 * @param $line Value of __LINE__ from calling method
3463 * @param $socketResource A valid socket resource
3464 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3466 * @throws InvalidSocketException If $socketResource is no socket resource
3467 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3468 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3470 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3471 // This method handles only socket resources
3472 if (!is_resource($socketResource)) {
3473 // No resource, abort here
3474 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3477 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3478 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3479 assert(isset($socketData[0]));
3480 assert(isset($socketData[1]));
3482 // Get error code for first validation (0 is not an error)
3483 $errorCode = socket_last_error($socketResource);
3485 // If the error code is zero, someone called this method without an error
3486 if ($errorCode == 0) {
3487 // No error detected (or previously cleared outside this method)
3488 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3491 // Get handler (method) name
3492 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3494 // Call-back the error handler method
3495 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3497 // Finally clear the error because it has been handled
3498 socket_clear_error($socketResource);