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
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
15 * For performance reasons, this class should only be instanciated once and then
16 * used as a "pipe-through" class.
18 * @author Roland Haeder <webmaster@shipsimu.org>
20 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2014 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
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.
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.
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/>.
38 class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, Registerable, Visitable {
40 * Package mask for compressing package data:
41 * 0: Compressor extension
43 * 2: Tags, seperated by semicolons, no semicolon is required if only one tag is needed
47 const PACKAGE_MASK = '%s%s%s%s%s%s%s';
50 * Separator for the above mask
52 const PACKAGE_MASK_SEPARATOR = '^';
55 * Size of an array created by invoking
56 * explode(NetworkPackage::PACKAGE_MASK_SEPARATOR, $content).
58 const PACKAGE_CONTENT_ARRAY_SIZE = 4;
61 * Separator for checksum
63 const PACKAGE_CHECKSUM_SEPARATOR = '_';
66 * Array indexes for above mask, start with zero
68 const INDEX_COMPRESSOR_EXTENSION = 0;
69 const INDEX_PACKAGE_DATA = 1;
71 const INDEX_CHECKSUM = 3;
74 * Array indexes for raw package array
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;
83 * Size of the decoded data array ('status' is not included)
85 const DECODED_DATA_ARRAY_SIZE = 4;
88 * Named array elements for decoded package content
90 const PACKAGE_CONTENT_EXTENSION = 'compressor';
91 const PACKAGE_CONTENT_MESSAGE = 'message';
92 const PACKAGE_CONTENT_TAGS = 'tags';
93 const PACKAGE_CONTENT_CHECKSUM = 'checksum';
96 * Named array elements for package data
98 const PACKAGE_DATA_SENDER = 'sender';
99 const PACKAGE_DATA_RECIPIENT = 'recipient';
100 const PACKAGE_DATA_CONTENT = 'content';
101 const PACKAGE_DATA_STATUS = 'status';
102 const PACKAGE_DATA_SIGNATURE = 'signature';
107 const PACKAGE_STATUS_NEW = 'new';
108 const PACKAGE_STATUS_FAILED = 'failed';
109 const PACKAGE_STATUS_DECODED = 'decoded';
110 const PACKAGE_STATUS_FAKED = 'faked';
113 * Constants for message data array
115 const MESSAGE_ARRAY_DATA = 'message_data';
116 const MESSAGE_ARRAY_TYPE = 'message_type';
119 * Generic answer status field
125 const PACKAGE_TAGS_SEPARATOR = ';';
128 * Raw package data separator
130 const PACKAGE_DATA_SEPARATOR = '#';
133 * Separator for more than one recipient
135 const PACKAGE_RECIPIENT_SEPARATOR = ':';
138 * Network target (alias): 'upper nodes'
140 const NETWORK_TARGET_UPPER = 'upper';
143 * Network target (alias): 'self'
145 const NETWORK_TARGET_SELF = 'self';
148 * Network target (alias): 'dht'
150 const NETWORK_TARGET_DHT = 'dht';
153 * TCP package size in bytes
155 const TCP_PACKAGE_SIZE = 512;
157 /**************************************************************************
158 * Stacker for out-going packages *
159 **************************************************************************/
162 * Stacker name for "undeclared" packages
164 const STACKER_NAME_UNDECLARED = 'package_undeclared';
167 * Stacker name for "declared" packages (which are ready to send out)
169 const STACKER_NAME_DECLARED = 'package_declared';
172 * Stacker name for "out-going" packages
174 const STACKER_NAME_OUTGOING = 'package_outgoing';
176 /**************************************************************************
177 * Stacker for incoming packages *
178 **************************************************************************/
181 * Stacker name for "incoming" decoded raw data
183 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
186 * Stacker name for handled decoded raw data
188 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
191 * Stacker name for "chunked" decoded raw data
193 const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
195 /**************************************************************************
196 * Stacker for incoming messages *
197 **************************************************************************/
200 * Stacker name for new messages
202 const STACKER_NAME_NEW_MESSAGE = 'package_new_message';
205 * Stacker name for processed messages
207 const STACKER_NAME_PROCESSED_MESSAGE = 'package_processed_message';
209 /**************************************************************************
210 * Stacker for raw data handling *
211 **************************************************************************/
214 * Stacker for outgoing data stream
216 const STACKER_NAME_OUTGOING_STREAM = 'outgoing_stream';
219 * Array index for final hash
221 const RAW_FINAL_HASH_INDEX = 'hash';
224 * Array index for encoded data
226 const RAW_ENCODED_DATA_INDEX = 'data';
229 * Array index for sent bytes
231 const RAW_SENT_BYTES_INDEX = 'sent';
234 * Array index for socket resource
236 const RAW_SOCKET_INDEX = 'socket';
239 * Array index for buffer size
241 const RAW_BUFFER_SIZE_INDEX = 'buffer';
244 * Array index for diff between buffer and sent bytes
246 const RAW_DIFF_INDEX = 'diff';
248 /**************************************************************************
250 **************************************************************************/
251 const PROTOCOL_TCP = 'TCP';
252 const PROTOCOL_UDP = 'UDP';
255 * Protected constructor
259 protected function __construct () {
260 // Call parent constructor
261 parent::__construct(__CLASS__);
265 * Creates an instance of this class
267 * @param $compressorInstance A Compressor instance for compressing the content
268 * @return $packageInstance An instance of a Deliverable class
270 public static final function createNetworkPackage (Compressor $compressorInstance) {
272 $packageInstance = new NetworkPackage();
274 // Now set the compressor instance
275 $packageInstance->setCompressorInstance($compressorInstance);
278 * We need to initialize a stack here for our packages even for those
279 * which have no recipient address and stamp... ;-) This stacker will
280 * also be used for incoming raw data to handle it.
282 $stackInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
284 // At last, set it in this class
285 $packageInstance->setStackInstance($stackInstance);
288 $packageInstance->initStacks();
290 // Get a visitor instance for speeding up things and set it
291 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
292 $packageInstance->setVisitorInstance($visitorInstance);
294 // Get crypto instance and set it, too
295 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
296 $packageInstance->setCryptoInstance($cryptoInstance);
298 // Get a singleton package assembler instance from factory and set it here, too
299 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
300 $packageInstance->setAssemblerInstance($assemblerInstance);
302 // Return the prepared instance
303 return $packageInstance;
307 * Initialize all stackers
309 * @param $forceReInit Whether to force reinitialization of all stacks
312 protected function initStacks ($forceReInit = FALSE) {
314 $this->getStackInstance()->initStacks(array(
315 self::STACKER_NAME_UNDECLARED,
316 self::STACKER_NAME_DECLARED,
317 self::STACKER_NAME_OUTGOING,
318 self::STACKER_NAME_DECODED_INCOMING,
319 self::STACKER_NAME_DECODED_HANDLED,
320 self::STACKER_NAME_DECODED_CHUNKED,
321 self::STACKER_NAME_NEW_MESSAGE,
322 self::STACKER_NAME_PROCESSED_MESSAGE,
323 self::STACKER_NAME_OUTGOING_STREAM
328 * "Getter" for hash from given content
330 * @param $content Raw package content
331 * @return $hash Hash for given package content
333 private function getHashFromContent ($content) {
335 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
338 // @TODO md5() is very weak, but it needs to be fast
341 self::PACKAGE_CHECKSUM_SEPARATOR .
342 $this->getSessionId() .
343 self::PACKAGE_CHECKSUM_SEPARATOR .
344 $this->getCompressorInstance()->getCompressorExtension()
348 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',hash=' . $hash . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
355 * Checks whether the checksum (sometimes called "hash") is the same
357 * @param $decodedContent Package raw content
358 * @param $decodedData Whole raw package data array
359 * @return $isChecksumValid Whether the checksum is the same
361 private function isChecksumValid (array $decodedContent, array $decodedData) {
363 $checksum = $this->getHashFromContentSessionId($decodedContent, $decodedData[self::PACKAGE_DATA_SENDER]);
366 $isChecksumValid = ($checksum == $decodedContent[self::PACKAGE_CONTENT_CHECKSUM]);
369 return $isChecksumValid;
373 * Change the package with given status in given stack
375 * @param $packageData Raw package data in an array
376 * @param $stackerName Name of the stacker
377 * @param $newStatus New status to set
380 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
381 // Skip this for empty stacks
382 if ($this->getStackInstance()->isStackEmpty($stackerName)) {
383 // This avoids an exception after all packages has failed
387 // Pop the entry (it should be it)
388 $nextData = $this->getStackInstance()->popNamed($stackerName);
390 // Compare both signatures
391 assert($nextData[self::PACKAGE_DATA_SIGNATURE] == $packageData[self::PACKAGE_DATA_SIGNATURE]);
393 // Temporary set the new status
394 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
397 $this->getStackInstance()->pushNamed($stackerName, $packageData);
401 * "Getter" for hash from given content and sender's session id
403 * @param $decodedContent Raw package content
404 * @param $sessionId Session id of the sender
405 * @return $hash Hash for given package content
407 public function getHashFromContentSessionId (array $decodedContent, $sessionId) {
409 //* 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]);
412 // @TODO md5() is very weak, but it needs to be fast
414 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] .
415 self::PACKAGE_CHECKSUM_SEPARATOR .
417 self::PACKAGE_CHECKSUM_SEPARATOR .
418 $decodedContent[self::PACKAGE_CONTENT_EXTENSION]
425 ///////////////////////////////////////////////////////////////////////////
426 // Delivering packages / raw data
427 ///////////////////////////////////////////////////////////////////////////
430 * Declares the given raw package data by discovering recipients
432 * @param $packageData Raw package data in an array
435 private function declareRawPackageData (array $packageData) {
436 // Make sure the required field is there
437 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
440 * We need to disover every recipient, just in case we have a
441 * multi-recipient entry like 'upper' is. 'all' may be a not so good
442 * target because it causes an overload on the network and may be
443 * abused for attacking the network with large packages.
445 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
447 // Discover all recipients, this may throw an exception
448 $discoveryInstance->discoverRecipients($packageData);
450 // Now get an iterator
451 $iteratorInstance = $discoveryInstance->getIterator();
453 // Make sure the iterator instance is valid
454 assert($iteratorInstance instanceof Iterator);
456 // Rewind back to the beginning
457 $iteratorInstance->rewind();
459 // ... and begin iteration
460 while ($iteratorInstance->valid()) {
462 $currentRecipient = $iteratorInstance->current();
465 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Setting recipient to ' . $currentRecipient . ',previous=' . $packageData[self::PACKAGE_DATA_RECIPIENT]);
468 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
470 // Push the declared package to the next stack.
471 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
474 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package declared for recipient ' . $currentRecipient);
476 // Skip to next entry
477 $iteratorInstance->next();
481 * The recipient list can be cleaned up here because the package which
482 * shall be delivered has already been added for all entries from the
485 $discoveryInstance->clearRecipients();
489 * Delivers raw package data. In short, this will discover the raw socket
490 * resource through a discovery class (which will analyse the receipient of
491 * the package), register the socket with the connection (handler/helper?)
492 * instance and finally push the raw data on our outgoing queue.
494 * @param $packageData Raw package data in an array
497 private function deliverRawPackageData (array $packageData) {
499 * This package may become big, depending on the shared object size or
500 * delivered message size which shouldn't be so long (to save
501 * bandwidth). Because of the nature of the used protocol (TCP) we need
502 * to split it up into smaller pieces to fit it into a TCP frame.
504 * So first we need (again) a discovery class but now a protocol
505 * discovery to choose the right socket resource. The discovery class
506 * should take a look at the raw package data itself and then decide
507 * which (configurable!) protocol should be used for that type of
510 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
512 // Now discover the right protocol
513 $socketResource = $discoveryInstance->discoverSocket($packageData, BaseConnectionHelper::CONNECTION_TYPE_OUTGOING);
516 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
519 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: stateInstance=' . $helperInstance->getStateInstance());
520 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
522 // The socket needs to be put in a special registry that can handle such data
523 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
525 // Get the connection helper from registry
526 $helperInstance = Registry::getRegistry()->getInstance('connection');
528 // And make sure it is valid
529 assert($helperInstance instanceof ConnectionHelper);
532 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
534 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Registering socket ' . $socketResource . ' ...');
537 $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
538 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
539 // Is not connected, then we cannot send
540 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
542 // Shutdown the socket
543 $this->shutdownSocket($socketResource);
547 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
549 // Make sure the connection is up
550 $helperInstance->getStateInstance()->validatePeerStateConnected();
553 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
555 // Enqueue it again on the out-going queue, the connection is up and working at this point
556 $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
559 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
563 * Sends waiting packages
565 * @param $packageData Raw package data
568 private function sendOutgoingRawPackageData (array $packageData) {
572 // Get the right connection instance
573 $helperInstance = SocketRegistryFactory::createSocketRegistryInstance()->getHandlerInstanceFromPackageData($packageData);
575 // Is this connection still alive?
576 if ($helperInstance->isShuttedDown()) {
577 // This connection is shutting down
578 // @TODO We may want to do somthing more here?
582 // Sent out package data
583 $helperInstance->sendRawPackageData($packageData);
587 * Generates a signature for given raw package content and sender id
589 * @param $content Raw package data
590 * @param $senderId Sender id to generate a signature for
591 * @return $signature Signature as BASE64-encoded string
593 private function generatePackageSignature ($content, $senderId) {
594 // Hash content and sender id together, use md5() as last algo
595 $hash = md5($this->getCryptoInstance()->hashString($senderId . $content, $this->getPrivateKey(), FALSE));
597 // Encrypt the content again with the hash as a key
598 $encryptedContent = $this->getCryptoInstance()->encryptString($content, $hash);
600 // Encode it with BASE64
601 $signature = base64_encode($encryptedContent);
608 * Checks whether the signature of given package data is 'valid', here that
609 * means it is the same or not.
611 * @param $decodedArray An array with 'decoded' (explode() was mostly called) data
612 * @return $isSignatureValid Whether the signature is valid
613 * @todo Unfinished area, signatures are currently NOT fully supported
615 private function isPackageSignatureValid (array $decodedArray) {
616 // Generate the signature of comparing it
617 $signature = $this->generatePackageSignature($decodedArray[self::INDEX_PACKAGE_CONTENT], $decodedArray[self::INDEX_PACKAGE_SENDER]);
620 //$isSignatureValid =
621 exit(__METHOD__ . ': signature=' . $signature . chr(10) . ',decodedArray=' . print_r($decodedArray, TRUE));
625 * "Enqueues" raw content into this delivery class by reading the raw content
626 * from given helper's template instance and pushing it on the 'undeclared'
629 * @param $helperInstance An instance of a HubHelper class
632 public function enqueueRawDataFromTemplate (HubHelper $helperInstance) {
634 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
636 // Get the raw content ...
637 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
638 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('content(' . strlen($content) . ')=' . $content);
640 // ... and compress it
641 $content = $this->getCompressorInstance()->compressStream($content);
643 // Add magic in front of it and hash behind it, including BASE64 encoding
644 $packageContent = sprintf(self::PACKAGE_MASK,
645 // 1.) Compressor's extension
646 $this->getCompressorInstance()->getCompressorExtension(),
648 self::PACKAGE_MASK_SEPARATOR,
649 // 2.) Raw package content, encoded with BASE64
650 base64_encode($content),
652 self::PACKAGE_MASK_SEPARATOR,
654 implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
656 self::PACKAGE_MASK_SEPARATOR,
658 $this->getHashFromContent($content)
662 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': Enqueueing package for recipientType=' . $helperInstance->getRecipientType() . ' ...');
664 // Now prepare the temporary array and push it on the 'undeclared' stack
665 $this->getStackInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
666 self::PACKAGE_DATA_SENDER => $this->getSessionId(),
667 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
668 self::PACKAGE_DATA_CONTENT => $packageContent,
669 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW,
670 self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($packageContent, $this->getSessionId())
674 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
678 * Checks whether a package has been enqueued for delivery.
680 * @return $isEnqueued Whether a package is enqueued
682 public function isPackageEnqueued () {
683 // Check whether the stacker is not empty
684 $isEnqueued = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
691 * Checks whether a package has been declared
693 * @return $isDeclared Whether a package is declared
695 public function isPackageDeclared () {
696 // Check whether the stacker is not empty
697 $isDeclared = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
704 * Checks whether a package should be sent out
706 * @return $isWaitingDelivery Whether a package is waiting for delivery
708 public function isPackageWaitingForDelivery () {
709 // Check whether the stacker is not empty
710 $isWaitingDelivery = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
713 return $isWaitingDelivery;
717 * Checks whether encoded (raw) data is pending
719 * @return $isPending Whether encoded data is pending
721 public function isEncodedDataPending () {
722 // Check whether the stacker is not empty
723 $isPending = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING_STREAM)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING_STREAM)));
730 * Delivers an enqueued package to the stated destination. If a non-session
731 * id is provided, recipient resolver is being asked (and instanced once).
732 * This allows that a single package is being delivered to multiple targets
733 * without enqueueing it for every target. If no target is provided or it
734 * can't be determined a NoTargetException is being thrown.
737 * @throws NoTargetException If no target can't be determined
739 public function declareEnqueuedPackage () {
741 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
743 // Make sure this method isn't working if there is no package enqueued
744 if (!$this->isPackageEnqueued()) {
745 // This is not fatal but should be avoided
746 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw package data waiting declaration, but ' . __METHOD__ . ' has been called!');
751 * Now there are for sure packages to deliver, so start with the first
754 $packageData = $this->getStackInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
756 // Declare the raw package data for delivery
757 $this->declareRawPackageData($packageData);
760 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
764 * Delivers the next declared package. Only one package per time will be sent
765 * because this may take time and slows down the whole delivery
770 public function processDeclaredPackage () {
772 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
774 // Sanity check if we have packages declared
775 if (!$this->isPackageDeclared()) {
776 // This is not fatal but should be avoided
777 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package has been declared, but ' . __METHOD__ . ' has been called!');
782 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
785 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
787 // Try to deliver the package
789 // And try to send it
790 $this->deliverRawPackageData($packageData);
792 // And remove it finally
793 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED);
794 } catch (InvalidStateException $e) {
795 // The state is not excepected (shall be 'connected')
796 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
798 // Mark the package with status failed
799 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
803 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
807 * Sends waiting packages out for delivery
811 public function sendWaitingPackage () {
813 /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
815 // Sanity check if we have packages waiting for delivery
816 if (!$this->isPackageWaitingForDelivery()) {
817 // This is not fatal but should be avoided
818 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
823 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_OUTGOING);
826 // Now try to send it
827 $this->sendOutgoingRawPackageData($packageData);
829 // And remove it finally
830 $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING);
831 } catch (InvalidSocketException $e) {
832 // Output exception message
833 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package was not delivered: ' . $e->getMessage());
835 // Mark package as failed
836 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
840 /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
844 * Sends out encoded data to a socket
848 public function sendEncodedData () {
850 /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
852 // Make sure there is pending encoded data
853 assert($this->isEncodedDataPending());
855 // Pop current data from stack
856 $encodedDataArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING_STREAM);
858 // Init in this round sent bytes
862 assert(is_resource($encodedDataArray[self::RAW_SOCKET_INDEX]));
865 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sending out ' . strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) . ' bytes,rawBufferSize=' . $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] . ',diff=' . $encodedDataArray[self::RAW_DIFF_INDEX]);
866 if ($encodedDataArray[self::RAW_DIFF_INDEX] >= 0) {
867 // Send all out (encodedData is smaller than or equal buffer size)
868 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: MD5=' . md5(substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], 0, ($encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - $encodedDataArray[self::RAW_DIFF_INDEX]))));
869 $sentBytes = @socket_write($encodedDataArray[self::RAW_SOCKET_INDEX], $encodedDataArray[self::RAW_ENCODED_DATA_INDEX], ($encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - $encodedDataArray[self::RAW_DIFF_INDEX]));
871 // Send buffer size out
872 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: MD5=' . md5(substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], 0, $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX])));
873 $sentBytes = @socket_write($encodedDataArray[self::RAW_SOCKET_INDEX], $encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX]);
876 // If there was an error, we don't continue here
877 if ($sentBytes === FALSE) {
878 // Handle the error with a faked recipientData array
879 $this->handleSocketError(__METHOD__, __LINE__, $encodedDataArray[self::RAW_SOCKET_INDEX], array('0.0.0.0', '0'));
882 throw new InvalidSocketException(array($this, $encodedDataArray[self::RAW_SOCKET_INDEX], $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
883 } elseif (($sentBytes === 0) && (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) > 0)) {
884 // Nothing sent means we are done
885 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
888 // The difference between sent bytes and length of raw data should not go below zero
889 assert((strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) - $sentBytes) >= 0);
891 // Add total sent bytes
892 $encodedDataArray[self::RAW_SENT_BYTES_INDEX] += $sentBytes;
894 // Cut out the last unsent bytes
895 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sent out ' . $sentBytes . ' of ' . strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) . ' bytes ...');
896 $encodedDataArray[self::RAW_ENCODED_DATA_INDEX] = substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $sentBytes);
898 // Calculate difference again
899 $encodedDataArray[self::RAW_DIFF_INDEX] = $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]);
902 if (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) <= 0) {
903 // Abort here, all sent!
904 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
909 // Push array back in stack
910 $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING_STREAM, $encodedDataArray);
913 /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
916 ///////////////////////////////////////////////////////////////////////////
917 // Receiving packages / raw data
918 ///////////////////////////////////////////////////////////////////////////
921 * Checks whether decoded raw data is pending
923 * @return $isPending Whether decoded raw data is pending
925 private function isRawDataPending () {
926 // Just return whether the stack is not empty
927 $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
934 * Checks whether new raw package data has arrived at a socket
936 * @param $poolInstance An instance of a PoolableListener class
937 * @return $hasArrived Whether new raw package data has arrived for processing
939 public function isNewRawDataPending (PoolableListener $poolInstance) {
940 // Visit the pool. This monitors the pool for incoming raw data.
941 $poolInstance->accept($this->getVisitorInstance());
943 // Check for new data arrival
944 $hasArrived = $this->isRawDataPending();
951 * Handles the incoming decoded raw data. This method does not "convert" the
952 * decoded data back into a package array, it just "handles" it and pushs it
957 public function handleIncomingDecodedData () {
959 * This method should only be called if decoded raw data is pending,
962 if (!$this->isRawDataPending()) {
963 // This is not fatal but should be avoided
964 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw (decoded?) data is pending, but ' . __METHOD__ . ' has been called!');
968 // Very noisy debug message:
969 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Stacker size is ' . $this->getStackInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
971 // "Pop" the next entry (the same array again) from the stack
972 $decodedData = $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
974 // Make sure both array elements are there
976 (is_array($decodedData)) &&
977 (isset($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
978 (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
982 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
983 * only want to handle unhandled packages here.
985 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] . '(' . BaseRawDataHandler::SOCKET_ERROR_UNHANDLED . ')');
986 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
988 // Remove the last chunk SEPARATOR (because there is no need for it)
989 if (substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
990 // It is there and should be removed
991 $decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], 0, -1);
994 // This package is "handled" and can be pushed on the next stack
995 //* 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 . ' ...');
996 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
1000 * Adds raw decoded data from the given handler instance to this receiver
1002 * @param $handlerInstance An instance of a Networkable class
1005 public function addRawDataToIncomingStack (Networkable $handlerInstance) {
1007 * Get the decoded data from the handler, this is an array with
1008 * 'raw_data' and 'error_code' as elements.
1010 $decodedData = $handlerInstance->getNextRawData();
1012 // Very noisy debug message:
1013 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, TRUE));
1015 // And push it on our stack
1016 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
1020 * Checks whether incoming decoded data is handled.
1022 * @return $isHandled Whether incoming decoded data is handled
1024 public function isIncomingRawDataHandled () {
1025 // Determine if the stack is not empty
1026 $isHandled = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
1033 * Checks whether the assembler has pending data left
1035 * @return $isHandled Whether the assembler has pending data left
1037 public function ifAssemblerHasPendingDataLeft () {
1038 // Determine if the stack is not empty
1039 $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
1046 * Checks whether the assembler has multiple packages pending
1048 * @return $isPending Whether the assembler has multiple packages pending
1050 public function ifMultipleMessagesPending () {
1051 // Determine if the stack is not empty
1052 $isPending = ($this->getAssemblerInstance()->ifMultipleMessagesPending());
1059 * Handles the attached assemler's pending data queue to be finally
1060 * assembled to the raw package data back.
1064 public function handleAssemblerPendingData () {
1066 $this->getAssemblerInstance()->handlePendingData();
1070 * Handles multiple messages.
1074 public function handleMultipleMessages () {
1076 $this->getAssemblerInstance()->handleMultipleMessages();
1080 * Assembles incoming decoded data so it will become an abstract network
1081 * package again. The assembler does later do it's job by an other task,
1082 * not this one to keep best speed possible.
1086 public function assembleDecodedDataToPackage () {
1087 // Make sure the raw decoded package data is handled
1088 assert($this->isIncomingRawDataHandled());
1090 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
1091 $packageContent = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
1093 // Assert on some elements
1095 (is_array($packageContent)) &&
1096 (isset($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
1097 (isset($packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
1100 // Start assembling the raw package data array by chunking it
1101 $this->getAssemblerInstance()->chunkPackageContent($packageContent);
1103 // Remove the package from 'handled_decoded' stack ...
1104 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
1106 // ... and push it on the 'chunked' stacker
1107 //* 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));
1108 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
1112 * Accepts the visitor to process the visit "request"
1114 * @param $visitorInstance An instance of a Visitor class
1117 public function accept (Visitor $visitorInstance) {
1119 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - CALLED!');
1121 // Visit the package
1122 $visitorInstance->visitNetworkPackage($this);
1124 // Then visit the assembler to handle multiple packages
1125 $this->getAssemblerInstance()->accept($visitorInstance);
1128 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - EXIT!');
1136 public function clearAllStacks () {
1137 // Call the init method to force re-initialization
1138 $this->initStacks(TRUE);
1141 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: All stacker have been re-initialized.');
1145 * Removes the first failed outoging package from the stack to continue
1146 * with next one (it will never work until the issue is fixed by you).
1149 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
1150 * @todo This may be enchanced for outgoing packages?
1152 public function removeFirstFailedPackage () {
1153 // Get the package again
1154 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
1156 // Is the package status 'failed'?
1157 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
1159 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
1162 // Remove this entry
1163 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED);
1167 * "Decode" the package content into the same array when it was sent.
1169 * @param $rawPackageContent The raw package content to be "decoded"
1170 * @return $decodedData An array with 'sender', 'recipient', 'content' and 'status' elements
1172 public function decodeRawContent ($rawPackageContent) {
1173 // Use the separator '#' to "decode" it
1174 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
1176 // Assert on count (should be always 3)
1177 assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
1179 // Generate the signature of comparing it
1181 * @todo Unsupported feature of "signed" messages commented out
1182 if (!$this->isPackageSignatureValid($decodedArray)) {
1183 // Is not valid, so throw an exception here
1184 exit(__METHOD__ . ':INVALID SIG! UNDER CONSTRUCTION!' . chr(10));
1189 * Create 'decodedData' array with all assoziative array elements,
1192 $decodedData = array(
1193 self::PACKAGE_DATA_SENDER => $decodedArray[self::INDEX_PACKAGE_SENDER],
1194 self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
1195 self::PACKAGE_DATA_CONTENT => $decodedArray[self::INDEX_PACKAGE_CONTENT],
1196 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_DECODED
1200 return $decodedData;
1204 * Handles decoded data for this node by "decoding" the 'content' part of
1205 * it. Again this method uses explode() for the "decoding" process.
1207 * @param $decodedData An array with decoded raw package data
1209 * @throws InvalidDataChecksumException If the checksum doesn't match
1211 public function handleRawData (array $decodedData) {
1213 * "Decode" the package's content by a simple explode() call, for
1214 * details of the array elements, see comments for constant
1217 $decodedContent = explode(self::PACKAGE_MASK_SEPARATOR, $decodedData[self::PACKAGE_DATA_CONTENT]);
1219 // Assert on array count for a very basic validation
1220 assert(count($decodedContent) == self::PACKAGE_CONTENT_ARRAY_SIZE);
1223 * Convert the indexed array into an associative array. This is much
1224 * better to remember than plain numbers, isn't it?
1226 $decodedContent = array(
1227 // Compressor's extension used to compress the data
1228 self::PACKAGE_CONTENT_EXTENSION => $decodedContent[self::INDEX_COMPRESSOR_EXTENSION],
1229 // Package data (aka "message") in BASE64-decoded form but still compressed
1230 self::PACKAGE_CONTENT_MESSAGE => base64_decode($decodedContent[self::INDEX_PACKAGE_DATA]),
1231 // Tags as an indexed array for "tagging" the message
1232 self::PACKAGE_CONTENT_TAGS => explode(self::PACKAGE_TAGS_SEPARATOR, $decodedContent[self::INDEX_TAGS]),
1233 // Checksum of the _decoded_ data
1234 self::PACKAGE_CONTENT_CHECKSUM => $decodedContent[self::INDEX_CHECKSUM]
1237 // Is the checksum valid?
1238 if (!$this->isChecksumValid($decodedContent, $decodedData)) {
1239 // Is not the same, so throw an exception here
1240 throw new InvalidDataChecksumException(array($this, $decodedContent, $decodedData), BaseListener::EXCEPTION_INVALID_DATA_CHECKSUM);
1244 * The checksum is the same, then it can be decompressed safely. The
1245 * original message is at this point fully decoded.
1247 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] = $this->getCompressorInstance()->decompressStream($decodedContent[self::PACKAGE_CONTENT_MESSAGE]);
1249 // And push it on the next stack
1250 $this->getStackInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent);
1254 * Checks whether a new message has arrived
1256 * @return $hasArrived Whether a new message has arrived for processing
1258 public function isNewMessageArrived () {
1259 // Determine if the stack is not empty
1260 $hasArrived = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE));
1267 * Handles newly arrived messages
1270 * @todo Implement verification of all sent tags here?
1272 public function handleNewlyArrivedMessage () {
1273 // Get it from the stacker, it is the full array with the decoded message
1274 $decodedContent = $this->getStackInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE);
1276 // Now get a filter chain back from factory with given tags array
1277 $chainInstance = PackageFilterChainFactory::createChainByTagsArray($decodedContent[self::PACKAGE_CONTENT_TAGS]);
1280 * Process the message through all filters, note that all other
1281 * elements from $decodedContent are no longer needed.
1283 $chainInstance->processMessage($decodedContent[self::PACKAGE_CONTENT_MESSAGE], $this);
1287 * Checks whether a processed message is pending for "interpretation"
1289 * @return $isPending Whether a processed message is pending
1291 public function isProcessedMessagePending () {
1293 $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE));
1300 * Handle processed messages by "interpreting" the 'message_type' element
1304 public function handleProcessedMessage () {
1305 // Get it from the stacker, it is the full array with the processed message
1306 $messageArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE);
1308 // Add type for later easier handling
1309 $messageArray[self::MESSAGE_ARRAY_DATA][self::MESSAGE_ARRAY_TYPE] = $messageArray[self::MESSAGE_ARRAY_TYPE];
1312 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: messageArray=' . print_r($messageArray, TRUE));
1314 // Create a handler instance from given message type
1315 $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);
1317 // Handle message data
1318 $handlerInstance->handleMessageData($messageArray[self::MESSAGE_ARRAY_DATA], $this);