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