3 * A general hub node class
5 * @author Roland Haeder <webmaster@shipsimu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2014 Hub Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.shipsimu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class BaseHubNode extends BaseHubSystem implements Updateable, AddableCriteria {
28 const NODE_TYPE_BOOT = 'boot';
29 const NODE_TYPE_MASTER = 'master';
30 const NODE_TYPE_LIST = 'list';
31 const NODE_TYPE_REGULAR = 'regular';
33 // Exception constants
34 const EXCEPTION_HUB_ALREADY_ANNOUNCED = 0xe00;
37 const OBJECT_LIST_SEPARATOR = ',';
40 * Universal node locator of bootstrap node
42 private $bootUnl = '';
45 * Whether this node is anncounced (keep on FALSE!)
48 private $hubIsAnnounced = FALSE;
51 * Whether this hub is active (default: FALSE)
53 private $isActive = FALSE;
56 * Whether this node accepts announcements (default: FALSE)
58 private $acceptAnnouncements = FALSE;
61 * Whether this node accepts DHT bootstrap requests (default: FALSE)
63 private $acceptDhtBootstrap = FALSE;
66 * Protected constructor
68 * @param $className Name of the class
71 protected function __construct ($className) {
72 // Call parent constructor
73 parent::__construct($className);
75 // Get a wrapper instance
76 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName('node_info_db_wrapper_class');
79 $this->setWrapperInstance($wrapperInstance);
81 // Get a crypto instance
82 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
85 $this->setCryptoInstance($cryptoInstance);
87 // Init state which sets the state to 'init'
92 * Initializes the node's state which sets it to 'init'
96 private function initState() {
97 // Get the state factory and create the initial state.
98 NodeStateFactory::createNodeStateInstanceByName('init', $this);
102 * Generates a private key and hashes it (for speeding up things)
104 * @param $searchInstance An instance of a LocalSearchCriteria class
107 private function generatePrivateKeyAndHash (LocalSearchCriteria $searchInstance) {
108 // Get an RNG instance
109 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
111 // Generate a pseudo-random string
112 $randomString = $rngInstance->randomString(255);
114 // Hash and encrypt the string so we become a node id (also documented as "hub id")
115 $this->setPrivateKey($this->getCryptoInstance()->encryptString($randomString));
116 $this->setPrivateKeyHash($this->getCryptoInstance()->hashString($this->getPrivateKey()));
118 // Register the node id with our wrapper
119 $this->getWrapperInstance()->registerPrivateKey($this, $this->getRequestInstance(), $searchInstance);
122 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Created new private key with hash: ' . $this->getPrivateKeyHash() . '');
126 * Generates an UNL (Universal Node Locator) for the internal address
128 * @return $internalUnl Internal UNL
130 private function generateInternalUnl () {
132 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: CALLED!');
134 // Is there cache? (This shortens a lot calls)
135 if (!isset($GLOBALS[__METHOD__])) {
136 // Determine UNL based on this node:
137 // 1) Get discovery class
138 $discoveryInstance = ObjectFactory::createObjectByConfiguredName('unl_discovery_class');
141 $GLOBALS[__METHOD__] = $discoveryInstance->discoverUniversalNodeLocatorByConfiguredAddress('internal');
145 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: unl=' . $GLOBALS[__METHOD__] . ' - EXIT!');
146 return $GLOBALS[__METHOD__];
150 * Generates an UNL (Universal Node Locator) for the external address
152 * @return $externalUnl External UNL
154 private function generateExternalUnl () {
156 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: CALLED!');
158 // Is there cache? (This shortens a lot calls)
159 if (!isset($GLOBALS[__METHOD__])) {
160 // Determine UNL based on this node:
161 // 1) Get discovery class
162 $discoveryInstance = ObjectFactory::createObjectByConfiguredName('unl_discovery_class');
165 $GLOBALS[__METHOD__] = $discoveryInstance->discoverUniversalNodeLocatorByConfiguredAddress('external');
169 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: unl=' . $GLOBALS[__METHOD__] . ' - EXIT!');
170 return $GLOBALS[__METHOD__];
174 * Generates a random string from various data inluding UUID if PECL
175 * extension uuid is installed.
177 * @param $length Length of the random part
178 * @return $randomString Random string
179 * @todo Make this code more generic and move it to CryptoHelper or
181 protected function generateRamdomString ($length) {
182 // Get an RNG instance
183 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
185 // Generate a pseudo-random string
186 $randomString = $rngInstance->randomString($length) . ':' . $this->getBootUniversalNodeLocator() . ':' . $this->getRequestInstance()->getRequestElement('mode');
188 // Add UUID for even more entropy for the hasher
189 $randomString .= $this->getCryptoInstance()->createUuid();
192 return $randomString;
196 * Getter for boot UNL (Universal Node Locator)
198 * @return $bootUnl The UNL (Universal Node Locator) of the boot node
200 protected final function getBootUniversalNodeLocator () {
201 return $this->bootUnl;
205 * Checks whether the given IP address matches one of the bootstrap nodes
207 * @param $remoteAddr IP address to checkout against our bootstrapping list
208 * @return $isFound Whether the IP is found
210 protected function ifAddressMatchesBootstrapNodes ($remoteAddr) {
211 // By default nothing is found
214 // Run through all configured IPs
215 foreach (explode(BaseHubSystem::BOOTSTRAP_NODES_SEPARATOR, $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $unl) {
217 die(__METHOD__ . ':' . print_r($this, TRUE));
218 die(__METHOD__ . ': unl=' . $unl . ',remoteAddr=' . $remoteAddr);
221 if ($unl == $remoteAddr) {
226 $this->bootUnl = $unl;
229 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __METHOD__ . ':' . __LINE__ . ']: IP matches remote address ' . $unl->__toString() . '.');
231 // Stop further searching
233 } elseif ($unl == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
235 * IP matches listen address. At this point we really don't care
236 * if we can really listen on that address
240 // Remember the port number
241 $this->bootUnl = $unl;
244 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __METHOD__ . ':' . __LINE__ . ']: IP matches listen address ' . $unl->__toString() . '.');
246 // Stop further searching
256 * Tries to detect own UNL (Universal Node Locator)
258 * @return $unl Node's own universal node locator
260 public function detectOwnUniversalNodeLocator () {
261 // Get the UNL array back
262 $unlArray = $this->getUniversalNodeLocatorArray();
265 die(__METHOD__ . ':unlArray=' . print_r($unlArray, TRUE));
269 * Outputs the console teaser. This should only be executed on startup or
270 * full restarts. This method generates some space around the teaser.
274 public function outputConsoleTeaser () {
275 // Get the app instance (for shortening our code)
276 $app = $this->getApplicationInstance();
279 self::createDebugInstance(__CLASS__)->debugOutput(' ');
280 self::createDebugInstance(__CLASS__)->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
281 self::createDebugInstance(__CLASS__)->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 - 2014 Hub Developer Team');
282 self::createDebugInstance(__CLASS__)->debugOutput(' ');
283 self::createDebugInstance(__CLASS__)->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
284 self::createDebugInstance(__CLASS__)->debugOutput('This is free software, and you are welcome to redistribute it under certain');
285 self::createDebugInstance(__CLASS__)->debugOutput('conditions; see docs/COPYING for details.');
286 self::createDebugInstance(__CLASS__)->debugOutput(' ');
290 * Generic method to acquire a hub-id. On first run this generates a new one
291 * based on many pseudo-random data. On any later run, unless the id
292 * got not removed from database, it will be restored from the database.
294 * @param $requestInstance A Requestable class
295 * @param $responseInstance A Responseable class
298 public function bootstrapAcquireNodeId (Requestable $requestInstance, Responseable $responseInstance) {
299 // Is there a node id?
300 if ($this->getWrapperInstance()->ifNodeDataIsFound($this)) {
301 // Get the node id from result and set it
302 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
305 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
307 // Get an RNG instance
308 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
310 // Generate a pseudo-random string
311 $randomString = $rngInstance->randomString(255);
313 // Hash and encrypt the string so we become a node id (also documented as "hub id")
314 $this->setNodeId($this->getCryptoInstance()->hashString($this->getCryptoInstance()->encryptString($randomString)));
316 // Register the node id with our wrapper
317 $this->getWrapperInstance()->registerNodeId($this, $this->getRequestInstance());
320 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
325 * Generates a session id which will be sent to the other hubs and peers
329 public function bootstrapGenerateSessionId () {
330 // Now get a search criteria instance
331 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
333 // Search for the node number one which is hard-coded the default
334 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR , 1);
335 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_MODE, $this->getRequestInstance()->getRequestElement('mode'));
336 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID , $this->getNodeId());
337 $searchInstance->setLimit(1);
339 // Remember it for later usage
340 $this->setSearchInstance($searchInstance);
342 // Get a random string
343 $randomString = $this->generateRamdomString(255);
345 // Hash and encrypt the string so we become a "node id" aka Hub-Id
346 $this->setSessionId($this->getCryptoInstance()->hashString($this->getCryptoInstance()->encryptString($randomString)));
348 // Register the node id with our wrapper
349 $this->getWrapperInstance()->registerSessionId($this, $this->getRequestInstance(), $searchInstance);
352 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
354 // Change the state because the node has auired a hub id
355 $this->getStateInstance()->nodeGeneratedSessionId();
359 * Generate a private key for en-/decryption
363 public function bootstrapGeneratePrivateKey () {
365 if ($this->getWrapperInstance()->ifNodeDataIsFound($this)) {
366 // Is the element set?
367 if (is_null($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY))) {
369 * Auto-generate the private key for e.g. out-dated database
370 * "tables". This allows a smooth update for the underlaying
373 $this->generatePrivateKeyAndHash($this->getSearchInstance());
375 // Get the node id from result and set it
376 $this->setPrivateKey(base64_decode($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY)));
377 $this->setPrivateKeyHash($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH));
380 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Re-using found private key hash: ' . $this->getPrivateKeyHash() . '');
384 * Generate it in a private method (no confusion with 'private
385 * method access' and 'private key' here! ;-)).
387 $this->generatePrivateKeyAndHash($this->getSearchInstance());
392 * Adds hub data elements to a given dataset instance
394 * @param $criteriaInstance An instance of a storeable criteria
395 * @param $requestInstance An instance of a Requestable class
398 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance = NULL) {
399 // Make sure the request instance is set as it is not optional.
400 assert($requestInstance instanceof Requestable);
402 // Add node number and type
403 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR , 1);
404 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_MODE, $requestInstance->getRequestElement('mode'));
407 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
409 // Add the session id if acquired
410 if ($this->getSessionId() != '') {
411 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
414 // Add the private key if acquired
415 if ($this->getPrivateKey() != '') {
416 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY, base64_encode($this->getPrivateKey()));
417 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH, $this->getPrivateKeyHash());
420 // Add own external and internal addresses as UNLs
421 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_INTERNAL_UNL, $this->generateInternalUnl());
422 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_EXTERNAL_UNL, $this->generateExternalUnl());
426 * Updates a given field with new value
428 * @param $fieldName Field to update
429 * @param $fieldValue New value to store
431 * @throws DatabaseUpdateSupportException If this class does not support database updates
432 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
434 public function updateDatabaseField ($fieldName, $fieldValue) {
436 $this->partialStub('Unfinished!');
439 // Get a critieria instance
440 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
442 // Add search criteria
443 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
444 $searchInstance->setLimit(1);
446 // Now get another criteria
447 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
449 // Add criteria entry which we shall update
450 $updateInstance->addCriteria($fieldName, $fieldValue);
452 // Add the search criteria for searching for the right entry
453 $updateInstance->setSearchInstance($searchInstance);
455 // Set wrapper class name
456 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
458 // Remember the update in database result
459 $this->getResultInstance()->add2UpdateQueue($updateInstance);
463 * Announces this hub to the upper (bootstrap or list) hubs. After this is
464 * successfully done the given task is unregistered from the handler. This
465 * might look a bit overloaded here but the announcement phase isn't a
466 * simple "Hello there" message, it may later on also contain more
467 * informations like the object list.
469 * @param $taskInstance The task instance running this announcement
471 * @throws NodeAlreadyAnnouncedException If this hub is already announced
472 * @todo Change the first if() block to check for a specific state
474 public function announceToUpperNodes (Taskable $taskInstance) {
475 // Is this hub node announced?
476 if ($this->hubIsAnnounced === TRUE) {
477 // Already announced!
478 throw new NodeAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
482 self::createDebugInstance(__CLASS__)->debugOutput('HUB-Announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
484 // Get a helper instance
485 $helperInstance = ObjectFactory::createObjectByConfiguredName('node_announcement_helper_class');
487 // Load the announcement descriptor
488 $helperInstance->loadDescriptorXml($this);
490 // Compile all variables
491 $helperInstance->getTemplateInstance()->compileConfigInVariables();
493 // "Publish" the descriptor by sending it to the bootstrap/list nodes
494 $helperInstance->sendPackage($this);
496 // Change the state, this should be the last line except debug output
497 $this->getStateInstance()->nodeAnnouncingToUpperHubs();
500 self::createDebugInstance(__CLASS__)->debugOutput('HUB-Announcement: FINISHED');
504 * Does a self-connect attempt on the public IP address. This should make
505 * it sure, we are reachable from outside world. For this kind of package we
506 * don't need that overload we have in the announcement phase.
508 * @param $taskInstance The task instance running this announcement
511 public function doSelfConnection (Taskable $taskInstance) {
513 self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
515 // Get a helper instance
516 $helperInstance = ObjectFactory::createObjectByConfiguredName('node_self_connect_helper_class', array($this));
518 // Load the descriptor (XML) file
519 $helperInstance->loadDescriptorXml($this);
521 // Compile all variables
522 $helperInstance->getTemplateInstance()->compileConfigInVariables();
524 // And send the package away
525 $helperInstance->sendPackage($this);
528 self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Self Connection: FINISHED');
532 * Activates the hub by doing some final preparation and setting
533 * $hubIsActive to TRUE.
535 * @param $requestInstance A Requestable class
536 * @param $responseInstance A Responseable class
539 public function activateNode (Requestable $requestInstance, Responseable $responseInstance) {
540 // Checks whether a listener is still active and shuts it down if one
541 // is still listening.
542 if (($this->determineIfListenerIsActive()) && ($this->isNodeActive())) {
543 // Shutdown them down before they can hurt anything
544 $this->shutdownListenerPool();
547 // Get the controller here
548 $controllerInstance = Registry::getRegistry()->getInstance('controller');
550 // Run all filters for the hub activation
551 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
553 // ----------------------- Last step from here ------------------------
554 // Activate the hub. This is ALWAYS the last step in this method
555 $this->getStateInstance()->nodeIsActivated();
556 // ---------------------- Last step until here ------------------------
560 * Initializes the listener pool (class)
564 public function initializeListenerPool () {
566 self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Initialize listener: START');
568 // Get a new pool instance
569 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
571 // Get an instance of the low-level listener
572 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
574 // Setup address and port
575 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
578 * All nodes can now use the same configuration entry because it can be
579 * customized in config-local.php.
581 $listenerInstance->setListenPortByConfiguration('node_listen_port');
583 // Initialize the listener
584 $listenerInstance->initListener();
586 // Get a decorator class
587 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('node_tcp_listener_class', array($listenerInstance));
589 // Add this listener to the pool
590 $this->getListenerPoolInstance()->addListener($decoratorInstance);
592 // Get a decorator class
593 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
595 // Add this listener to the pool
596 $this->getListenerPoolInstance()->addListener($decoratorInstance);
598 // Get an instance of the low-level listener
599 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
601 // Setup address and port
602 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
605 * All nodes can now use the same configuration entry because it can be
606 * customized in config-local.php.
608 $listenerInstance->setListenPortByConfiguration('node_listen_port');
610 // Initialize the listener
611 $listenerInstance->initListener();
613 // Get a decorator class
614 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('node_udp_listener_class', array($listenerInstance));
616 // Add this listener to the pool
617 $this->getListenerPoolInstance()->addListener($decoratorInstance);
619 // Get a decorator class
620 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
622 // Add this listener to the pool
623 $this->getListenerPoolInstance()->addListener($decoratorInstance);
626 self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Initialize listener: FINISHED.');
630 * Getter for isActive attribute
632 * @return $isActive Whether the hub is active
634 public final function isNodeActive () {
635 return $this->isActive;
639 * Enables (default) or disables isActive flag
641 * @param $isActive Whether the hub is active
644 public final function enableIsActive ($isActive = TRUE) {
645 $this->isActive = (bool) $isActive;
649 * Checks whether this node accepts announcements
651 * @return $acceptAnnouncements Whether this node accepts announcements
653 public final function isAcceptingAnnouncements () {
654 // Check it (this node must be active and not shutdown!)
655 $acceptAnnouncements = (($this->acceptAnnouncements === TRUE) && ($this->isNodeActive()));
658 return $acceptAnnouncements;
662 * Checks whether this node accepts DHT bootstrap requests
664 * @return $acceptDhtBootstrap Whether this node accepts DHT bootstrap requests
666 public final function isAcceptingDhtBootstrap () {
667 // Check it (this node must be active and not shutdown!)
668 $acceptDhtBootstrap = (($this->acceptDhtBootstrap === TRUE) && ($this->isNodeActive()));
671 return $acceptDhtBootstrap;
675 * Checks whether this node has attempted to announce itself
677 * @return $hasAnnounced Whether this node has attempted to announce itself
678 * @todo Add checking if this node has been announced to the sender node
680 public function ifNodeIsAnnouncing () {
682 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: ifNodeIsAnnouncing(): state=' . $this->getStateInstance()->getStateName());
684 // Simply check the state of this node
685 $hasAnnounced = ($this->getStateInstance() instanceof NodeAnnouncingState);
688 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: ifNodeIsAnnouncing(): hasAnnounced=' . intval($hasAnnounced));
691 return $hasAnnounced;
695 * Checks whether this node has attempted to announce itself and completed it
697 * @return $hasAnnouncementCompleted Whether this node has attempted to announce itself and completed it
698 * @todo Add checking if this node has been announced to the sender node
700 public function ifNodeHasAnnouncementCompleted () {
702 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: ifNodeHasAnnouncementCompleted(): state=' . $this->getStateInstance()->getStateName());
704 // Simply check the state of this node
705 $hasAnnouncementCompleted = ($this->getStateInstance() instanceof NodeAnnouncementCompletedState);
708 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: ifNodeHasAnnouncementCompleted(): hasAnnouncementCompleted=' . intval($hasAnnouncementCompleted));
711 return $hasAnnouncementCompleted;
715 * Enables whether this node accepts announcements
717 * @param $acceptAnnouncements Whether this node accepts announcements (default: TRUE)
720 protected final function enableAcceptingAnnouncements ($acceptAnnouncements = TRUE) {
721 $this->acceptAnnouncements = $acceptAnnouncements;
725 * Enables whether this node accepts DHT bootstrap requests
727 * @param $acceptDhtBootstrap Whether this node accepts DHT bootstrap requests (default: TRUE)
730 public final function enableAcceptDhtBootstrap ($acceptDhtBootstrap = TRUE) {
731 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Enabling DHT bootstrap requests ...');
732 $this->acceptDhtBootstrap = $acceptDhtBootstrap;
736 * Checks wether this node is accepting node-list requests
738 * @return $acceptsRequest Wether this node accepts node-list requests
740 public function isAcceptingNodeListRequests () {
742 * Only 'regular' nodes does not accept such requests, checking
743 * HubRegularNode is faster, but if e.g. HubRegularI2PNode will be
744 * added then the next check will be TRUE.
746 $acceptsRequest = ((!$this instanceof HubRegularNode) && ($this->getRequestInstance()->getRequestElement('mode') != self::NODE_TYPE_REGULAR));
749 return $acceptsRequest;
753 * Determines an instance of a LocateableNode class
755 * @return $unlInstance An instance of a LocateableNode class for this node
757 public function determineUniversalNodeLocator () {
759 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: CALLED!');
761 // Determine UNL based on this node:
762 // 1) Get discovery class
763 $discoveryInstance = ObjectFactory::createObjectByConfiguredName('unl_discovery_class');
766 $unlInstance = $discoveryInstance->discoverUniversalNodeLocatorByNode($this);
769 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: unlInstance= ' . $unlInstance->__toString() . ' - EXIT!');
774 * "Getter" for an array of an instance of a LocateableNode class
776 * @return $unlArray An array from an instance of a LocateableNode class for this node
778 public final function getUniversalNodeLocatorArray () {
780 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: CALLED!');
782 // Get the Universal Node Locator (UNL) instance
783 $unlInstance = $this->determineUniversalNodeLocator();
786 die(__METHOD__ . ':unlInstance[' . gettype($unlInstance) . ']=' . print_r($unlInstance, TRUE));
789 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: EXIT!');
794 * Updates/refreshes node data (e.g. status).
797 * @todo Find more to do here
799 public function updateNodeData () {
800 // Set some dummy configuration entries, e.g. node_status
801 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
805 * Handles message answer by given data array
807 * @param $messageData A valid answer message data array
808 * @param $packageInstance An instance of a Receivable class
810 * @todo Handle thrown exception
812 public function handleAnswerStatusByMessageData (array $messageData, Receivable $packageInstance) {
814 assert(!empty($messageData[BaseXmlAnswerTemplateEngine::ANSWER_STATUS]));
816 // Construct configuration entry for handling class' name
817 $classConfigEntry = strtolower($messageData[NetworkPackage::MESSAGE_ARRAY_TYPE] . '_status_' . $messageData[BaseXmlAnswerTemplateEngine::ANSWER_STATUS]) . '_handler_class';
819 // Try to get a class
820 $handlerInstance = ObjectFactory::createObjectByConfiguredName($classConfigEntry);
823 $handlerInstance->handleAnswerMessageData($messageData, $packageInstance);
827 * "Getter" for an array of all accepted object types
829 * @return $objectList Array of all accepted object types
831 public function getListFromAcceptedObjectTypes () {
832 // Get registry instance
833 $objectRegistryInstance = ObjectTypeRegistryFactory::createObjectTypeRegistryInstance();
836 $objectList = $objectRegistryInstance->getEntries(XmlObjectRegistryTemplateEngine::OBJECT_TYPE_DATA_NAME);
843 * Adds all required elements from given array into data set instance
845 * @param $dataSetInstance An instance of a StoreableCriteria class
846 * @param $nodeData An array with valid node data
849 public function addArrayToDataSet (StoreableCriteria $dataSetInstance, array $nodeData) {
850 // Add all data the array provides
851 foreach (NodeDistributedHashTableDatabaseWrapper::getAllElements() as $element) {
852 // Is the element there?
853 if (isset($nodeData[$element])) {
855 $dataSetInstance->addCriteria($element, $nodeData[$element]);
857 // Output warning message
858 /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: addArrayToDataSet(): Element ' . $element . ' not found in nodeData array.');