]> git.mxchange.org Git - hub.git/blob - application/hub/main/nodes/class_BaseHubNode.php
Continued with hub:
[hub.git] / application / hub / main / nodes / class_BaseHubNode.php
1 <?php
2 /**
3  * A general hub node class
4  *
5  * @author              Roland Haeder <webmaster@shipsimu.org>
6  * @version             0.0.0
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
10  *
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.
15  *
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.
20  *
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/>.
23  */
24 class BaseHubNode extends BaseHubSystem implements Updateable, AddableCriteria {
25         /**
26          * Node types
27          */
28         const NODE_TYPE_BOOT    = 'boot';
29         const NODE_TYPE_MASTER  = 'master';
30         const NODE_TYPE_LIST    = 'list';
31         const NODE_TYPE_REGULAR = 'regular';
32
33         // Exception constants
34         const EXCEPTION_HUB_ALREADY_ANNOUNCED = 0xe00;
35
36         // Other constants
37         const OBJECT_LIST_SEPARATOR = ',';
38
39         /**
40          * IP/port number of bootstrap node
41          */
42         private $bootIpPort = '';
43
44         /**
45          * Query connector instance
46          */
47         private $queryConnectorInstance = NULL;
48
49         /**
50          * Queue connector instance
51          */
52         private $queueConnectorInstance = NULL;
53
54         /**
55          * Whether this node is anncounced (keep on FALSE!)
56          * @deprecated
57          */
58         private $hubIsAnnounced = FALSE;
59
60         /**
61          * Whether this hub is active (default: FALSE)
62          */
63         private $isActive = FALSE;
64
65         /**
66          * Whether this node accepts announcements (default: FALSE)
67          */
68         private $acceptAnnouncements = FALSE;
69
70         /**
71          * Whether this node accepts DHT bootstrap requests (default: FALSE)
72          */
73         private $acceptDhtBootstrap = FALSE;
74
75         /**
76          * Protected constructor
77          *
78          * @param       $className      Name of the class
79          * @return      void
80          */
81         protected function __construct ($className) {
82                 // Call parent constructor
83                 parent::__construct($className);
84
85                 // Get a wrapper instance
86                 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName('node_info_db_wrapper_class');
87
88                 // Set it here
89                 $this->setWrapperInstance($wrapperInstance);
90
91                 // Get a crypto instance
92                 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
93
94                 // Set it here
95                 $this->setCryptoInstance($cryptoInstance);
96
97                 // Init state which sets the state to 'init'
98                 $this->initState();
99         }
100
101         /**
102          * Initializes the node's state which sets it to 'init'
103          *
104          * @return      void
105          */
106         private function initState() {
107                 // Get the state factory and create the initial state.
108                 NodeStateFactory::createNodeStateInstanceByName('init', $this);
109         }
110
111         /**
112          * Generates a random string from various data inluding UUID if PECL
113          * extension uuid is installed.
114          *
115          * @param       $length                 Length of the random part
116          * @return      $randomString   Random string
117          * @todo        Make this code more generic and move it to CryptoHelper or
118          */
119         protected function generateRamdomString ($length) {
120                 // Get an RNG instance
121                 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
122
123                 // Generate a pseudo-random string
124                 $randomString = $rngInstance->randomString($length) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
125
126                 // Add UUID for even more entropy for the hasher
127                 $randomString .= $this->getCryptoInstance()->createUuid();
128
129                 // Return it
130                 return $randomString;
131         }
132
133         /**
134          * Generates a private key and hashes it (for speeding up things)
135          *
136          * @param       $searchInstance         An instance of a LocalSearchCriteria class
137          * @return void
138          */
139         private function generatePrivateKeyAndHash (LocalSearchCriteria $searchInstance) {
140                 // Get an RNG instance
141                 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
142
143                 // Generate a pseudo-random string
144                 $randomString = $rngInstance->randomString(255);
145
146                 // Hash and encrypt the string so we become a node id (also documented as "hub id")
147                 $this->setPrivateKey($this->getCryptoInstance()->encryptString($randomString));
148                 $this->setPrivateKeyHash($this->getCryptoInstance()->hashString($this->getPrivateKey()));
149
150                 // Register the node id with our wrapper
151                 $this->getWrapperInstance()->registerPrivateKey($this, $this->getRequestInstance(), $searchInstance);
152
153                 // Output message
154                 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Created new private key with hash: ' . $this->getPrivateKeyHash() . '');
155         }
156
157         /**
158          * Setter for query instance
159          *
160          * @param       $connectorInstance              Our new query instance
161          * @return      void
162          */
163         private final function setQueryConnectorInstance (Connectable $connectorInstance) {
164                 $this->queryConnectorInstance = $connectorInstance;
165         }
166
167         /**
168          * Getter for query instance
169          *
170          * @return      $connectorInstance              Our new query instance
171          */
172         public final function getQueryConnectorInstance () {
173                 return $this->queryConnectorInstance;
174         }
175
176         /**
177          * Setter for queue instance
178          *
179          * @param       $connectorInstance              Our new queue instance
180          * @return      void
181          */
182         private final function setQueueConnectorInstance (Connectable $connectorInstance) {
183                 $this->queueConnectorInstance = $connectorInstance;
184         }
185
186         /**
187          * Getter for queue instance
188          *
189          * @return      $connectorInstance              Our new queue instance
190          */
191         public final function getQueueConnectorInstance () {
192                 return $this->queueConnectorInstance;
193         }
194
195         /**
196          * Getter for boot IP/port combination
197          *
198          * @return      $bootIpPort             The IP/port combination of the boot node
199          */
200         protected final function getBootIpPort () {
201                 return $this->bootIpPort;
202         }
203
204         /**
205          * Checks whether the given IP address matches one of the bootstrap nodes
206          *
207          * @param       $remoteAddr             IP address to checkout against our bootstrapping list
208          * @return      $isFound                Whether the IP is found
209          */
210         protected function ifAddressMatchesBootstrapNodes ($remoteAddr) {
211                 // By default nothing is found
212                 $isFound = FALSE;
213
214                 // Run through all configured IPs
215                 foreach (explode(BaseHubSystem::BOOTSTRAP_NODES_SEPARATOR, $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
216                         // Split it up in IP/port
217                         $ipPortArray = explode(':', $ipPort);
218
219                         // Does it match?
220                         if ($ipPortArray[0] == $remoteAddr) {
221                                 // Found it!
222                                 $isFound = TRUE;
223
224                                 // Remember the port number
225                                 $this->bootIpPort = $ipPort;
226
227                                 // Output message
228                                 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __METHOD__ . ':' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
229
230                                 // Stop further searching
231                                 break;
232                         } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
233                                 /*
234                                  * IP matches listen address. At this point we really don't care
235                                  * if we can really listen on that address
236                                  */
237                                 $isFound = TRUE;
238
239                                 // Remember the port number
240                                 $this->bootIpPort = $ipPort;
241
242                                 // Output message
243                                 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __METHOD__ . ':' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
244
245                                 // Stop further searching
246                                 break;
247                         }
248                 } // END - foreach
249
250                 // Return the result
251                 return $isFound;
252         }
253
254         /**
255          * Outputs the console teaser. This should only be executed on startup or
256          * full restarts. This method generates some space around the teaser.
257          *
258          * @return      void
259          */
260         public function outputConsoleTeaser () {
261                 // Get the app instance (for shortening our code)
262                 $app = $this->getApplicationInstance();
263
264                 // Output all lines
265                 self::createDebugInstance(__CLASS__)->debugOutput(' ');
266                 self::createDebugInstance(__CLASS__)->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
267                 self::createDebugInstance(__CLASS__)->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 - 2014 Hub Developer Team');
268                 self::createDebugInstance(__CLASS__)->debugOutput(' ');
269                 self::createDebugInstance(__CLASS__)->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
270                 self::createDebugInstance(__CLASS__)->debugOutput('This is free software, and you are welcome to redistribute it under certain');
271                 self::createDebugInstance(__CLASS__)->debugOutput('conditions; see docs/COPYING for details.');
272                 self::createDebugInstance(__CLASS__)->debugOutput(' ');
273         }
274
275         /**
276          * Generic method to acquire a hub-id. On first run this generates a new one
277          * based on many pseudo-random data. On any later run, unless the id
278          * got not removed from database, it will be restored from the database.
279          *
280          * @param       $requestInstance        A Requestable class
281          * @param       $responseInstance       A Responseable class
282          * @return      void
283          */
284         public function bootstrapAcquireNodeId (Requestable $requestInstance, Responseable $responseInstance) {
285                 // Is there a node id?
286                 if ($this->getWrapperInstance()->ifNodeDataIsFound($this)) {
287                         // Get the node id from result and set it
288                         $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
289
290                         // Output message
291                         self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
292                 } else {
293                         // Get an RNG instance
294                         $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
295
296                         // Generate a pseudo-random string
297                         $randomString = $rngInstance->randomString(255);
298
299                         // Hash and encrypt the string so we become a node id (also documented as "hub id")
300                         $this->setNodeId($this->getCryptoInstance()->hashString($this->getCryptoInstance()->encryptString($randomString)));
301
302                         // Register the node id with our wrapper
303                         $this->getWrapperInstance()->registerNodeId($this, $this->getRequestInstance());
304
305                         // Output message
306                         self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
307                 }
308         }
309
310         /**
311          * Generates a session id which will be sent to the other hubs and peers
312          *
313          * @return      void
314          */
315         public function bootstrapGenerateSessionId () {
316                 // Now get a search criteria instance
317                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
318
319                 // Search for the node number one which is hard-coded the default
320                 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR  , 1);
321                 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_MODE, $this->getRequestInstance()->getRequestElement('mode'));
322                 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID  , $this->getNodeId());
323                 $searchInstance->setLimit(1);
324
325                 // Remember it for later usage
326                 $this->setSearchInstance($searchInstance);
327
328                 // Get a random string
329                 $randomString = $this->generateRamdomString(255);
330
331                 // Hash and encrypt the string so we become a "node id" aka Hub-Id
332                 $this->setSessionId($this->getCryptoInstance()->hashString($this->getCryptoInstance()->encryptString($randomString)));
333
334                 // Register the node id with our wrapper
335                 $this->getWrapperInstance()->registerSessionId($this, $this->getRequestInstance(), $searchInstance);
336
337                 // Output message
338                 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
339
340                 // Change the state because the node has auired a hub id
341                 $this->getStateInstance()->nodeGeneratedSessionId();
342         }
343
344         /**
345          * Generate a private key for en-/decryption
346          *
347          * @return      void
348          */
349         public function bootstrapGeneratePrivateKey () {
350                 // Is it valid?
351                 if ($this->getWrapperInstance()->ifNodeDataIsFound($this)) {
352                         // Is the element set?
353                         if (is_null($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY))) {
354                                 /*
355                                  * Auto-generate the private key for e.g. out-dated database
356                                  * "tables". This allows a smooth update for the underlaying
357                                  * database table.
358                                  */
359                                 $this->generatePrivateKeyAndHash($this->getSearchInstance());
360                         } else {
361                                 // Get the node id from result and set it
362                                 $this->setPrivateKey(base64_decode($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY)));
363                                 $this->setPrivateKeyHash($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH));
364
365                                 // Output message
366                                 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Re-using found private key hash: ' . $this->getPrivateKeyHash() . '');
367                         }
368                 } else {
369                         /*
370                          * Generate it in a private method (no confusion with 'private
371                          * method access' and 'private key' here! ;-)).
372                          */
373                         $this->generatePrivateKeyAndHash($this->getSearchInstance());
374                 }
375         }
376
377         /**
378          * Adds hub data elements to a given dataset instance
379          *
380          * @param       $criteriaInstance       An instance of a storeable criteria
381          * @param       $requestInstance        An instance of a Requestable class
382          * @return      void
383          */
384         public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance = NULL) {
385                 // Make sure request instance is set as it is not optional
386                 assert($requestInstance instanceof Requestable);
387
388                 // Add node number and type
389                 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR  , 1);
390                 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_MODE, $requestInstance->getRequestElement('mode'));
391
392                 // Add the node id
393                 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
394
395                 // Add the session id if acquired
396                 if ($this->getSessionId() != '') {
397                         $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
398                 } // END - if
399
400                 // Add the private key if acquired
401                 if ($this->getPrivateKey() != '') {
402                         $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY, base64_encode($this->getPrivateKey()));
403                         $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH, $this->getPrivateKeyHash());
404                 } // END - if
405         }
406
407         /**
408          * Updates a given field with new value
409          *
410          * @param       $fieldName              Field to update
411          * @param       $fieldValue             New value to store
412          * @return      void
413          * @throws      DatabaseUpdateSupportException  If this class does not support database updates
414          * @todo        Try to make this method more generic so we can move it in BaseFrameworkSystem
415          */
416         public function updateDatabaseField ($fieldName, $fieldValue) {
417                 // Unfinished
418                 $this->partialStub('Unfinished!');
419                 return;
420
421                 // Get a critieria instance
422                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
423
424                 // Add search criteria
425                 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
426                 $searchInstance->setLimit(1);
427
428                 // Now get another criteria
429                 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
430
431                 // Add criteria entry which we shall update
432                 $updateInstance->addCriteria($fieldName, $fieldValue);
433
434                 // Add the search criteria for searching for the right entry
435                 $updateInstance->setSearchInstance($searchInstance);
436
437                 // Set wrapper class name
438                 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
439
440                 // Remember the update in database result
441                 $this->getResultInstance()->add2UpdateQueue($updateInstance);
442         }
443
444         /**
445          * Announces this hub to the upper (bootstrap or list) hubs. After this is
446          * successfully done the given task is unregistered from the handler. This
447          * might look a bit overloaded here but the announcement phase isn't a
448          * simple "Hello there" message, it may later on also contain more
449          * informations like the object list.
450          *
451          * @param       $taskInstance   The task instance running this announcement
452          * @return      void
453          * @throws      NodeAlreadyAnnouncedException   If this hub is already announced
454          * @todo        Change the first if() block to check for a specific state
455          */
456         public function announceToUpperNodes (Taskable $taskInstance) {
457                 // Is this hub node announced?
458                 if ($this->hubIsAnnounced === TRUE) {
459                         // Already announced!
460                         throw new NodeAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
461                 } // END - if
462
463                 // Debug output
464                 self::createDebugInstance(__CLASS__)->debugOutput('HUB-Announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
465
466                 // Get a helper instance
467                 $helperInstance = ObjectFactory::createObjectByConfiguredName('node_announcement_helper_class');
468
469                 // Load the announcement descriptor
470                 $helperInstance->loadDescriptorXml($this);
471
472                 // Compile all variables
473                 $helperInstance->getTemplateInstance()->compileConfigInVariables();
474
475                 // "Publish" the descriptor by sending it to the bootstrap/list nodes
476                 $helperInstance->sendPackage($this);
477
478                 // Change the state, this should be the last line except debug output
479                 $this->getStateInstance()->nodeAnnouncingToUpperHubs();
480
481                 // Debug output
482                 self::createDebugInstance(__CLASS__)->debugOutput('HUB-Announcement: FINISHED');
483         }
484
485         /**
486          * Does a self-connect attempt on the public IP address. This should make
487          * it sure, we are reachable from outside world. For this kind of package we
488          * don't need that overload we have in the announcement phase.
489          *
490          * @param       $taskInstance   The task instance running this announcement
491          * @return      void
492          */
493         public function doSelfConnection (Taskable $taskInstance) {
494                 // Debug output
495                 self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
496
497                 // Get a helper instance
498                 $helperInstance = ObjectFactory::createObjectByConfiguredName('node_self_connect_helper_class', array($this));
499
500                 // Load the descriptor (XML) file
501                 $helperInstance->loadDescriptorXml($this);
502
503                 // Compile all variables
504                 $helperInstance->getTemplateInstance()->compileConfigInVariables();
505
506                 // And send the package away
507                 $helperInstance->sendPackage($this);
508
509                 // Debug output
510                 self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Self Connection: FINISHED');
511         }
512
513         /**
514          * Activates the hub by doing some final preparation and setting
515          * $hubIsActive to TRUE.
516          *
517          * @param       $requestInstance        A Requestable class
518          * @param       $responseInstance       A Responseable class
519          * @return      void
520          */
521         public function activateNode (Requestable $requestInstance, Responseable $responseInstance) {
522                 // Checks whether a listener is still active and shuts it down if one
523                 // is still listening.
524                 if (($this->determineIfListenerIsActive()) && ($this->isNodeActive())) {
525                         // Shutdown them down before they can hurt anything
526                         $this->shutdownListenerPool();
527                 } // END - if
528
529                 // Get the controller here
530                 $controllerInstance = Registry::getRegistry()->getInstance('controller');
531
532                 // Run all filters for the hub activation
533                 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
534
535                 // ----------------------- Last step from here ------------------------
536                 // Activate the hub. This is ALWAYS the last step in this method
537                 $this->getStateInstance()->nodeIsActivated();
538                 // ---------------------- Last step until here ------------------------
539         }
540
541         /**
542          * Initializes the listener pool (class)
543          *
544          * @return      void
545          */
546         public function initializeListenerPool () {
547                 // Debug output
548                 self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Initialize listener: START');
549
550                 // Get a new pool instance
551                 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
552
553                 // Get an instance of the low-level listener
554                 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
555
556                 // Setup address and port
557                 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
558
559                 /*
560                  * All nodes can now use the same configuration entry because it can be
561                  * customized in config-local.php.
562                  */
563                 $listenerInstance->setListenPortByConfiguration('node_listen_port');
564
565                 // Initialize the listener
566                 $listenerInstance->initListener();
567
568                 // Get a decorator class
569                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('node_tcp_listener_class', array($listenerInstance));
570
571                 // Add this listener to the pool
572                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
573
574                 // Get a decorator class
575                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
576
577                 // Add this listener to the pool
578                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
579
580                 // Get an instance of the low-level listener
581                 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
582
583                 // Setup address and port
584                 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
585
586                 /*
587                  * All nodes can now use the same configuration entry because it can be
588                  * customized in config-local.php.
589                  */
590                 $listenerInstance->setListenPortByConfiguration('node_listen_port');
591
592                 // Initialize the listener
593                 $listenerInstance->initListener();
594
595                 // Get a decorator class
596                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('node_udp_listener_class', array($listenerInstance));
597
598                 // Add this listener to the pool
599                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
600
601                 // Get a decorator class
602                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
603
604                 // Add this listener to the pool
605                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
606
607                 // Debug output
608                 self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Initialize listener: FINISHED.');
609         }
610
611         /**
612          * Getter for isActive attribute
613          *
614          * @return      $isActive       Whether the hub is active
615          */
616         public final function isNodeActive () {
617                 return $this->isActive;
618         }
619
620         /**
621          * Enables (default) or disables isActive flag
622          *
623          * @param       $isActive       Whether the hub is active
624          * @return      void
625          */
626         public final function enableIsActive ($isActive = TRUE) {
627                 $this->isActive = (bool) $isActive;
628         }
629
630         /**
631          * Checks whether this node accepts announcements
632          *
633          * @return      $acceptAnnouncements    Whether this node accepts announcements
634          */
635         public final function isAcceptingAnnouncements () {
636                 // Check it (this node must be active and not shutdown!)
637                 $acceptAnnouncements = (($this->acceptAnnouncements === TRUE) && ($this->isNodeActive()));
638
639                 // Return it
640                 return $acceptAnnouncements;
641         }
642
643         /**
644          * Checks whether this node accepts DHT bootstrap requests
645          *
646          * @return      $acceptDhtBootstrap     Whether this node accepts DHT bootstrap requests
647          */
648         public final function isAcceptingDhtBootstrap () {
649                 // Check it (this node must be active and not shutdown!)
650                 $acceptDhtBootstrap = (($this->acceptDhtBootstrap === TRUE) && ($this->isNodeActive()));
651
652                 // Return it
653                 return $acceptDhtBootstrap;
654         }
655
656         /**
657          * Checks whether this node has attempted to announce itself
658          *
659          * @return      $hasAnnounced   Whether this node has attempted to announce itself
660          * @todo        Add checking if this node has been announced to the sender node
661          */
662         public function ifNodeIsAnnouncing () {
663                 // Debug message
664                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: ifNodeIsAnnouncing(): state=' . $this->getStateInstance()->getStateName());
665
666                 // Simply check the state of this node
667                 $hasAnnounced = ($this->getStateInstance() instanceof NodeAnnouncingState);
668
669                 // Debug message
670                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: ifNodeIsAnnouncing(): hasAnnounced=' . intval($hasAnnounced));
671
672                 // Return it
673                 return $hasAnnounced;
674         }
675
676         /**
677          * Checks whether this node has attempted to announce itself and completed it
678          *
679          * @return      $hasAnnouncementCompleted       Whether this node has attempted to announce itself and completed it
680          * @todo        Add checking if this node has been announced to the sender node
681          */
682         public function ifNodeHasAnnouncementCompleted () {
683                 // Debug message
684                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: ifNodeHasAnnouncementCompleted(): state=' . $this->getStateInstance()->getStateName());
685
686                 // Simply check the state of this node
687                 $hasAnnouncementCompleted = ($this->getStateInstance() instanceof NodeAnnouncementCompletedState);
688
689                 // Debug message
690                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: ifNodeHasAnnouncementCompleted(): hasAnnouncementCompleted=' . intval($hasAnnouncementCompleted));
691
692                 // Return it
693                 return $hasAnnouncementCompleted;
694         }
695
696         /**
697          * Enables whether this node accepts announcements
698          *
699          * @param       $acceptAnnouncements    Whether this node accepts announcements (default: TRUE)
700          * @return      void
701          */
702         protected final function enableAcceptingAnnouncements ($acceptAnnouncements = TRUE) {
703                 $this->acceptAnnouncements = $acceptAnnouncements;
704         }
705
706         /**
707          * Enables whether this node accepts DHT bootstrap requests
708          *
709          * @param       $acceptDhtBootstrap     Whether this node accepts DHT bootstrap requests (default: TRUE)
710          * @return      void
711          */
712         public final function enableAcceptDhtBootstrap ($acceptDhtBootstrap = TRUE) {
713                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Enabling DHT bootstrap requests ...');
714                 $this->acceptDhtBootstrap = $acceptDhtBootstrap;
715         }
716
717         /**
718          * Checks wether this node is accepting node-list requests
719          *
720          * @return      $acceptsRequest         Wether this node accepts node-list requests
721          */
722         public function isAcceptingNodeListRequests () {
723                 /*
724                  * Only 'regular' nodes does not accept such requests, checking
725                  * HubRegularNode is faster, but if e.g. HubRegularI2PNode will be
726                  * added then the next check will be TRUE.
727                  */
728                 $acceptsRequest = ((!$this instanceof HubRegularNode) && ($this->getRequestInstance()->getRequestElement('mode') != self::NODE_TYPE_REGULAR));
729
730                 // Return it
731                 return $acceptsRequest;
732         }
733
734         /**
735          * "Getter" for address:port combination
736          *
737          * @return      $addressPort    A address:port combination for this node
738          */
739         public final function getAddressPort () {
740                 // Get IP and port
741                 $addressPort = $this->getConfigInstance()->detectServerAddress() . ':' . $this->getConfigInstance()->getConfigEntry('node_listen_port');
742
743                 // Return it
744                 return $addressPort;
745         }
746
747         /**
748          * "Getter" for address:port array
749          *
750          * @return      $addressPortArray       An array of a address:port combination for this node
751          */
752         public final function getAddressPortArray () {
753                 // Get IP and port
754                 $addressPortArray = explode(':', $this->getAddressPort());
755
756                 // Return it
757                 return $addressPortArray;
758         }
759
760         /**
761          * Updates/refreshes node data (e.g. status).
762          *
763          * @return      void
764          * @todo        Find more to do here
765          */
766         public function updateNodeData () {
767                 // Set some dummy configuration entries, e.g. node_status
768                 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
769         }
770
771         /**
772          * Handles message answer by given data array
773          *
774          * @param       $messageData            A valid answer message data array
775          * @param       $packageInstance        An instance of a Receivable class
776          * @return      void
777          * @todo        Handle thrown exception
778          */
779         public function handleAnswerStatusByMessageData (array $messageData, Receivable $packageInstance) {
780                 // Is it not empty?
781                 assert(!empty($messageData[BaseXmlAnswerTemplateEngine::ANSWER_STATUS]));
782
783                 // Construct configuration entry for handling class' name
784                 $classConfigEntry = strtolower($messageData[NetworkPackage::MESSAGE_ARRAY_TYPE] . '_status_' . $messageData[BaseXmlAnswerTemplateEngine::ANSWER_STATUS]) . '_handler_class';
785
786                 // Try to get a class
787                 $handlerInstance = ObjectFactory::createObjectByConfiguredName($classConfigEntry);
788
789                 // Handle it there
790                 $handlerInstance->handleAnswerMessageData($messageData, $packageInstance);
791         }
792
793         /**
794          * "Getter" for an array of all accepted object types
795          *
796          * @return      $objectList             Array of all accepted object types
797          */
798         public function getListFromAcceptedObjectTypes () {
799                 // Get registry instance
800                 $objectRegistryInstance = ObjectTypeRegistryFactory::createObjectTypeRegistryInstance();
801
802                 // Get all entries
803                 $objectList = $objectRegistryInstance->getEntries(XmlObjectRegistryTemplateEngine::OBJECT_TYPE_DATA_NAME);
804
805                 // ... and return it
806                 return $objectList;
807         }
808
809         /**
810          * Adds all required elements from given array into data set instance
811          *
812          * @param       $dataSetInstance        An instance of a StoreableCriteria class
813          * @param       $nodeData                       An array with valid node data
814          * @return      void
815          */
816         public function addArrayToDataSet (StoreableCriteria $dataSetInstance, array $nodeData) {
817                 // Add all data the array provides
818                 foreach (NodeDistributedHashTableDatabaseWrapper::getAllElements() as $element) {
819                         // Is the element there?
820                         if (isset($nodeData[$element])) {
821                                 // Add it
822                                 $dataSetInstance->addCriteria($element, $nodeData[$element]);
823                         } else {
824                                 // Output warning message
825                                 /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: addArrayToDataSet(): Element ' . $element . ' not found in nodeData array.');
826                         }
827                 } // END - foreac
828         }
829 }
830
831 // [EOF]
832 ?>