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