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