]> git.mxchange.org Git - hub.git/blob - application/hub/main/package/class_NetworkPackage.php
3c8aa6590ad6d8979ce8ca9da251dabe20103c7c
[hub.git] / application / hub / main / package / class_NetworkPackage.php
1 <?php
2 /**
3  * A NetworkPackage class. This class implements Deliverable and Receivable
4  * because all network packages should be deliverable to other nodes and
5  * receivable from other nodes. It further provides methods for reading raw
6  * content from template engines and feeding it to the stacker for undeclared
7  * packages.
8  *
9  * The factory method requires you to provide a compressor class (which must
10  * implement the Compressor interface). If you don't want any compression (not
11  * adviceable due to increased network load), please use the NullCompressor
12  * class and encode it with BASE64 for a more error-free transfer over the
13  * Internet.
14  *
15  * For performance reasons, this class should only be instanciated once and then
16  * used as a "pipe-through" class.
17  *
18  * @author              Roland Haeder <webmaster@shipsimu.org>
19  * @version             0.0.0
20  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Hub Developer Team
21  * @license             GNU GPL 3.0 or any newer version
22  * @link                http://www.shipsimu.org
23  * @todo                Needs to add functionality for handling the object's type
24  *
25  * This program is free software: you can redistribute it and/or modify
26  * it under the terms of the GNU General Public License as published by
27  * the Free Software Foundation, either version 3 of the License, or
28  * (at your option) any later version.
29  *
30  * This program is distributed in the hope that it will be useful,
31  * but WITHOUT ANY WARRANTY; without even the implied warranty of
32  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33  * GNU General Public License for more details.
34  *
35  * You should have received a copy of the GNU General Public License
36  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
37  */
38 class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, Registerable, Visitable {
39         /**
40          * Package mask for compressing package data:
41          * 0: Compressor extension
42          * 1: Raw package data
43          * 2: Tags, seperated by semicolons, no semicolon is required if only one tag is needed
44          * 3: Checksum
45          *                     0  1  2  3
46          */
47         const PACKAGE_MASK = '%s%s%s%s%s%s%s';
48
49         /**
50          * Separator for the above mask
51          */
52         const PACKAGE_MASK_SEPARATOR = '^';
53
54         /**
55          * Size of an array created by invoking
56          * explode(NetworkPackage::PACKAGE_MASK_SEPARATOR, $content).
57          */
58         const PACKAGE_CONTENT_ARRAY_SIZE = 4;
59
60         /**
61          * Separator for checksum
62          */
63         const PACKAGE_CHECKSUM_SEPARATOR = '_';
64
65         /**
66          * Array indexes for above mask, start with zero
67          */
68         const INDEX_COMPRESSOR_EXTENSION = 0;
69         const INDEX_PACKAGE_DATA         = 1;
70         const INDEX_TAGS                 = 2;
71         const INDEX_CHECKSUM             = 3;
72
73         /**
74          * Array indexes for raw package array
75          */
76         const INDEX_PACKAGE_SENDER    = 0;
77         const INDEX_PACKAGE_RECIPIENT = 1;
78         const INDEX_PACKAGE_CONTENT   = 2;
79         const INDEX_PACKAGE_STATUS    = 3;
80         const INDEX_PACKAGE_SIGNATURE = 4;
81
82         /**
83          * Size of the decoded data array ('status' is not included)
84          */
85         const DECODED_DATA_ARRAY_SIZE = 4;
86
87         /**
88          * Named array elements for decoded package content
89          */
90         const PACKAGE_CONTENT_EXTENSION = 'compressor';
91         const PACKAGE_CONTENT_MESSAGE   = 'message';
92         const PACKAGE_CONTENT_TAGS      = 'tags';
93         const PACKAGE_CONTENT_CHECKSUM  = 'checksum';
94
95         /**
96          * Named array elements for package data
97          */
98         const PACKAGE_DATA_SENDER    = 'sender';
99         const PACKAGE_DATA_RECIPIENT = 'recipient';
100         const PACKAGE_DATA_PROTOCOL  = 'protocol';
101         const PACKAGE_DATA_CONTENT   = 'content';
102         const PACKAGE_DATA_STATUS    = 'status';
103         const PACKAGE_DATA_SIGNATURE = 'signature';
104
105         /**
106          * All package status
107          */
108         const PACKAGE_STATUS_NEW     = 'new';
109         const PACKAGE_STATUS_FAILED  = 'failed';
110         const PACKAGE_STATUS_DECODED = 'decoded';
111         const PACKAGE_STATUS_FAKED   = 'faked';
112
113         /**
114          * Constants for message data array
115          */
116         const MESSAGE_ARRAY_DATA = 'message_data';
117         const MESSAGE_ARRAY_TYPE = 'message_type';
118
119         /**
120          * Generic answer status field
121          */
122
123         /**
124          * Tags separator
125          */
126         const PACKAGE_TAGS_SEPARATOR = ';';
127
128         /**
129          * Raw package data separator
130          */
131         const PACKAGE_DATA_SEPARATOR = '#';
132
133         /**
134          * Separator for more than one recipient
135          */
136         const PACKAGE_RECIPIENT_SEPARATOR = ':';
137
138         /**
139          * Network target (alias): 'upper nodes'
140          */
141         const NETWORK_TARGET_UPPER = 'upper';
142
143         /**
144          * Network target (alias): 'self'
145          */
146         const NETWORK_TARGET_SELF = 'self';
147
148         /**
149          * Network target (alias): 'dht'
150          */
151         const NETWORK_TARGET_DHT = 'dht';
152
153         /**
154          * TCP package size in bytes
155          */
156         const TCP_PACKAGE_SIZE = 512;
157
158         /**************************************************************************
159          *                    Stacker for out-going packages                      *
160          **************************************************************************/
161
162         /**
163          * Stacker name for "undeclared" packages
164          */
165         const STACKER_NAME_UNDECLARED = 'package_undeclared';
166
167         /**
168          * Stacker name for "declared" packages (which are ready to send out)
169          */
170         const STACKER_NAME_DECLARED = 'package_declared';
171
172         /**
173          * Stacker name for "out-going" packages
174          */
175         const STACKER_NAME_OUTGOING = 'package_outgoing';
176
177         /**************************************************************************
178          *                     Stacker for incoming packages                      *
179          **************************************************************************/
180
181         /**
182          * Stacker name for "incoming" decoded raw data
183          */
184         const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
185
186         /**
187          * Stacker name for handled decoded raw data
188          */
189         const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
190
191         /**
192          * Stacker name for "chunked" decoded raw data
193          */
194         const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
195
196         /**************************************************************************
197          *                     Stacker for incoming messages                      *
198          **************************************************************************/
199
200         /**
201          * Stacker name for new messages
202          */
203         const STACKER_NAME_NEW_MESSAGE = 'package_new_message';
204
205         /**
206          * Stacker name for processed messages
207          */
208         const STACKER_NAME_PROCESSED_MESSAGE = 'package_processed_message';
209
210         /**************************************************************************
211          *                   Stacker for other/internal purposes                  *
212          **************************************************************************/
213
214         /**
215          * Stacker name for "back-buffered" packages
216          */
217         const STACKER_NAME_BACK_BUFFER = 'package_backbuffer';
218
219         /**************************************************************************
220          *                            Protocol names                              *
221          **************************************************************************/
222         const PROTOCOL_TCP = 'TCP';
223         const PROTOCOL_UDP = 'UDP';
224
225         /**
226          * Protected constructor
227          *
228          * @return      void
229          */
230         protected function __construct () {
231                 // Call parent constructor
232                 parent::__construct(__CLASS__);
233         }
234
235         /**
236          * Creates an instance of this class
237          *
238          * @param       $compressorInstance             A Compressor instance for compressing the content
239          * @return      $packageInstance                An instance of a Deliverable class
240          */
241         public static final function createNetworkPackage (Compressor $compressorInstance) {
242                 // Get new instance
243                 $packageInstance = new NetworkPackage();
244
245                 // Now set the compressor instance
246                 $packageInstance->setCompressorInstance($compressorInstance);
247
248                 /*
249                  * We need to initialize a stack here for our packages even for those
250                  * which have no recipient address and stamp... ;-) This stacker will
251                  * also be used for incoming raw data to handle it.
252                  */
253                 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
254
255                 // At last, set it in this class
256                 $packageInstance->setStackerInstance($stackerInstance);
257
258                 // Init all stacker
259                 $packageInstance->initStacks();
260
261                 // Get a visitor instance for speeding up things and set it
262                 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
263                 $packageInstance->setVisitorInstance($visitorInstance);
264
265                 // Get crypto instance and set it, too
266                 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
267                 $packageInstance->setCryptoInstance($cryptoInstance);
268
269                 // Get a singleton package assembler instance from factory and set it here, too
270                 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
271                 $packageInstance->setAssemblerInstance($assemblerInstance);
272
273                 // Return the prepared instance
274                 return $packageInstance;
275         }
276
277         /**
278          * Initialize all stackers
279          *
280          * @param       $forceReInit    Whether to force reinitialization of all stacks
281          * @return      void
282          */
283         protected function initStacks ($forceReInit = FALSE) {
284                 // Initialize all
285                 $this->getStackerInstance()->initStacks(array(
286                         self::STACKER_NAME_UNDECLARED,
287                         self::STACKER_NAME_DECLARED,
288                         self::STACKER_NAME_OUTGOING,
289                         self::STACKER_NAME_DECODED_INCOMING,
290                         self::STACKER_NAME_DECODED_HANDLED,
291                         self::STACKER_NAME_DECODED_CHUNKED,
292                         self::STACKER_NAME_NEW_MESSAGE,
293                         self::STACKER_NAME_PROCESSED_MESSAGE,
294                         self::STACKER_NAME_BACK_BUFFER
295                 ), $forceReInit);
296         }
297
298         /**
299          * "Getter" for hash from given content
300          *
301          * @param       $content        Raw package content
302          * @return      $hash           Hash for given package content
303          */
304         private function getHashFromContent ($content) {
305                 // Debug message
306                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
307
308                 // Create the hash
309                 // @TODO md5() is very weak, but it needs to be fast
310                 $hash = md5(
311                         $content .
312                         self::PACKAGE_CHECKSUM_SEPARATOR .
313                         $this->getSessionId() .
314                         self::PACKAGE_CHECKSUM_SEPARATOR .
315                         $this->getCompressorInstance()->getCompressorExtension()
316                 );
317
318                 // Debug message
319                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',hash=' . $hash . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
320
321                 // And return it
322                 return $hash;
323         }
324
325         /**
326          * Checks whether the checksum (sometimes called "hash") is the same
327          *
328          * @param       $decodedContent         Package raw content
329          * @param       $decodedData            Whole raw package data array
330          * @return      $isChecksumValid        Whether the checksum is the same
331          */
332         private function isChecksumValid (array $decodedContent, array $decodedData) {
333                 // Get checksum
334                 $checksum = $this->getHashFromContentSessionId($decodedContent, $decodedData[self::PACKAGE_DATA_SENDER]);
335
336                 // Is it the same?
337                 $isChecksumValid = ($checksum == $decodedContent[self::PACKAGE_CONTENT_CHECKSUM]);
338
339                 // Return it
340                 return $isChecksumValid;
341         }
342
343         /**
344          * Change the package with given status in given stack
345          *
346          * @param       $packageData    Raw package data in an array
347          * @param       $stackerName    Name of the stacker
348          * @param       $newStatus              New status to set
349          * @return      void
350          */
351         private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
352                 // Skip this for empty stacks
353                 if ($this->getStackerInstance()->isStackEmpty($stackerName)) {
354                         // This avoids an exception after all packages has failed
355                         return;
356                 } // END - if
357
358                 // Pop the entry (it should be it)
359                 $nextData = $this->getStackerInstance()->popNamed($stackerName);
360
361                 // Compare both signatures
362                 assert($nextData[self::PACKAGE_DATA_SIGNATURE] == $packageData[self::PACKAGE_DATA_SIGNATURE]);
363
364                 // Temporary set the new status
365                 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
366
367                 // And push it again
368                 $this->getStackerInstance()->pushNamed($stackerName, $packageData);
369         }
370
371         /**
372          * "Getter" for hash from given content and sender's session id
373          *
374          * @param       $decodedContent         Raw package content
375          * @param       $sessionId                      Session id of the sender
376          * @return      $hash                           Hash for given package content
377          */
378         public function getHashFromContentSessionId (array $decodedContent, $sessionId) {
379                 // Debug message
380                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($decodedContent[self::PACKAGE_CONTENT_MESSAGE]) . ',sender=' . $sessionId . ',compressor=' . $decodedContent[self::PACKAGE_CONTENT_EXTENSION]);
381
382                 // Create the hash
383                 // @TODO md5() is very weak, but it needs to be fast
384                 $hash = md5(
385                         $decodedContent[self::PACKAGE_CONTENT_MESSAGE] .
386                         self::PACKAGE_CHECKSUM_SEPARATOR .
387                         $sessionId .
388                         self::PACKAGE_CHECKSUM_SEPARATOR .
389                         $decodedContent[self::PACKAGE_CONTENT_EXTENSION]
390                 );
391
392                 // And return it
393                 return $hash;
394         }
395
396         ///////////////////////////////////////////////////////////////////////////
397         //                   Delivering packages / raw data
398         ///////////////////////////////////////////////////////////////////////////
399
400         /**
401          * Declares the given raw package data by discovering recipients
402          *
403          * @param       $packageData    Raw package data in an array
404          * @return      void
405          */
406         private function declareRawPackageData (array $packageData) {
407                 // Make sure the required field is there
408                 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
409
410                 /*
411                  * We need to disover every recipient, just in case we have a
412                  * multi-recipient entry like 'upper' is. 'all' may be a not so good
413                  * target because it causes an overload on the network and may be
414                  * abused for attacking the network with large packages.
415                  */
416                 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
417
418                 // Discover all recipients, this may throw an exception
419                 $discoveryInstance->discoverRecipients($packageData);
420
421                 // Now get an iterator
422                 $iteratorInstance = $discoveryInstance->getIterator();
423
424                 // Rewind back to the beginning
425                 $iteratorInstance->rewind();
426
427                 // ... and begin iteration
428                 while ($iteratorInstance->valid()) {
429                         // Get current entry
430                         $currentRecipient = $iteratorInstance->current();
431
432                         // Debug message
433                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Setting recipient to ' . $currentRecipient . ',previous=' . $packageData[self::PACKAGE_DATA_RECIPIENT]);
434
435                         // Set the recipient
436                         $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
437
438                         // Push the declared package to the next stack.
439                         $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
440
441                         // Debug message
442                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package declared for recipient ' . $currentRecipient);
443
444                         // Skip to next entry
445                         $iteratorInstance->next();
446                 } // END - while
447
448                 /*
449                  * The recipient list can be cleaned up here because the package which
450                  * shall be delivered has already been added for all entries from the
451                  * list.
452                  */
453                 $discoveryInstance->clearRecipients();
454         }
455
456         /**
457          * Delivers raw package data. In short, this will discover the raw socket
458          * resource through a discovery class (which will analyse the receipient of
459          * the package), register the socket with the connection (handler/helper?)
460          * instance and finally push the raw data on our outgoing queue.
461          *
462          * @param       $packageData    Raw package data in an array
463          * @return      void
464          */
465         private function deliverRawPackageData (array $packageData) {
466                 /*
467                  * This package may become big, depending on the shared object size or
468                  * delivered message size which shouldn't be so long (to save
469                  * bandwidth). Because of the nature of the used protocol (TCP) we need
470                  * to split it up into smaller pieces to fit it into a TCP frame.
471                  *
472                  * So first we need (again) a discovery class but now a protocol
473                  * discovery to choose the right socket resource. The discovery class
474                  * should take a look at the raw package data itself and then decide
475                  * which (configurable!) protocol should be used for that type of
476                  * package.
477                  */
478                 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
479
480                 // Now discover the right protocol
481                 $socketResource = $discoveryInstance->discoverSocket($packageData, BaseConnectionHelper::CONNECTION_TYPE_OUTGOING);
482
483                 // Debug message
484                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
485
486                 // Debug message
487                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: stateInstance=' . $helperInstance->getStateInstance());
488                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
489
490                 // Is it not there?
491                 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
492                         // The socket needs to be put in a special registry that can handle such data
493                         $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
494
495                         // Get the connection helper from registry
496                         $helperInstance = Registry::getRegistry()->getInstance('connection');
497
498                         // And make sure it is valid
499                         assert($helperInstance instanceof ConnectionHelper);
500
501                         // Debug message
502                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Registering socket ' . $socketResource . ' ...');
503
504                         // Then register it
505                         $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
506                 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
507                         // Is not connected, then we cannot send
508                         self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
509
510                         // Shutdown the socket
511                         $this->shutdownSocket($socketResource);
512                 }
513
514                 // Debug message
515                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
516
517                 // Make sure the connection is up
518                 $helperInstance->getStateInstance()->validatePeerStateConnected();
519
520                 // Debug message
521                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
522
523                 // Enqueue it again on the out-going queue, the connection is up and working at this point
524                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
525
526                 // Debug message
527                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
528         }
529
530         /**
531          * Sends waiting packages
532          *
533          * @param       $packageData    Raw package data
534          * @return      void
535          */
536         private function sendOutgoingRawPackageData (array $packageData) {
537                 // Init sent bytes
538                 $sentBytes = 0;
539
540                 // Get the right connection instance
541                 $helperInstance = SocketRegistryFactory::createSocketRegistryInstance()->getHandlerInstanceFromPackageData($packageData);
542
543                 // Is this connection still alive?
544                 if ($helperInstance->isShuttedDown()) {
545                         // This connection is shutting down
546                         // @TODO We may want to do somthing more here?
547                         return;
548                 } // END - if
549
550                 // Sent out package data
551                 $sentBytes = $helperInstance->sendRawPackageData($packageData);
552
553                 // Remember unsent raw bytes in back-buffer, if any
554                 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
555         }
556
557         /**
558          * Generates a signature for given raw package content and sender id
559          *
560          * @param       $content        Raw package data
561          * @param       $senderId       Sender id to generate a signature for
562          * @return      $signature      Signature as BASE64-encoded string
563          */
564         private function generatePackageSignature ($content, $senderId) {
565                 // Hash content and sender id together, use md5() as last algo
566                 $hash = md5($this->getCryptoInstance()->hashString($senderId . $content, $this->getPrivateKey(), FALSE));
567
568                 // Encrypt the content again with the hash as a key
569                 $encryptedContent = $this->getCryptoInstance()->encryptString($content, $hash);
570
571                 // Encode it with BASE64
572                 $signature = base64_encode($encryptedContent);
573
574                 // Return it
575                 return $signature;
576         }
577
578         /**
579          * Checks whether the signature of given package data is 'valid', here that
580          * means it is the same or not.
581          *
582          * @param       $decodedArray           An array with 'decoded' (explode() was mostly called) data
583          * @return      $isSignatureValid       Whether the signature is valid
584          * @todo        Unfinished area, signatures are currently NOT fully supported
585          */
586         private function isPackageSignatureValid (array $decodedArray) {
587                 // Generate the signature of comparing it
588                 $signature = $this->generatePackageSignature($decodedArray[self::INDEX_PACKAGE_CONTENT], $decodedArray[self::INDEX_PACKAGE_SENDER]);
589
590                 // Is it the same?
591                 //$isSignatureValid = 
592                 exit(__METHOD__.': signature='.$signature.chr(10).',decodedArray='.print_r($decodedArray, TRUE));
593         }
594
595         /**
596          * "Enqueues" raw content into this delivery class by reading the raw content
597          * from given helper's template instance and pushing it on the 'undeclared'
598          * stack.
599          *
600          * @param       $helperInstance         An instance of a Helper class
601          * @param       $protocol                       Name of used protocol (TCP/UDP)
602          * @return      void
603          */
604         public function enqueueRawDataFromTemplate (Helper $helperInstance, $protocolName) {
605                 // Get the raw content ...
606                 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
607                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('content(' . strlen($content) . ')=' . $content);
608
609                 // ... and compress it
610                 $content = $this->getCompressorInstance()->compressStream($content);
611
612                 // Add magic in front of it and hash behind it, including BASE64 encoding
613                 $packageContent = sprintf(self::PACKAGE_MASK,
614                         // 1.) Compressor's extension
615                         $this->getCompressorInstance()->getCompressorExtension(),
616                         // - separator
617                         self::PACKAGE_MASK_SEPARATOR,
618                         // 2.) Raw package content, encoded with BASE64
619                         base64_encode($content),
620                         // - separator
621                         self::PACKAGE_MASK_SEPARATOR,
622                         // 3.) Tags
623                         implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
624                         // - separator
625                         self::PACKAGE_MASK_SEPARATOR,
626                         // 4.) Checksum
627                         $this->getHashFromContent($content)
628                 );
629
630                 // Now prepare the temporary array and push it on the 'undeclared' stack
631                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
632                         self::PACKAGE_DATA_SENDER    => $this->getSessionId(),
633                         self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
634                         self::PACKAGE_DATA_PROTOCOL  => $protocolName,
635                         self::PACKAGE_DATA_CONTENT   => $packageContent,
636                         self::PACKAGE_DATA_STATUS    => self::PACKAGE_STATUS_NEW,
637                         self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($packageContent, $this->getSessionId())
638                 ));
639         }
640
641         /**
642          * Checks whether a package has been enqueued for delivery.
643          *
644          * @return      $isEnqueued             Whether a package is enqueued
645          */
646         public function isPackageEnqueued () {
647                 // Check whether the stacker is not empty
648                 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
649
650                 // Return the result
651                 return $isEnqueued;
652         }
653
654         /**
655          * Checks whether a package has been declared
656          *
657          * @return      $isDeclared             Whether a package is declared
658          */
659         public function isPackageDeclared () {
660                 // Check whether the stacker is not empty
661                 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
662
663                 // Return the result
664                 return $isDeclared;
665         }
666
667         /**
668          * Checks whether a package should be sent out
669          *
670          * @return      $isWaitingDelivery      Whether a package is waiting for delivery
671          */
672         public function isPackageWaitingForDelivery () {
673                 // Check whether the stacker is not empty
674                 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
675
676                 // Return the result
677                 return $isWaitingDelivery;
678         }
679
680         /**
681          * Delivers an enqueued package to the stated destination. If a non-session
682          * id is provided, recipient resolver is being asked (and instanced once).
683          * This allows that a single package is being delivered to multiple targets
684          * without enqueueing it for every target. If no target is provided or it
685          * can't be determined a NoTargetException is being thrown.
686          *
687          * @return      void
688          * @throws      NoTargetException       If no target can't be determined
689          */
690         public function declareEnqueuedPackage () {
691                 // Make sure this method isn't working if there is no package enqueued
692                 if (!$this->isPackageEnqueued()) {
693                         // This is not fatal but should be avoided
694                         self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw package data waiting declaration, but ' . __METHOD__ . ' has been called!');
695                         return;
696                 } // END - if
697
698                 /*
699                  * Now there are for sure packages to deliver, so start with the first
700                  * one.
701                  */
702                 $packageData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
703
704                 // Declare the raw package data for delivery
705                 $this->declareRawPackageData($packageData);
706         }
707
708         /**
709          * Delivers the next declared package. Only one package per time will be sent
710          * because this may take time and slows down the whole delivery
711          * infrastructure.
712          *
713          * @return      void
714          */
715         public function processDeclaredPackage () {
716                 // Sanity check if we have packages declared
717                 if (!$this->isPackageDeclared()) {
718                         // This is not fatal but should be avoided
719                         self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package has been declared, but ' . __METHOD__ . ' has been called!');
720                         return;
721                 } // END - if
722
723                 // Get the package
724                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
725
726                 // Assert on it
727                 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
728
729                 // Try to deliver the package
730                 try {
731                         // And try to send it
732                         $this->deliverRawPackageData($packageData);
733
734                         // And remove it finally
735                         $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
736                 } catch (InvalidStateException $e) {
737                         // The state is not excepected (shall be 'connected')
738                         self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
739
740                         // Mark the package with status failed
741                         $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
742                 }
743         }
744
745         /**
746          * Sends waiting packages out for delivery
747          *
748          * @return      void
749          */
750         public function sendWaitingPackage () {
751                 // Send any waiting bytes in the back-buffer before sending a new package
752                 $this->sendBackBufferBytes();
753
754                 // Sanity check if we have packages waiting for delivery
755                 if (!$this->isPackageWaitingForDelivery()) {
756                         // This is not fatal but should be avoided
757                         self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
758                         return;
759                 } // END - if
760
761                 // Get the package
762                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
763
764                 try {
765                         // Now try to send it
766                         $this->sendOutgoingRawPackageData($packageData);
767
768                         // And remove it finally
769                         $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
770                 } catch (InvalidSocketException $e) {
771                         // Output exception message
772                         self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package was not delivered: ' . $e->getMessage());
773
774                         // Mark package as failed
775                         $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
776                 }
777         }
778
779         ///////////////////////////////////////////////////////////////////////////
780         //                   Receiving packages / raw data
781         ///////////////////////////////////////////////////////////////////////////
782
783         /**
784          * Checks whether decoded raw data is pending
785          *
786          * @return      $isPending      Whether decoded raw data is pending
787          */
788         private function isRawDataPending () {
789                 // Just return whether the stack is not empty
790                 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
791
792                 // Return the status
793                 return $isPending;
794         }
795
796         /**
797          * Checks whether new raw package data has arrived at a socket
798          *
799          * @param       $poolInstance   An instance of a PoolableListener class
800          * @return      $hasArrived             Whether new raw package data has arrived for processing
801          */
802         public function isNewRawDataPending (PoolableListener $poolInstance) {
803                 // Visit the pool. This monitors the pool for incoming raw data.
804                 $poolInstance->accept($this->getVisitorInstance());
805
806                 // Check for new data arrival
807                 $hasArrived = $this->isRawDataPending();
808
809                 // Return the status
810                 return $hasArrived;
811         }
812
813         /**
814          * Handles the incoming decoded raw data. This method does not "convert" the
815          * decoded data back into a package array, it just "handles" it and pushs it
816          * on the next stack.
817          *
818          * @return      void
819          */
820         public function handleIncomingDecodedData () {
821                 /*
822                  * This method should only be called if decoded raw data is pending,
823                  * so check it again.
824                  */
825                 if (!$this->isRawDataPending()) {
826                         // This is not fatal but should be avoided
827                         self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw (decoded?) data is pending, but ' . __METHOD__ . ' has been called!');
828                         return;
829                 } // END - if
830
831                 // Very noisy debug message:
832                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
833
834                 // "Pop" the next entry (the same array again) from the stack
835                 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
836
837                 // Make sure both array elements are there
838                 assert(
839                         (is_array($decodedData)) &&
840                         (isset($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
841                         (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
842                 );
843
844                 /*
845                  * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
846                  * only want to handle unhandled packages here.
847                  */
848                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] . '(' . BaseRawDataHandler::SOCKET_ERROR_UNHANDLED . ')');
849                 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
850
851                 // Remove the last chunk SEPARATOR (because it is being added and we don't need it)
852                 if (substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
853                         // It is there and should be removed
854                         $decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], 0, -1);
855                 } // END - if
856
857                 // This package is "handled" and can be pushed on the next stack
858                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Pushing ' . strlen($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA]) . ' bytes to stack ' . self::STACKER_NAME_DECODED_HANDLED . ' ...');
859                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
860         }
861
862         /**
863          * Adds raw decoded data from the given handler instance to this receiver
864          *
865          * @param       $handlerInstance        An instance of a Networkable class
866          * @return      void
867          */
868         public function addRawDataToIncomingStack (Networkable $handlerInstance) {
869                 /*
870                  * Get the decoded data from the handler, this is an array with
871                  * 'raw_data' and 'error_code' as elements.
872                  */
873                 $decodedData = $handlerInstance->getNextRawData();
874
875                 // Very noisy debug message:
876                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, TRUE));
877
878                 // And push it on our stack
879                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
880         }
881
882         /**
883          * Checks whether incoming decoded data is handled.
884          *
885          * @return      $isHandled      Whether incoming decoded data is handled
886          */
887         public function isIncomingRawDataHandled () {
888                 // Determine if the stack is not empty
889                 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
890
891                 // Return it
892                 return $isHandled;
893         }
894
895         /**
896          * Checks whether the assembler has pending data left
897          *
898          * @return      $isHandled      Whether the assembler has pending data left
899          */
900         public function ifAssemblerHasPendingDataLeft () {
901                 // Determine if the stack is not empty
902                 $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
903
904                 // Return it
905                 return $isHandled;
906         }
907
908         /**
909          * Handles the attached assemler's pending data queue to be finally
910          * assembled to the raw package data back.
911          *
912          * @return      void
913          */
914         public function handleAssemblerPendingData () {
915                 // Handle it
916                 $this->getAssemblerInstance()->handlePendingData();
917         }
918
919         /**
920          * Assembles incoming decoded data so it will become an abstract network
921          * package again. The assembler does later do it's job by an other task,
922          * not this one to keep best speed possible.
923          *
924          * @return      void
925          */
926         public function assembleDecodedDataToPackage () {
927                 // Make sure the raw decoded package data is handled
928                 assert($this->isIncomingRawDataHandled());
929
930                 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
931                 $packageContent = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
932
933                 // Assert on some elements
934                 assert(
935                         (is_array($packageContent)) &&
936                         (isset($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
937                         (isset($packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
938                 );
939
940                 // Start assembling the raw package data array by chunking it
941                 $this->getAssemblerInstance()->chunkPackageContent($packageContent);
942
943                 // Remove the package from 'handled_decoded' stack ...
944                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
945
946                 // ... and push it on the 'chunked' stacker
947                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Pushing ' . strlen($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA]) . ' bytes on stack ' . self::STACKER_NAME_DECODED_CHUNKED . ',packageContent=' . print_r($packageContent, TRUE));
948                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
949         }
950
951         /**
952          * Accepts the visitor to process the visit "request"
953          *
954          * @param       $visitorInstance        An instance of a Visitor class
955          * @return      void
956          */
957         public function accept (Visitor $visitorInstance) {
958                 // Debug message
959                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - START');
960
961                 // Visit the package
962                 $visitorInstance->visitNetworkPackage($this);
963
964                 // Debug message
965                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
966         }
967
968         /**
969          * Clears all stacks
970          *
971          * @return      void
972          */
973         public function clearAllStacks () {
974                 // Call the init method to force re-initialization
975                 $this->initStacks(TRUE);
976
977                 // Debug message
978                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: All stacker have been re-initialized.');
979         }
980
981         /**
982          * Removes the first failed outoging package from the stack to continue
983          * with next one (it will never work until the issue is fixed by you).
984          *
985          * @return      void
986          * @throws      UnexpectedPackageStatusException        If the package status is not 'failed'
987          * @todo        This may be enchanced for outgoing packages?
988          */
989         public function removeFirstFailedPackage () {
990                 // Get the package again
991                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
992
993                 // Is the package status 'failed'?
994                 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
995                         // Not failed!
996                         throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
997                 } // END - if
998
999                 // Remove this entry
1000                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
1001         }
1002
1003         /**
1004          * "Decode" the package content into the same array when it was sent.
1005          *
1006          * @param       $rawPackageContent      The raw package content to be "decoded"
1007          * @return      $decodedData            An array with 'sender', 'recipient', 'content' and 'status' elements
1008          */
1009         public function decodeRawContent ($rawPackageContent) {
1010                 // Use the separator '#' to "decode" it
1011                 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
1012
1013                 // Assert on count (should be always 3)
1014                 assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
1015
1016                 // Generate the signature of comparing it
1017                 /*
1018                  * @todo Unsupported feature of "signed" messages commented out
1019                 if (!$this->isPackageSignatureValid($decodedArray)) {
1020                         // Is not valid, so throw an exception here
1021                         exit(__METHOD__ . ':INVALID SIG! UNDER CONSTRUCTION!' . chr(10));
1022                 } // END - if
1023                 */
1024
1025                 /*
1026                  * Create 'decodedData' array with all assoziative array elements,
1027                  * except signature.
1028                  */
1029                 $decodedData = array(
1030                         self::PACKAGE_DATA_SENDER    => $decodedArray[self::INDEX_PACKAGE_SENDER],
1031                         self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
1032                         self::PACKAGE_DATA_CONTENT   => $decodedArray[self::INDEX_PACKAGE_CONTENT],
1033                         self::PACKAGE_DATA_STATUS    => self::PACKAGE_STATUS_DECODED
1034                 );
1035
1036                 // And return it
1037                 return $decodedData;
1038         }
1039
1040         /**
1041          * Handles decoded data for this node by "decoding" the 'content' part of
1042          * it. Again this method uses explode() for the "decoding" process.
1043          *
1044          * @param       $decodedData    An array with decoded raw package data
1045          * @return      void
1046          * @throws      InvalidDataChecksumException    If the checksum doesn't match
1047          */
1048         public function handleRawData (array $decodedData) {
1049                 /*
1050                  * "Decode" the package's content by a simple explode() call, for
1051                  * details of the array elements, see comments for constant
1052                  * PACKAGE_MASK.
1053                  */
1054                 $decodedContent = explode(self::PACKAGE_MASK_SEPARATOR, $decodedData[self::PACKAGE_DATA_CONTENT]);
1055
1056                 // Assert on array count for a very basic validation
1057                 assert(count($decodedContent) == self::PACKAGE_CONTENT_ARRAY_SIZE);
1058
1059                 /*
1060                  * Convert the indexed array into an associative array. This is much
1061                  * better to remember than plain numbers, isn't it?
1062                  */
1063                 $decodedContent = array(
1064                         // Compressor's extension used to compress the data
1065                         self::PACKAGE_CONTENT_EXTENSION => $decodedContent[self::INDEX_COMPRESSOR_EXTENSION],
1066                         // Package data (aka "message") in BASE64-decoded form but still compressed
1067                         self::PACKAGE_CONTENT_MESSAGE   => base64_decode($decodedContent[self::INDEX_PACKAGE_DATA]),
1068                         // Tags as an indexed array for "tagging" the message
1069                         self::PACKAGE_CONTENT_TAGS      => explode(self::PACKAGE_TAGS_SEPARATOR, $decodedContent[self::INDEX_TAGS]),
1070                         // Checksum of the _decoded_ data
1071                         self::PACKAGE_CONTENT_CHECKSUM  => $decodedContent[self::INDEX_CHECKSUM]
1072                 );
1073
1074                 // Is the checksum valid?
1075                 if (!$this->isChecksumValid($decodedContent, $decodedData)) {
1076                         // Is not the same, so throw an exception here
1077                         throw new InvalidDataChecksumException(array($this, $decodedContent, $decodedData), BaseListener::EXCEPTION_INVALID_DATA_CHECKSUM);
1078                 } // END - if
1079
1080                 /*
1081                  * The checksum is the same, then it can be decompressed safely. The
1082                  * original message is at this point fully decoded.
1083                  */
1084                 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] = $this->getCompressorInstance()->decompressStream($decodedContent[self::PACKAGE_CONTENT_MESSAGE]);
1085
1086                 // And push it on the next stack
1087                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent);
1088         }
1089
1090         /**
1091          * Checks whether a new message has arrived
1092          *
1093          * @return      $hasArrived             Whether a new message has arrived for processing
1094          */
1095         public function isNewMessageArrived () {
1096                 // Determine if the stack is not empty
1097                 $hasArrived = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE));
1098
1099                 // Return it
1100                 return $hasArrived;
1101         }
1102
1103         /**
1104          * Handles newly arrived messages
1105          *
1106          * @return      void
1107          * @todo        Implement verification of all sent tags here?
1108          */
1109         public function handleNewlyArrivedMessage () {
1110                 // Get it from the stacker, it is the full array with the decoded message
1111                 $decodedContent = $this->getStackerInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE);
1112
1113                 // Now get a filter chain back from factory with given tags array
1114                 $chainInstance = PackageFilterChainFactory::createChainByTagsArray($decodedContent[self::PACKAGE_CONTENT_TAGS]);
1115
1116                 /*
1117                  * Process the message through all filters, note that all other
1118                  * elements from $decodedContent are no longer needed.
1119                  */
1120                 $chainInstance->processMessage($decodedContent[self::PACKAGE_CONTENT_MESSAGE], $this);
1121         }
1122
1123         /**
1124          * Checks whether a processed message is pending for "interpretation"
1125          *
1126          * @return      $isPending      Whether a processed message is pending
1127          */
1128         public function isProcessedMessagePending () {
1129                 // Check it
1130                 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE));
1131
1132                 // Return it
1133                 return $isPending;
1134         }
1135
1136         /**
1137          * Handle processed messages by "interpreting" the 'message_type' element
1138          *
1139          * @return      void
1140          */
1141         public function handleProcessedMessage () {
1142                 // Get it from the stacker, it is the full array with the processed message
1143                 $messageArray = $this->getStackerInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE);
1144
1145                 // Add type for later easier handling
1146                 $messageArray[self::MESSAGE_ARRAY_DATA][self::MESSAGE_ARRAY_TYPE] = $messageArray[self::MESSAGE_ARRAY_TYPE];
1147
1148                 // Debug message
1149                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: messageArray=' . print_r($messageArray, TRUE));
1150
1151                 // Create a handler instance from given message type
1152                 $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);
1153
1154                 // Handle message data
1155                 $handlerInstance->handleMessageData($messageArray[self::MESSAGE_ARRAY_DATA], $this);
1156         }
1157 }
1158
1159 // [EOF]
1160 ?>