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