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@ship-simu.org>
20 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Hub Developer Team
21 * @license GNU GPL 3.0 or any newer version
22 * @link http://www.ship-simu.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 * SEPARATOR for checksum
57 const PACKAGE_CHECKSUM_SEPARATOR = '_';
60 * Array indexes for above mask, start with zero
62 const INDEX_COMPRESSOR_EXTENSION = 0;
63 const INDEX_PACKAGE_DATA = 1;
65 const INDEX_CHECKSUM = 3;
68 * Array indexes for raw package array
70 const INDEX_PACKAGE_SENDER = 0;
71 const INDEX_PACKAGE_RECIPIENT = 1;
72 const INDEX_PACKAGE_CONTENT = 2;
73 const INDEX_PACKAGE_STATUS = 3;
74 const INDEX_PACKAGE_SIGNATURE = 4;
77 * Named array elements for package data
79 const PACKAGE_DATA_SENDER = 'sender';
80 const PACKAGE_DATA_RECIPIENT = 'recipient';
81 const PACKAGE_DATA_CONTENT = 'content';
82 const PACKAGE_DATA_STATUS = 'status';
83 const PACKAGE_DATA_SIGNATURE = 'signature';
88 const PACKAGE_STATUS_NEW = 'new';
89 const PACKAGE_STATUS_FAILED = 'failed';
90 const PACKAGE_STATUS_DECODED = 'decoded';
95 const PACKAGE_TAGS_SEPARATOR = ';';
98 * Raw package data separator
100 const PACKAGE_DATA_SEPARATOR = '#';
103 * Network target (alias): 'upper hubs'
105 const NETWORK_TARGET_UPPER_HUBS = 'upper';
108 * Network target (alias): 'self'
110 const NETWORK_TARGET_SELF = 'self';
113 * TCP package size in bytes
115 const TCP_PACKAGE_SIZE = 512;
117 /**************************************************************************
118 * Stacker for out-going packages *
119 **************************************************************************/
122 * Stacker name for "undeclared" packages
124 const STACKER_NAME_UNDECLARED = 'package_undeclared';
127 * Stacker name for "declared" packages (which are ready to send out)
129 const STACKER_NAME_DECLARED = 'package_declared';
132 * Stacker name for "out-going" packages
134 const STACKER_NAME_OUTGOING = 'package_outgoing';
136 /**************************************************************************
137 * Stacker for incoming packages *
138 **************************************************************************/
141 * Stacker name for "incoming" decoded raw data
143 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
146 * Stacker name for handled decoded raw data
148 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
151 * Stacker name for "chunked" decoded raw data
153 const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
155 /**************************************************************************
156 * Stacker for other/internal purposes *
157 **************************************************************************/
160 * Stacker name for "back-buffered" packages
162 const STACKER_NAME_BACK_BUFFER = 'package_backbuffer';
165 * Protected constructor
169 protected function __construct () {
170 // Call parent constructor
171 parent::__construct(__CLASS__);
175 * Creates an instance of this class
177 * @param $compressorInstance A Compressor instance for compressing the content
178 * @return $packageInstance An instance of a Deliverable class
180 public static final function createNetworkPackage (Compressor $compressorInstance) {
182 $packageInstance = new NetworkPackage();
184 // Now set the compressor instance
185 $packageInstance->setCompressorInstance($compressorInstance);
188 * We need to initialize a stack here for our packages even for those
189 * which have no recipient address and stamp... ;-) This stacker will
190 * also be used for incoming raw data to handle it.
192 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
194 // At last, set it in this class
195 $packageInstance->setStackerInstance($stackerInstance);
198 $packageInstance->initStackers();
200 // Get a visitor instance for speeding up things
201 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
203 // Set it in this package
204 $packageInstance->setVisitorInstance($visitorInstance);
206 // Get crypto instance and set it in this package
207 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
208 $packageInstance->setCryptoInstance($cryptoInstance);
210 // Return the prepared instance
211 return $packageInstance;
215 * Initialize all stackers
217 * @param $forceReInit Whether to force reinitialization of all stacks
220 protected function initStackers ($forceReInit = false) {
224 self::STACKER_NAME_UNDECLARED,
225 self::STACKER_NAME_DECLARED,
226 self::STACKER_NAME_OUTGOING,
227 self::STACKER_NAME_DECODED_INCOMING,
228 self::STACKER_NAME_DECODED_HANDLED,
229 self::STACKER_NAME_DECODED_CHUNKED,
230 self::STACKER_NAME_BACK_BUFFER
233 $this->getStackerInstance()->initStacker($stackerName, $forceReInit);
238 * "Getter" for hash from given content and helper instance
240 * @param $content Raw package content
241 * @param $helperInstance An instance of a HelpableHub class
242 * @param $nodeInstance An instance of a NodeHelper class
243 * @return $hash Hash for given package content
244 * @todo $helperInstance is unused
246 private function getHashFromContent ($content, HelpableHub $helperInstance, NodeHelper $nodeInstance) {
248 // @TODO crc32() is very weak, but it needs to be fast
251 self::PACKAGE_CHECKSUM_SEPARATOR .
252 $nodeInstance->getSessionId() .
253 self::PACKAGE_CHECKSUM_SEPARATOR .
254 $this->getCompressorInstance()->getCompressorExtension()
262 * Change the package with given status in given stack
264 * @param $packageData Raw package data in an array
265 * @param $stackerName Name of the stacker
266 * @param $newStatus New status to set
269 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
270 // Skip this for empty stacks
271 if ($this->getStackerInstance()->isStackEmpty($stackerName)) {
272 // This avoids an exception after all packages has failed
276 // Pop the entry (it should be it)
277 $nextData = $this->getStackerInstance()->popNamed($stackerName);
279 // Compare both arrays
280 assert($nextData[self::PACKAGE_DATA_SIGNATURE] == $packageData[self::PACKAGE_DATA_SIGNATURE]);
282 // Temporary set the new status
283 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
286 $this->getStackerInstance()->pushNamed($stackerName, $packageData);
289 ///////////////////////////////////////////////////////////////////////////
290 // Delivering packages / raw data
291 ///////////////////////////////////////////////////////////////////////////
294 * Delivers the given raw package data.
296 * @param $packageData Raw package data in an array
299 private function declareRawPackageData (array $packageData) {
301 * We need to disover every recipient, just in case we have a
302 * multi-recipient entry like 'upper' is. 'all' may be a not so good
303 * target because it causes an overload on the network and may be
304 * abused for attacking the network with large packages.
306 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
308 // Discover all recipients, this may throw an exception
309 $discoveryInstance->discoverRecipients($packageData);
311 // Now get an iterator
312 $iteratorInstance = $discoveryInstance->getIterator();
314 // ... and begin iteration
315 while ($iteratorInstance->valid()) {
317 $currentRecipient = $iteratorInstance->current();
320 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
323 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
325 // And enqueue it to the writer class
326 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
328 // Skip to next entry
329 $iteratorInstance->next();
333 * The recipient list can be cleaned up here because the package which
334 * shall be delivered has already been added for all entries from the
337 $discoveryInstance->clearRecipients();
341 * Delivers raw package data. In short, this will discover the raw socket
342 * resource through a discovery class (which will analyse the receipient of
343 * the package), register the socket with the connection (handler/helper?)
344 * instance and finally push the raw data on our outgoing queue.
346 * @param $packageData Raw package data in an array
349 private function deliverRawPackageData (array $packageData) {
351 * This package may become big, depending on the shared object size or
352 * delivered message size which shouldn't be so long (to save
353 * bandwidth). Because of the nature of the used protocol (TCP) we need
354 * to split it up into smaller pieces to fit it into a TCP frame.
356 * So first we need (again) a discovery class but now a protocol
357 * discovery to choose the right socket resource. The discovery class
358 * should take a look at the raw package data itself and then decide
359 * which (configurable!) protocol should be used for that type of
362 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
364 // Now discover the right protocol
365 $socketResource = $discoveryInstance->discoverSocket($packageData);
368 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
370 // We have to put this socket in our registry, so get an instance
371 $registryInstance = SocketRegistry::createSocketRegistry();
373 // Get the listener from registry
374 $helperInstance = Registry::getRegistry()->getInstance('connection');
377 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
380 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
382 $this->debugOutput('PACKAGE: Registering socket ' . $socketResource . ' ...');
385 $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
386 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
387 // Is not connected, then we cannot send
388 $this->debugOutput('PACKAGE: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
390 // Shutdown the socket
391 $this->shutdownSocket($socketResource);
395 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
397 // Make sure the connection is up
398 $helperInstance->getStateInstance()->validatePeerStateConnected();
401 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
403 // Enqueue it again on the out-going queue, the connection is up and working at this point
404 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
407 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
411 * Sends waiting packages
413 * @param $packageData Raw package data
416 private function sendOutgoingRawPackageData (array $packageData) {
420 // Get the right connection instance
421 $helperInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
423 // Is this connection still alive?
424 if ($helperInstance->isShuttedDown()) {
425 // This connection is shutting down
426 // @TODO We may want to do somthing more here?
430 // Sent out package data
431 $sentBytes = $helperInstance->sendRawPackageData($packageData);
433 // Remember unsent raw bytes in back-buffer, if any
434 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
438 * Generates a signature for given raw package content and sender id
440 * @param $content Raw package data
441 * @param $senderId Sender id to generate a signature for
442 * @return $signature Signature as BASE64-encoded string
444 private function generatePackageSignature ($content, $senderId) {
445 // ash content and sender id together, use md5() as last algo
446 $hash = md5($this->getCryptoInstance()->hashString($senderId . $content));
448 // Encrypt the content again with the hash as a key
449 $encryptedContent = $this->getCryptoInstance()->encryptString($content, $hash);
451 // Encode it with BASE64
452 $signature = base64_encode($encryptedContent);
459 * "Enqueues" raw content into this delivery class by reading the raw content
460 * from given template instance and pushing it on the 'undeclared' stack.
462 * @param $helperInstance An instance of a HelpableHub class
463 * @param $nodeInstance An instance of a NodeHelper class
466 public function enqueueRawDataFromTemplate (HelpableHub $helperInstance, NodeHelper $nodeInstance) {
467 // Get the raw content ...
468 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
470 // ... and compress it
471 $content = $this->getCompressorInstance()->compressStream($content);
473 // Add magic in front of it and hash behind it, including BASE64 encoding
474 $content = sprintf(self::PACKAGE_MASK,
475 // 1.) Compressor's extension
476 $this->getCompressorInstance()->getCompressorExtension(),
478 self::PACKAGE_MASK_SEPARATOR,
479 // 2.) Raw package content, encoded with BASE64
480 base64_encode($content),
482 self::PACKAGE_MASK_SEPARATOR,
484 implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
486 self::PACKAGE_MASK_SEPARATOR,
488 $this->getHashFromContent($content, $helperInstance, $nodeInstance)
491 // Now prepare the temporary array and push it on the 'undeclared' stack
492 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
493 self::PACKAGE_DATA_SENDER => $nodeInstance->getSessionId(),
494 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
495 self::PACKAGE_DATA_CONTENT => $content,
496 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW,
497 self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($content, $nodeInstance->getSessionId())
502 * Checks whether a package has been enqueued for delivery.
504 * @return $isEnqueued Whether a package is enqueued
506 public function isPackageEnqueued () {
507 // Check whether the stacker is not empty
508 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
515 * Checks whether a package has been declared
517 * @return $isDeclared Whether a package is declared
519 public function isPackageDeclared () {
520 // Check whether the stacker is not empty
521 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
528 * Checks whether a package should be sent out
530 * @return $isWaitingDelivery Whether a package is waiting for delivery
532 public function isPackageWaitingForDelivery () {
533 // Check whether the stacker is not empty
534 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
537 return $isWaitingDelivery;
541 * Delivers an enqueued package to the stated destination. If a non-session
542 * id is provided, recipient resolver is being asked (and instanced once).
543 * This allows that a single package is being delivered to multiple targets
544 * without enqueueing it for every target. If no target is provided or it
545 * can't be determined a NoTargetException is being thrown.
548 * @throws NoTargetException If no target can't be determined
550 public function declareEnqueuedPackage () {
551 // Make sure this method isn't working if there is no package enqueued
552 if (!$this->isPackageEnqueued()) {
553 // This is not fatal but should be avoided
554 // @TODO Add some logging here
558 // Now we know for sure there are packages to deliver, we can start
559 // with the first one.
560 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
562 // Declare the raw package data for delivery
563 $this->declareRawPackageData($packageData);
565 // And remove it finally
566 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
570 * Delivers the next declared package. Only one package per time will be sent
571 * because this may take time and slows down the whole delivery
576 public function deliverDeclaredPackage () {
577 // Sanity check if we have packages declared
578 if (!$this->isPackageDeclared()) {
579 // This is not fatal but should be avoided
580 // @TODO Add some logging here
585 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
588 // And try to send it
589 $this->deliverRawPackageData($packageData);
591 // And remove it finally
592 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
593 } catch (InvalidStateException $e) {
594 // The state is not excepected (shall be 'connected')
595 $this->debugOutput('PACKAGE: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
597 // Mark the package with status failed
598 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
603 * Sends waiting packages out for delivery
607 public function sendWaitingPackage () {
608 // Send any waiting bytes in the back-buffer before sending a new package
609 $this->sendBackBufferBytes();
611 // Sanity check if we have packages waiting for delivery
612 if (!$this->isPackageWaitingForDelivery()) {
613 // This is not fatal but should be avoided
614 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
619 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
622 // Now try to send it
623 $this->sendOutgoingRawPackageData($packageData);
625 // And remove it finally
626 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
627 } catch (InvalidSocketException $e) {
628 // Output exception message
629 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
631 // Mark package as failed
632 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
636 ///////////////////////////////////////////////////////////////////////////
637 // Receiving packages / raw data
638 ///////////////////////////////////////////////////////////////////////////
641 * Checks whether decoded raw data is pending
643 * @return $isPending Whether decoded raw data is pending
645 private function isDecodedDataPending () {
646 // Just return whether the stack is not empty
647 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
654 * Checks whether new raw package data has arrived at a socket
656 * @param $poolInstance An instance of a PoolableListener class
657 * @return $hasArrived Whether new raw package data has arrived for processing
659 public function isNewRawDataPending (PoolableListener $poolInstance) {
660 // Visit the pool. This monitors the pool for incoming raw data.
661 $poolInstance->accept($this->getVisitorInstance());
663 // Check for new data arrival
664 $hasArrived = $this->isDecodedDataPending();
671 * Handles the incoming decoded raw data. This method does not "convert" the
672 * decoded data back into a package array, it just "handles" it and pushs it
677 public function handleIncomingDecodedData () {
679 * This method should only be called if decoded raw data is pending,
682 if (!$this->isDecodedDataPending()) {
683 // This is not fatal but should be avoided
684 // @TODO Add some logging here
688 // Very noisy debug message:
689 /* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
691 // "Pop" the next entry (the same array again) from the stack
692 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
694 // Make sure both array elements are there
696 (is_array($decodedData)) &&
697 (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) &&
698 (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
702 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
703 * only want to handle unhandled packages here.
705 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
707 // Remove the last chunk SEPARATOR (because it is being added and we don't need it)
708 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
709 // It is there and should be removed
710 $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
713 // This package is "handled" and can be pushed on the next stack
714 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
718 * Adds raw decoded data from the given handler instance to this receiver
720 * @param $handlerInstance An instance of a Networkable class
723 public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
725 * Get the decoded data from the handler, this is an array with
726 * 'decoded_data' and 'error_code' as elements.
728 $decodedData = $handlerInstance->getNextDecodedData();
730 // Very noisy debug message:
731 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
733 // And push it on our stack
734 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
738 * Checks whether incoming decoded data is handled.
740 * @return $isHandled Whether incoming decoded data is handled
742 public function isIncomingDecodedDataHandled () {
743 // Determine if the stack is not empty
744 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
751 * Assembles incoming decoded data so it will become an abstract network
752 * package again. The assembler does later do it's job by an other task,
753 * not this one to keep best speed possible.
757 public function assembleDecodedDataToPackage () {
758 // Make sure the raw decoded package data is handled
759 assert($this->isIncomingDecodedDataHandled());
761 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
762 $packageContent = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
764 // Get a singleton package assembler instance from factory
765 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance();
767 // Start assembling the raw package data array by chunking it
768 $assemblerInstance->chunkPackageContent($packageContent);
770 // Remove the package from 'handled_decoded' stack ...
771 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
773 // ... and push it on the 'chunked' stacker
774 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
778 * Checks whether a new package has arrived
780 * @return $hasArrived Whether a new package has arrived for processing
782 public function isNewPackageArrived () {
783 // @TODO Add some content here
787 * Accepts the visitor to process the visit "request"
789 * @param $visitorInstance An instance of a Visitor class
792 public function accept (Visitor $visitorInstance) {
794 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
797 $visitorInstance->visitNetworkPackage($this);
800 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
808 public function clearAllStacker () {
809 // Call the init method to force re-initialization
810 $this->initStackers(true);
813 /* DEBUG: */ $this->debugOutput('PACKAGE: All stacker have been re-initialized.');
817 * Removes the first failed outoging package from the stack to continue
818 * with next one (it will never work until the issue is fixed by you).
821 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
822 * @todo This may be enchanced for outgoing packages?
824 public function removeFirstFailedPackage () {
825 // Get the package again
826 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
828 // Is the package status 'failed'?
829 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
831 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
835 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
839 * "Decode" the package content into the same array when it was sent.
841 * @param $rawPackageContent The raw package content to be "decoded"
842 * @return $decodedData An array with 'sender', 'recipient', 'content' and 'status' elements
844 public function decodeRawContent ($rawPackageContent) {
845 // Use the separator '#' to "decode" it
846 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
848 // Assert on count (should be always 3)
849 assert(count($decodedArray) == 3);
851 // Create 'decodedData' array with all assoziative array elements
852 $decodedData = array(
853 self::PACKAGE_DATA_SENDER => $decodedArray[self::INDEX_PACKAGE_SENDER],
854 self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
855 self::PACKAGE_DATA_CONTENT => $decodedArray[self::INDEX_PACKAGE_CONTENT],
856 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_DECODED,
857 self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($decodedArray[self::INDEX_PACKAGE_CONTENT], $decodedArray[self::INDEX_PACKAGE_SENDER])