]> git.mxchange.org Git - hub.git/blob
b4c63f919855b44f2175e1f3d404e6d4c915bf7e
[hub.git] /
1 <?php
2 // Own namespace
3 namespace Org\Shipsimu\Hub\Database\Frontend\Node\Dht;
4
5 // Import application-specific stuff
6 use Org\Shipsimu\Hub\Database\Frontend\BaseHubDatabaseFrontend;
7 use Org\Shipsimu\Hub\Factory\Node\NodeObjectFactory;
8 use Org\Shipsimu\Hub\Locator\Node\LocateableNode;
9 use Org\Shipsimu\Hub\Network\Message\DeliverableMessage;
10 use Org\Shipsimu\Hub\Network\Package\DeliverablePackage;
11 use Org\Shipsimu\Hub\Node\BaseHubNode;
12
13 // Import framework stuff
14 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
15 use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
16 use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
17 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
18 use Org\Mxchange\CoreFramework\Handler\DataSet\HandleableDataSet;
19 use Org\Mxchange\CoreFramework\Registry\Registerable;
20 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
21
22 // Import SPL stuff
23 use \InvalidArgumentException;
24
25 /**
26  * A database frontend for distributed hash tables
27  *
28  * @author              Roland Haeder <webmaster@shipsimu.org>
29  * @version             0.0.0
30  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2018 Hub Developer Team
31  * @license             GNU GPL 3.0 or any newer version
32  * @link                http://www.shipsimu.org
33  *
34  * This program is free software: you can redistribute it and/or modify
35  * it under the terms of the GNU General Public License as published by
36  * the Free Software Foundation, either version 3 of the License, or
37  * (at your option) any later version.
38  *
39  * This program is distributed in the hope that it will be useful,
40  * but WITHOUT ANY WARRANTY; without even the implied warranty of
41  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
42  * GNU General Public License for more details.
43  *
44  * You should have received a copy of the GNU General Public License
45  * along with this program. If not, see <http://www.gnu.org/licenses/>.
46  */
47 class NodeDistributedHashTableDatabaseFrontend extends BaseHubDatabaseFrontend implements NodeDhtFrontend, Registerable {
48         /**
49          * "Cached" results for dabase for looking for unpublished entries
50          */
51         private $unpublishedEntriesInstance = NULL;
52
53         // Constants for database table names
54         const DB_TABLE_NODE_DHT = 'node_dht';
55
56         // Constants for database column names
57         const DB_COLUMN_NODE_ID            = 'node_id';
58         const DB_COLUMN_SESSION_ID         = 'session_id';
59         const DB_COLUMN_EXTERNAL_ADDRESS   = 'external_address';
60         const DB_COLUMN_PRIVATE_KEY_HASH   = 'private_key_hash';
61         const DB_COLUMN_NODE_MODE          = 'node_mode';
62         const DB_COLUMN_ACCEPTED_OBJECTS   = 'accepted_object_types';
63         const DB_COLUMN_NODE_LIST          = 'node_list';
64         const DB_COLUMN_PUBLICATION_STATUS = 'publication_status';
65         const DB_COLUMN_ANSWER_STATUS      = 'answer_status';
66         const DB_COLUMN_ACCEPT_BOOTSTRAP   = 'accept_bootstrap';
67
68         // Publication status'
69         const PUBLICATION_STATUS_PENDING = 'PENDING';
70
71         // Exception codes
72         const EXCEPTION_NODE_ALREADY_REGISTERED = 0x800;
73         const EXCEPTION_NODE_NOT_REGISTERED     = 0x801;
74
75         /**
76          * Protected constructor
77          *
78          * @return      void
79          */
80         protected function __construct () {
81                 // Call parent constructor
82                 parent::__construct(__CLASS__);
83         }
84
85         /**
86          * Creates an instance of this database frontend by a provided user class
87          *
88          * @return      $frontendInstance       An instance of the created frontend class
89          */
90         public static final function createNodeDistributedHashTableDatabaseFrontend () {
91                 // Get a new instance
92                 $frontendInstance = new NodeDistributedHashTableDatabaseFrontend();
93
94                 // Set (primary!) table name
95                 $frontendInstance->setTableName(self::DB_TABLE_NODE_DHT);
96
97                 // Get node instance
98                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: Creating node instance ...');
99                 $nodeInstance = NodeObjectFactory::createNodeInstance();
100
101                 // And set it here
102                 $frontendInstance->setNodeInstance($nodeInstance);
103
104                 // Return the instance
105                 return $frontendInstance;
106         }
107
108         /**
109          * Static getter for an array of all DHT database entries
110          *
111          * @return      $elements       All elements for the DHT dabase
112          */
113         public static final function getAllElements () {
114                 // Create array and ...
115                 $elements = array(
116                         self::DB_COLUMN_NODE_ID,
117                         self::DB_COLUMN_SESSION_ID,
118                         self::DB_COLUMN_EXTERNAL_ADDRESS,
119                         self::DB_COLUMN_PRIVATE_KEY_HASH,
120                         self::DB_COLUMN_NODE_MODE,
121                         self::DB_COLUMN_ACCEPTED_OBJECTS,
122                         self::DB_COLUMN_NODE_LIST
123                 );
124
125                 // ... return it
126                 return $elements;
127         }
128
129         /**
130          * Prepares a search instance for given node data
131          *
132          * @param       $nodeData                       An array with valid node data
133          * @return      $searchInstance         An instance of a SearchCriteria class
134          */
135         private function prepareSearchInstance (array $nodeData) {
136                 // Assert on array elements
137                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: CALLED!');
138                 assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
139
140                 // Get instance
141                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
142
143                 // Search for node id and limit it to one entry
144                 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID, $nodeData[self::DB_COLUMN_NODE_ID]);
145                 $searchInstance->setLimit(1);
146
147                 // Return it
148                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: EXIT!');
149                 return $searchInstance;
150         }
151
152         /**
153          * Prepares a "local" instance of a StoreableCriteria class with all node
154          * data for insert/update queries. This data set contains data from *this*
155          * (local) node.
156          *
157          * @return      $dataSetInstance        An instance of a StoreableCriteria class
158          */
159         private function prepareLocalDataSetInstance () {
160                 // Debug message
161                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: CALLED!');
162
163                 // Get request instances
164                 $requestInstance = FrameworkBootstrap::getRequestInstance();
165
166                 // Get a dataset instance
167                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
168
169                 // Set the primary key
170                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_NODE_ID);
171
172                 // Get Universal Node Locator and "explode" it
173                 $locatorInstance = $this->getNodeInstance()->determineUniversalNodeLocator();
174
175                 // Get external UNL
176                 $externalUnl = $locatorInstance->getExternalUnl();
177
178                 // Make sure both is valid
179                 // @TODO Bad check on UNL, better use a proper validator
180                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: externalUnl=' . $externalUnl);
181                 assert($externalUnl !== 'invalid');
182
183                 // Get an array of all accepted object types
184                 $objectList = $this->getNodeInstance()->getListFromAcceptedObjectTypes();
185
186                 // Make sure this is an array
187                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: objectList()=' . count($objectList));
188                 assert(is_array($objectList));
189
190                 // Add public node data
191                 $dataSetInstance->addCriteria(self::DB_COLUMN_NODE_MODE       , $requestInstance->getRequestElement('mode'));
192                 $dataSetInstance->addCriteria(self::DB_COLUMN_EXTERNAL_ADDRESS, $externalUnl);
193                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: nodeInstance->nodeId=' . $this->getNodeInstance()->getNodeId());
194                 $dataSetInstance->addCriteria(self::DB_COLUMN_NODE_ID         , $this->getNodeInstance()->getNodeId());
195                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: nodeInstance->sessionId=' . $this->getNodeInstance()->getSessionId());
196                 $dataSetInstance->addCriteria(self::DB_COLUMN_SESSION_ID      , $this->getNodeInstance()->getSessionId());
197                 $dataSetInstance->addCriteria(self::DB_COLUMN_PRIVATE_KEY_HASH, $this->getNodeInstance()->getNodePrivateKeyHash());
198                 $dataSetInstance->addCriteria(self::DB_COLUMN_ACCEPTED_OBJECTS, implode(BaseHubNode::OBJECT_LIST_SEPARATOR, $objectList));
199                 $dataSetInstance->addCriteria(self::DB_COLUMN_ACCEPT_BOOTSTRAP, $this->translateBooleanToYesNo($this->getNodeInstance()->isAcceptingDhtBootstrap()));
200
201                 // Return it
202                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: dataSetInstance=' . $dataSetInstance->__toString() . ' - EXIT!');
203                 return $dataSetInstance;
204         }
205
206         /**
207          * Getter for result instance for unpublished entries
208          *
209          * @return      $unpublishedEntriesInstance             Result instance
210          */
211         public final function getUnpublishedEntriesInstance () {
212                 return $this->unpublishedEntriesInstance;
213         }
214
215         /**
216          * Checks whether the local (*this*) node is registered in the DHT by
217          * checking if the external address is found.
218          *
219          * @return      $isRegistered   Whether *this* node is registered in the DHT
220          */
221         public function isLocalNodeRegistered () {
222                 // Get a search criteria instance
223                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: CALLED!');
224                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
225
226                 // Get Universal Node Locator and "explode" it
227                 $locatorInstance = $this->getNodeInstance()->determineUniversalNodeLocator();
228
229                 // Make sure the external address is set and not invalid
230                 // @TODO Bad check on UNL, better use a proper validator
231                 $externalUnl = $locatorInstance->getExternalUnl();
232                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-WRAPPER: externalUnl=%s', $externalUnl));
233                 assert($externalUnl != 'invalid');
234
235                 // Add Universal Node Locator/node id as criteria
236                 $searchInstance->addCriteria(self::DB_COLUMN_EXTERNAL_ADDRESS, $externalUnl);
237                 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID         , $this->getNodeInstance()->getNodeId());
238                 $searchInstance->addCriteria(self::DB_COLUMN_SESSION_ID      , $this->getNodeInstance()->getSessionId());
239                 $searchInstance->setLimit(1);
240
241                 // Query database and get a result instance back
242                 $resultInstance = $this->doSelectByCriteria($searchInstance);
243
244                 // Cache result of if there is an entry, valid() will tell us if an entry is there
245                 $isRegistered = $resultInstance->valid();
246
247                 // Return result
248                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-WRAPPER: isRegistered=%d - EXIT!', intval($isRegistered)));
249                 return $isRegistered;
250         }
251
252         /**
253          * Registeres the local (*this*) node with its data in the DHT.
254          *
255          * @return      void
256          */
257         public function registerLocalNode () {
258                 // Debug message
259                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: CALLED!');
260
261                 // Assert to make sure this method is called with no record in DB (the actual backend of the DHT)
262                 assert(!$this->isLocalNodeRegistered());
263
264                 // Get prepared data set instance
265                 $dataSetInstance = $this->prepareLocalDataSetInstance();
266
267                 // "Insert" this dataset instance completely into the database
268                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: Calling this->queryInsertDataSet(' . $dataSetInstance->__toString() . ') ...');
269                 $this->queryInsertDataSet($dataSetInstance);
270
271                 // Debug message
272                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: EXIT!');
273         }
274
275         /**
276          * Updates local (*this*) node's data in DHT, this is but not limited to the
277          * session id, ip number (and/or hostname) and port number.
278          *
279          * @return      void
280          */
281         public function updateLocalNode () {
282                 // Debug message
283                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: CALLED!');
284
285                 // Assert to make sure this method is called with one record in DB (the actual backend of the DHT)
286                 assert($this->isLocalNodeRegistered());
287
288                 // Get search criteria
289                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
290
291                 // Search for node id and limit it to one entry
292                 $searchInstance->addCriteria(self::DB_COLUMN_NODE_ID, $this->getNodeInstance()->getNodeId());
293                 $searchInstance->setLimit(1);
294
295                 // Get a prepared dataset instance
296                 $dataSetInstance = $this->prepareLocalDataSetInstance();
297
298                 // Set search instance
299                 $dataSetInstance->setSearchInstance($searchInstance);
300
301                 // Update DHT database record
302                 $this->queryUpdateDataSet($dataSetInstance);
303
304                 // Debug message
305                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: EXIT!');
306         }
307
308         /**
309          * Finds a node locally by given session id
310          *
311          * @param       $sessionId      Session id to lookup
312          * @return      $resultInstance         An instance of a SearchableResult class
313          * @throws      InvalidArgumentException        If parameter $sessionId is not valid
314          */
315         public function findNodeLocalBySessionId ($sessionId) {
316                 // Validate parameter
317                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-WRAPPER: sessionId=%s - CALLED!', $sessionId));
318                 if (empty($sessionId)) {
319                         // Cannot be empty
320                         throw new InvalidArgumentException('Parameter "sessionId" is empty.');
321                 }
322
323                 // Get search criteria
324                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
325
326                 // Search for session id and limit it to one entry
327                 $searchInstance->addCriteria(self::DB_COLUMN_SESSION_ID, $sessionId);
328                 $searchInstance->setLimit(1);
329
330                 // Query database and get a result instance back
331                 $resultInstance = $this->doSelectByCriteria($searchInstance);
332
333                 // Return result instance
334                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-WRAPPER: resultInstance->valid()=%d - EXIT!', intval($resultInstance->valid())));
335                 return $resultInstance;
336         }
337
338         /**
339          * Finds a node locally by given UNL instance
340          *
341          * @param       $locatorInstance        An instance of a LocateableNode class
342          * @return      $resultInstance         An instance of a SearchableResult class
343          */
344         public function findNodeLocalByLocatorInstance (LocateableNode $locatorInstance) {
345                 // Get search criteria
346                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-WRAPPER: locatorInstance=%s - CALLED!', $locatorInstance->__toString()));
347                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
348
349                 // Search for session id and limit it to one entry
350                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-WRAPPER: externalUnl=%s', $locatorInstance->getExternalUnl()));
351                 $searchInstance->addCriteria(self::DB_COLUMN_EXTERNAL_ADDRESS, $locatorInstance->getExternalUnl());
352                 $searchInstance->setLimit(1);
353
354                 // Query database and get a result instance back
355                 $resultInstance = $this->doSelectByCriteria($searchInstance);
356
357                 // Return result instance
358                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-WRAPPER: resultInstance->valid()=%d - EXIT!', intval($resultInstance->valid())));
359                 return $resultInstance;
360         }
361
362         /**
363          * Registeres a node by given message data.
364          *
365          * @param       $messageInstance        An instance of a DeliverableMessage class
366          * @param       $handlerInstance        An instance of a HandleableDataSet class
367          * @return      void
368          */
369         public function registerNodeByMessageInstance (DeliverableMessage $messageInstance, HandleableDataSet $handlerInstance) {
370                 // Debug message
371                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: handlerInstance=' . $handlerInstance->__toString() . ' - CALLED!');
372
373                 // Get a data set instance
374                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
375
376                 // Set primary key (session id)
377                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
378
379                 // Add all array elements
380                 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageInstance);
381
382                 // Remove 'node_list'
383                 $dataSetInstance->unsetCriteria(self::DB_COLUMN_NODE_LIST);
384
385                 // Run the "INSERT" query
386                 $this->queryInsertDataSet($dataSetInstance);
387
388                 // Debug message
389                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER - EXIT!');
390         }
391
392         /**
393          * Updates an existing entry in node list
394          *
395          * @param       $messageInstance        An instance of a DeliverableMessage class
396          * @param       $handlerInstance        An instance of a HandleableDataSet class
397          * @param       $searchInstance         An instance of LocalSearchCriteria class
398          * @return      void
399          */
400         public function updateNodeByMessageInstance (DeliverableMessage $messageInstance, HandleableDataSet $handlerInstance, LocalSearchCriteria $searchInstance) {
401                 // Debug message
402                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: CALLED!');
403
404                 // Get a data set instance
405                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
406
407                 // Add search instance
408                 $dataSetInstance->setSearchInstance($searchInstance);
409
410                 // Set primary key (session id)
411                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
412
413                 // Add all array elements
414                 $handlerInstance->addArrayToDataSet($dataSetInstance, $messageInstance);
415
416                 // Remove 'node_list'
417                 $dataSetInstance->unsetCriteria(self::DB_COLUMN_NODE_LIST);
418
419                 // Run the "UPDATE" query
420                 $this->queryUpdateDataSet($dataSetInstance);
421
422                 // Debug message
423                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: EXIT!');
424         }
425
426         /**
427          * Determines whether the given node data is already inserted in the DHT
428          *
429          * @param       $nodeData               An array with valid node data
430          * @return      $isRegistered   Whether the given node data is already inserted
431          */
432         public function isNodeRegistered (array $nodeData) {
433                 // Debug message
434                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: CALLED!');
435
436                 // Assert on array elements
437                 assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
438
439                 // Debug message
440                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: node-id=' . $nodeData[self::DB_COLUMN_NODE_ID]);
441
442                 // Get search criteria
443                 $searchInstance = $this->prepareSearchInstance($nodeData);
444
445                 // Query database and get a result instance back
446                 $resultInstance = $this->doSelectByCriteria(
447                         // Search instance
448                         $searchInstance,
449                         // Only look for these array elements ("keys")
450                         array(
451                                 self::DB_COLUMN_NODE_ID          => TRUE,
452                                 self::DB_COLUMN_EXTERNAL_ADDRESS => TRUE
453                         )
454                 );
455
456                 // Check if there is an entry
457                 $isRegistered = $resultInstance->valid();
458
459                 // Debug message
460                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: isRegistered=' . intval($isRegistered) . ' - EXIT!');
461
462                 // Return registration status
463                 return $isRegistered;
464         }
465
466         /**
467          * Registers a node with given data in the DHT. If the node is already
468          * registered this method shall throw an exception.
469          *
470          * @param       $nodeData       An array with valid node data
471          * @return      void
472          * @throws      NodeAlreadyRegisteredException  If the node is already registered
473          */
474         public function registerNode (array $nodeData) {
475                 // Debug message
476                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: CALLED!');
477
478                 // Assert on array elements
479                 assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
480
481                 // Is the node registered?
482                 if ($this->isNodeRegistered($nodeData)) {
483                         // Throw an exception
484                         throw new NodeAlreadyRegisteredException(array($this, $nodeData), self::EXCEPTION_NODE_ALREADY_REGISTERED);
485                 } // END - if
486
487                 // @TODO Unimplemented part
488                 $this->partialStub('nodeData=' . print_r($nodeData, TRUE));
489
490                 // Debug message
491                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: EXIT!');
492         }
493
494         /**
495          * Updates a node's entry in the DHT with given data. This will enrich or
496          * just update already exsiting data. If the node is not found this method
497          * shall throw an exception.
498          *
499          * @param       $nodeData       An array with valid node data
500          * @return      void
501          * @throws      NodeDataMissingException        If the node's data is missing
502          */
503         public function updateNode (array $nodeData) {
504                 // Debug message
505                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: nodeData=' . print_r($nodeData, TRUE));
506                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: CALLED!');
507
508                 // Assert on array elements
509                 assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
510
511                 // Debug message
512                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: Updating DHT entry for node-id=' . $nodeData[self::DB_COLUMN_NODE_ID] . ' ...');
513
514                 // Is the node registered?
515                 if (!$this->isNodeRegistered($nodeData)) {
516                         // No, then throw an exception
517                         throw new NodeDataMissingException(array($this, $nodeData), self::EXCEPTION_NODE_NOT_REGISTERED);
518                 } // END - if
519
520                 // Get a search instance
521                 $searchInstance = $this->prepareSearchInstance($nodeData);
522
523                 // Get a data set instance
524                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
525
526                 // Add search instance
527                 $dataSetInstance->setSearchInstance($searchInstance);
528
529                 // Set primary key (session id)
530                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_SESSION_ID);
531
532                 // Add all array elements
533                 $this->getNodeInstance()->addArrayToDataSet($dataSetInstance, $nodeData);
534
535                 // Remove 'node_list'
536                 $dataSetInstance->unsetCriteria(self::DB_COLUMN_NODE_LIST);
537
538                 // Run the "UPDATE" query
539                 $this->queryUpdateDataSet($dataSetInstance);
540
541                 // Debug message
542                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: EXIT!');
543         }
544
545         /**
546          * Checks whether there are unpublished entries
547          *
548          * @return      $hasUnpublished         Whether there are unpublished entries
549          * @todo        Add minimum/maximum age limitations
550          */
551         public function hasUnpublishedEntries () {
552                 // Get search instance
553                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
554
555                 // Add exclusion key which is the publish status
556                 $searchInstance->addExcludeCriteria(NodeDistributedHashTableDatabaseFrontend::DB_COLUMN_PUBLICATION_STATUS, NodeDistributedHashTableDatabaseFrontend::PUBLICATION_STATUS_PENDING);
557
558                 // Remember search instance
559                 $this->setSearchInstance($searchInstance);
560
561                 // Run the query
562                 $this->unpublishedEntriesInstance = $this->doSelectByCriteria($searchInstance);
563
564                 // Check pending entries
565                 $hasUnpublished = $this->unpublishedEntriesInstance->valid();
566
567                 // Debug message
568                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: EXIT!');
569
570                 // Return it
571                 return $hasUnpublished;
572         }
573
574         /**
575          * Initializes publication of DHT entries. This does only prepare
576          * publication. The next step is to pickup such prepared entries and publish
577          * them by uploading to other (recently appeared) DHT members.
578          *
579          * @return      void
580          * @todo        Add timestamp to dataset instance
581          */
582         public function initEntryPublication () {
583                 // Debug message
584                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: CALLED!');
585
586                 /*
587                  * Make sure that hasUnpublishedEntries() has been called first by
588                  * asserting on the "cached" object instance. This "caching" saves some
589                  * needless queries as this method shall be called immediately after
590                  * hasUnpublishedEntries() returns TRUE.
591                  */
592                 assert($this->unpublishedEntriesInstance instanceof SearchableResult);
593
594                 // Result is still okay?
595                 assert($this->unpublishedEntriesInstance->valid());
596
597                 // Remove 'publication_status'
598                 $this->getSearchInstance()->unsetCriteria(self::DB_COLUMN_PUBLICATION_STATUS);
599
600                 // Make sure all entries are marked as pending, first get a dataset instance.
601                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
602
603                 // Add search instance
604                 $dataSetInstance->setSearchInstance($this->getSearchInstance());
605
606                 // Set primary key (node id)
607                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_NODE_ID);
608
609                 // Add criteria (that should be set)
610                 $dataSetInstance->addCriteria(self::DB_COLUMN_PUBLICATION_STATUS, self::PUBLICATION_STATUS_PENDING);
611
612                 // Run the "UPDATE" query
613                 $this->queryUpdateDataSet($dataSetInstance);
614
615                 // Debug message
616                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: EXIT!');
617         }
618
619         /**
620          * Removes non-public data from given array.
621          *
622          * @param       $data   An array with possible non-public data that needs to be removed.
623          * @return      $data   A cleaned up array with only public data.
624          */
625         public function removeNonPublicDataFromArray(array $data) {
626                 // Currently call only inner method
627                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: Calling parent::removeNonPublicDataFromArray(data) ...');
628                 $data = parent::removeNonPublicDataFromArray($data);
629                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: data[]=' . gettype($data));
630
631                 // Return cleaned data
632                 return $data;
633         }
634
635         /**
636          * Find recipients for given package data and exclude the sender
637          *
638          * @param       $packageInstance        An instance of a DeliverablePackage class
639          * @return      $recipients                     An indexed array with DHT recipients
640          */
641         public function getResultFromExcludedSender (DeliverablePackage $packageInstance) {
642                 // Debug message
643                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: CALLED!');
644
645                 // Get max recipients
646                 $maxRecipients = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('max_dht_recipients');
647
648                 // First creata a search instance
649                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
650
651                 // Then exclude 'sender' field as the sender is the current (*this*) node
652                 $searchInstance->addExcludeCriteria(NodeDistributedHashTableDatabaseFrontend::DB_COLUMN_SESSION_ID, $packageInstance->getSenderAddress());
653
654                 // Set limit to maximum DHT recipients
655                 $searchInstance->setLimit($maxRecipients);
656
657                 // Get a result instance back from DHT database frontend.
658                 $resultInstance = $this->doSelectByCriteria($searchInstance);
659
660                 // Debug message
661                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: EXIT!');
662
663                 // Return result instance
664                 return $resultInstance;
665         }
666
667         /**
668          * Find recopients by given key/value pair. First look for the key and if it
669          * matches, compare the value.
670          *
671          * @param       $key                    Key to look for
672          * @param       $value                  Value to compare if key matches
673          * @return      $recipients             An indexed array with DHT recipients
674          * @throws      InvalidArgumentException        If $key is empty
675          */
676         public function getResultFromKeyValue (string $key, $value) {
677                 // Is key parameter valid?
678                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-WRAPPER: key=%s,value[%s]=%s - CALLED!', $key, gettype($value), $value));
679                 if (empty($key)) {
680                         // Throw exception
681                         throw new InvalidArgumentException('Parameter key is empty');
682                 }
683
684                 // Get max recipients
685                 $maxRecipients = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('max_dht_recipients');
686
687                 // First creata a search instance
688                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
689
690                 // Find the key/value pair
691                 $searchInstance->addCriteria($key, $value);
692
693                 // Get a result instance back from DHT database frontend.
694                 $resultInstance = $this->doSelectByCriteria($searchInstance);
695
696                 // Return result instance
697                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-WRAPPER: resultInstance=%s - EXIT!', $resultInstance->__toString()));
698                 return $resultInstance;
699         }
700
701         /**
702          * Enable DHT bootstrap request acceptance for local node
703          *
704          * @return      void
705          */
706         public function enableAcceptDhtBootstrap () {
707                 // Debug message
708                 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: Enabling DHT bootstrap requests ...');
709
710                 // Is the node already registered?
711                 if ($this->isLocalNodeRegistered()) {
712                         // Just update our record
713                         $this->updateLocalNode();
714                 } else {
715                         // Register it
716                         $this->registerLocalNode();
717                 }
718         }
719
720 }