3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Feed\PubSubHubbub;
16 use Zend\Http\Request as HttpRequest;
17 use Zend\Stdlib\ArrayUtils;
22 * An array of URLs for all Hub Servers to subscribe/unsubscribe.
26 protected $hubUrls = [];
29 * An array of optional parameters to be included in any
30 * (un)subscribe requests.
34 protected $parameters = [];
37 * The URL of the topic (Rss or Atom feed) which is the subject of
38 * our current intent to subscribe to/unsubscribe from updates from
39 * the currently configured Hub Servers.
43 protected $topicUrl = '';
46 * The URL Hub Servers must use when communicating with this Subscriber
50 protected $callbackUrl = '';
53 * The number of seconds for which the subscriber would like to have the
54 * subscription active. Defaults to null, i.e. not sent, to setup a
55 * permanent subscription if possible.
59 protected $leaseSeconds = null;
62 * The preferred verification mode (sync or async). By default, this
63 * Subscriber prefers synchronous verification, but is considered
64 * desirable to support asynchronous verification if possible.
66 * Zend\Feed\Pubsubhubbub\Subscriber will always send both modes, whose
67 * order of occurrence in the parameter list determines this preference.
71 protected $preferredVerificationMode = PubSubHubbub::VERIFICATION_MODE_SYNC;
74 * An array of any errors including keys for 'response', 'hubUrl'.
75 * The response is the actual Zend\Http\Response object.
79 protected $errors = [];
82 * An array of Hub Server URLs for Hubs operating at this time in
83 * asynchronous verification mode.
87 protected $asyncHubs = [];
90 * An instance of Zend\Feed\Pubsubhubbub\Model\SubscriptionPersistence used to background
91 * save any verification tokens associated with a subscription or other.
93 * @var \Zend\Feed\PubSubHubbub\Model\SubscriptionPersistenceInterface
95 protected $storage = null;
98 * An array of authentication credentials for HTTP Basic Authentication
99 * if required by specific Hubs. The array is indexed by Hub Endpoint URI
100 * and the value is a simple array of the username and password to apply.
104 protected $authentications = [];
107 * Tells the Subscriber to append any subscription identifier to the path
108 * of the base Callback URL. E.g. an identifier "subkey1" would be added
109 * to the callback URL "http://www.example.com/callback" to create a subscription
110 * specific Callback URL of "http://www.example.com/callback/subkey1".
112 * This is required for all Hubs using the Pubsubhubbub 0.1 Specification.
113 * It should be manually intercepted and passed to the Callback class using
114 * Zend\Feed\Pubsubhubbub\Subscriber\Callback::setSubscriptionKey(). Will
115 * require a route in the form "callback/:subkey" to allow the parameter be
116 * retrieved from an action using the Zend\Controller\Action::\getParam()
121 protected $usePathParameter = false;
124 * Constructor; accepts an array or Traversable instance to preset
125 * options for the Subscriber without calling all supported setter
128 * @param array|Traversable $options
130 public function __construct($options = null)
132 if ($options !== null) {
133 $this->setOptions($options);
138 * Process any injected configuration options
140 * @param array|Traversable $options
142 * @throws Exception\InvalidArgumentException
144 public function setOptions($options)
146 if ($options instanceof Traversable) {
147 $options = ArrayUtils::iteratorToArray($options);
150 if (! is_array($options)) {
151 throw new Exception\InvalidArgumentException('Array or Traversable object'
152 . 'expected, got ' . gettype($options));
154 if (array_key_exists('hubUrls', $options)) {
155 $this->addHubUrls($options['hubUrls']);
157 if (array_key_exists('callbackUrl', $options)) {
158 $this->setCallbackUrl($options['callbackUrl']);
160 if (array_key_exists('topicUrl', $options)) {
161 $this->setTopicUrl($options['topicUrl']);
163 if (array_key_exists('storage', $options)) {
164 $this->setStorage($options['storage']);
166 if (array_key_exists('leaseSeconds', $options)) {
167 $this->setLeaseSeconds($options['leaseSeconds']);
169 if (array_key_exists('parameters', $options)) {
170 $this->setParameters($options['parameters']);
172 if (array_key_exists('authentications', $options)) {
173 $this->addAuthentications($options['authentications']);
175 if (array_key_exists('usePathParameter', $options)) {
176 $this->usePathParameter($options['usePathParameter']);
178 if (array_key_exists('preferredVerificationMode', $options)) {
179 $this->setPreferredVerificationMode(
180 $options['preferredVerificationMode']
187 * Set the topic URL (RSS or Atom feed) to which the intended (un)subscribe
192 * @throws Exception\InvalidArgumentException
194 public function setTopicUrl($url)
196 if (empty($url) || ! is_string($url) || ! Uri::factory($url)->isValid()) {
197 throw new Exception\InvalidArgumentException('Invalid parameter "url"'
198 .' of "' . $url . '" must be a non-empty string and a valid'
201 $this->topicUrl = $url;
206 * Set the topic URL (RSS or Atom feed) to which the intended (un)subscribe
210 * @throws Exception\RuntimeException
212 public function getTopicUrl()
214 if (empty($this->topicUrl)) {
215 throw new Exception\RuntimeException('A valid Topic (RSS or Atom'
216 . ' feed) URL MUST be set before attempting any operation');
218 return $this->topicUrl;
222 * Set the number of seconds for which any subscription will remain valid
224 * @param int $seconds
226 * @throws Exception\InvalidArgumentException
228 public function setLeaseSeconds($seconds)
230 $seconds = intval($seconds);
232 throw new Exception\InvalidArgumentException('Expected lease seconds'
233 . ' must be an integer greater than zero');
235 $this->leaseSeconds = $seconds;
240 * Get the number of lease seconds on subscriptions
244 public function getLeaseSeconds()
246 return $this->leaseSeconds;
250 * Set the callback URL to be used by Hub Servers when communicating with
255 * @throws Exception\InvalidArgumentException
257 public function setCallbackUrl($url)
259 if (empty($url) || ! is_string($url) || ! Uri::factory($url)->isValid()) {
260 throw new Exception\InvalidArgumentException('Invalid parameter "url"'
261 . ' of "' . $url . '" must be a non-empty string and a valid'
264 $this->callbackUrl = $url;
269 * Get the callback URL to be used by Hub Servers when communicating with
273 * @throws Exception\RuntimeException
275 public function getCallbackUrl()
277 if (empty($this->callbackUrl)) {
278 throw new Exception\RuntimeException('A valid Callback URL MUST be'
279 . ' set before attempting any operation');
281 return $this->callbackUrl;
285 * Set preferred verification mode (sync or async). By default, this
286 * Subscriber prefers synchronous verification, but does support
287 * asynchronous if that's the Hub Server's utilised mode.
289 * Zend\Feed\Pubsubhubbub\Subscriber will always send both modes, whose
290 * order of occurrence in the parameter list determines this preference.
292 * @param string $mode Should be 'sync' or 'async'
294 * @throws Exception\InvalidArgumentException
296 public function setPreferredVerificationMode($mode)
298 if ($mode !== PubSubHubbub::VERIFICATION_MODE_SYNC
299 && $mode !== PubSubHubbub::VERIFICATION_MODE_ASYNC
301 throw new Exception\InvalidArgumentException('Invalid preferred'
302 . ' mode specified: "' . $mode . '" but should be one of'
303 . ' Zend\Feed\Pubsubhubbub::VERIFICATION_MODE_SYNC or'
304 . ' Zend\Feed\Pubsubhubbub::VERIFICATION_MODE_ASYNC');
306 $this->preferredVerificationMode = $mode;
311 * Get preferred verification mode (sync or async).
315 public function getPreferredVerificationMode()
317 return $this->preferredVerificationMode;
321 * Add a Hub Server URL supported by Publisher
325 * @throws Exception\InvalidArgumentException
327 public function addHubUrl($url)
329 if (empty($url) || ! is_string($url) || ! Uri::factory($url)->isValid()) {
330 throw new Exception\InvalidArgumentException('Invalid parameter "url"'
331 . ' of "' . $url . '" must be a non-empty string and a valid'
334 $this->hubUrls[] = $url;
339 * Add an array of Hub Server URLs supported by Publisher
344 public function addHubUrls(array $urls)
346 foreach ($urls as $url) {
347 $this->addHubUrl($url);
353 * Remove a Hub Server URL
358 public function removeHubUrl($url)
360 if (! in_array($url, $this->getHubUrls())) {
363 $key = array_search($url, $this->hubUrls);
364 unset($this->hubUrls[$key]);
369 * Return an array of unique Hub Server URLs currently available
373 public function getHubUrls()
375 $this->hubUrls = array_unique($this->hubUrls);
376 return $this->hubUrls;
380 * Add authentication credentials for a given URL
383 * @param array $authentication
385 * @throws Exception\InvalidArgumentException
387 public function addAuthentication($url, array $authentication)
389 if (empty($url) || ! is_string($url) || ! Uri::factory($url)->isValid()) {
390 throw new Exception\InvalidArgumentException('Invalid parameter "url"'
391 . ' of "' . $url . '" must be a non-empty string and a valid'
394 $this->authentications[$url] = $authentication;
399 * Add authentication credentials for hub URLs
401 * @param array $authentications
404 public function addAuthentications(array $authentications)
406 foreach ($authentications as $url => $authentication) {
407 $this->addAuthentication($url, $authentication);
413 * Get all hub URL authentication credentials
417 public function getAuthentications()
419 return $this->authentications;
423 * Set flag indicating whether or not to use a path parameter
428 public function usePathParameter($bool = true)
430 $this->usePathParameter = $bool;
435 * Add an optional parameter to the (un)subscribe requests
437 * @param string $name
438 * @param string|null $value
440 * @throws Exception\InvalidArgumentException
442 public function setParameter($name, $value = null)
444 if (is_array($name)) {
445 $this->setParameters($name);
448 if (empty($name) || ! is_string($name)) {
449 throw new Exception\InvalidArgumentException('Invalid parameter "name"'
450 . ' of "' . $name . '" must be a non-empty string');
452 if ($value === null) {
453 $this->removeParameter($name);
456 if (empty($value) || (! is_string($value) && $value !== null)) {
457 throw new Exception\InvalidArgumentException('Invalid parameter "value"'
458 . ' of "' . $value . '" must be a non-empty string');
460 $this->parameters[$name] = $value;
465 * Add an optional parameter to the (un)subscribe requests
467 * @param array $parameters
470 public function setParameters(array $parameters)
472 foreach ($parameters as $name => $value) {
473 $this->setParameter($name, $value);
479 * Remove an optional parameter for the (un)subscribe requests
481 * @param string $name
483 * @throws Exception\InvalidArgumentException
485 public function removeParameter($name)
487 if (empty($name) || ! is_string($name)) {
488 throw new Exception\InvalidArgumentException('Invalid parameter "name"'
489 . ' of "' . $name . '" must be a non-empty string');
491 if (array_key_exists($name, $this->parameters)) {
492 unset($this->parameters[$name]);
498 * Return an array of optional parameters for (un)subscribe requests
502 public function getParameters()
504 return $this->parameters;
508 * Sets an instance of Zend\Feed\Pubsubhubbub\Model\SubscriptionPersistence used to background
509 * save any verification tokens associated with a subscription or other.
511 * @param Model\SubscriptionPersistenceInterface $storage
514 public function setStorage(Model\SubscriptionPersistenceInterface $storage)
516 $this->storage = $storage;
521 * Gets an instance of Zend\Feed\Pubsubhubbub\Storage\StoragePersistence used
522 * to background save any verification tokens associated with a subscription
525 * @return Model\SubscriptionPersistenceInterface
526 * @throws Exception\RuntimeException
528 public function getStorage()
530 if ($this->storage === null) {
531 throw new Exception\RuntimeException('No storage vehicle '
534 return $this->storage;
538 * Subscribe to one or more Hub Servers using the stored Hub URLs
539 * for the given Topic URL (RSS or Atom feed)
543 public function subscribeAll()
545 $this->_doRequest('subscribe');
549 * Unsubscribe from one or more Hub Servers using the stored Hub URLs
550 * for the given Topic URL (RSS or Atom feed)
554 public function unsubscribeAll()
556 $this->_doRequest('unsubscribe');
560 * Returns a boolean indicator of whether the notifications to Hub
561 * Servers were ALL successful. If even one failed, FALSE is returned.
565 public function isSuccess()
567 if (count($this->errors) > 0) {
574 * Return an array of errors met from any failures, including keys:
575 * 'response' => the Zend\Http\Response object from the failure
576 * 'hubUrl' => the URL of the Hub Server whose notification failed
580 public function getErrors()
582 return $this->errors;
586 * Return an array of Hub Server URLs who returned a response indicating
587 * operation in Asynchronous Verification Mode, i.e. they will not confirm
588 * any (un)subscription immediately but at a later time (Hubs may be
589 * doing this as a batch process when load balancing)
593 public function getAsyncHubs()
595 return $this->asyncHubs;
599 * Executes an (un)subscribe request
601 * @param string $mode
603 * @throws Exception\RuntimeException
605 // @codingStandardsIgnoreStart
606 protected function _doRequest($mode)
608 // @codingStandardsIgnoreEnd
609 $client = $this->_getHttpClient();
610 $hubs = $this->getHubUrls();
612 throw new Exception\RuntimeException('No Hub Server URLs'
613 . ' have been set so no subscriptions can be attempted');
616 $this->asyncHubs = [];
617 foreach ($hubs as $url) {
618 if (array_key_exists($url, $this->authentications)) {
619 $auth = $this->authentications[$url];
620 $client->setAuth($auth[0], $auth[1]);
622 $client->setUri($url);
623 $client->setRawBody($params = $this->_getRequestParameters($url, $mode));
624 $response = $client->send();
625 if ($response->getStatusCode() !== 204
626 && $response->getStatusCode() !== 202
629 'response' => $response,
633 * At first I thought it was needed, but the backend storage will
634 * allow tracking async without any user interference. It's left
635 * here in case the user is interested in knowing what Hubs
636 * are using async verification modes so they may update Models and
637 * move these to asynchronous processes.
639 } elseif ($response->getStatusCode() == 202) {
640 $this->asyncHubs[] = [
641 'response' => $response,
649 * Get a basic prepared HTTP client for use
651 * @return \Zend\Http\Client
653 // @codingStandardsIgnoreStart
654 protected function _getHttpClient()
656 // @codingStandardsIgnoreEnd
657 $client = PubSubHubbub::getHttpClient();
658 $client->setMethod(HttpRequest::METHOD_POST);
659 $client->setOptions(['useragent' => 'Zend_Feed_Pubsubhubbub_Subscriber/'
660 . Version::VERSION]);
665 * Return a list of standard protocol/optional parameters for addition to
666 * client's POST body that are specific to the current Hub Server URL
668 * @param string $hubUrl
669 * @param string $mode
671 * @throws Exception\InvalidArgumentException
673 // @codingStandardsIgnoreStart
674 protected function _getRequestParameters($hubUrl, $mode)
676 // @codingStandardsIgnoreEnd
677 if (! in_array($mode, ['subscribe', 'unsubscribe'])) {
678 throw new Exception\InvalidArgumentException('Invalid mode specified: "'
679 . $mode . '" which should have been "subscribe" or "unsubscribe"');
684 'hub.topic' => $this->getTopicUrl(),
687 if ($this->getPreferredVerificationMode()
688 == PubSubHubbub::VERIFICATION_MODE_SYNC
691 PubSubHubbub::VERIFICATION_MODE_SYNC,
692 PubSubHubbub::VERIFICATION_MODE_ASYNC,
696 PubSubHubbub::VERIFICATION_MODE_ASYNC,
697 PubSubHubbub::VERIFICATION_MODE_SYNC,
700 $params['hub.verify'] = [];
701 foreach ($vmodes as $vmode) {
702 $params['hub.verify'][] = $vmode;
706 * Establish a persistent verify_token and attach key to callback
707 * URL's path/query_string
709 $key = $this->_generateSubscriptionKey($params, $hubUrl);
710 $token = $this->_generateVerifyToken();
711 $params['hub.verify_token'] = $token;
713 // Note: query string only usable with PuSH 0.2 Hubs
714 if (! $this->usePathParameter) {
715 $params['hub.callback'] = $this->getCallbackUrl()
716 . '?xhub.subscription=' . PubSubHubbub::urlencode($key);
718 $params['hub.callback'] = rtrim($this->getCallbackUrl(), '/')
719 . '/' . PubSubHubbub::urlencode($key);
721 if ($mode == 'subscribe' && $this->getLeaseSeconds() !== null) {
722 $params['hub.lease_seconds'] = $this->getLeaseSeconds();
725 // hub.secret not currently supported
726 $optParams = $this->getParameters();
727 foreach ($optParams as $name => $value) {
728 $params[$name] = $value;
731 // store subscription to storage
732 $now = new DateTime();
734 if (isset($params['hub.lease_seconds'])) {
735 $expires = $now->add(new DateInterval('PT' . $params['hub.lease_seconds'] . 'S'))
736 ->format('Y-m-d H:i:s');
740 'topic_url' => $params['hub.topic'],
741 'hub_url' => $hubUrl,
742 'created_time' => $now->format('Y-m-d H:i:s'),
743 'lease_seconds' => $params['hub.lease_seconds'],
744 'verify_token' => hash('sha256', $params['hub.verify_token']),
746 'expiration_time' => $expires,
747 // @codingStandardsIgnoreStart
748 'subscription_state' => ($mode == 'unsubscribe') ? PubSubHubbub::SUBSCRIPTION_TODELETE : PubSubHubbub::SUBSCRIPTION_NOTVERIFIED,
749 // @codingStandardsIgnoreEnd
751 $this->getStorage()->setSubscription($data);
753 return $this->_toByteValueOrderedString(
754 $this->_urlEncode($params)
759 * Simple helper to generate a verification token used in (un)subscribe
760 * requests to a Hub Server. Follows no particular method, which means
761 * it might be improved/changed in future.
765 // @codingStandardsIgnoreStart
766 protected function _generateVerifyToken()
768 // @codingStandardsIgnoreEnd
769 if (! empty($this->testStaticToken)) {
770 return $this->testStaticToken;
772 return uniqid(rand(), true) . time();
776 * Simple helper to generate a verification token used in (un)subscribe
777 * requests to a Hub Server.
779 * @param array $params
780 * @param string $hubUrl The Hub Server URL for which this token will apply
783 // @codingStandardsIgnoreStart
784 protected function _generateSubscriptionKey(array $params, $hubUrl)
786 // @codingStandardsIgnoreEnd
787 $keyBase = $params['hub.topic'] . $hubUrl;
788 $key = md5($keyBase);
794 * URL Encode an array of parameters
796 * @param array $params
799 // @codingStandardsIgnoreStart
800 protected function _urlEncode(array $params)
802 // @codingStandardsIgnoreEnd
804 foreach ($params as $key => $value) {
805 if (is_array($value)) {
806 $ekey = PubSubHubbub::urlencode($key);
807 $encoded[$ekey] = [];
808 foreach ($value as $duplicateKey) {
810 = PubSubHubbub::urlencode($duplicateKey);
813 $encoded[PubSubHubbub::urlencode($key)]
814 = PubSubHubbub::urlencode($value);
821 * Order outgoing parameters
823 * @param array $params
826 // @codingStandardsIgnoreStart
827 protected function _toByteValueOrderedString(array $params)
829 // @codingStandardsIgnoreEnd
831 uksort($params, 'strnatcmp');
832 foreach ($params as $key => $value) {
833 if (is_array($value)) {
834 foreach ($value as $keyduplicate) {
835 $return[] = $key . '=' . $keyduplicate;
838 $return[] = $key . '=' . $value;
841 return implode('&', $return);
845 * This is STRICTLY for testing purposes only...
847 protected $testStaticToken = null;
849 final public function setTestStaticToken($token)
851 $this->testStaticToken = (string) $token;