Added the zend framework 2 library, the path is specified in line no.26 in zend_modul...
[openemr.git] / interface / modules / zend_modules / library / Zend / Feed / PubSubHubbub / Subscriber.php
blob7171694d20a45910fc2be25829f2605f8f55b584
1 <?php
2 /**
3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
8 */
10 namespace Zend\Feed\PubSubHubbub;
12 use DateInterval;
13 use DateTime;
14 use Traversable;
15 use Zend\Feed\Uri;
16 use Zend\Http\Request as HttpRequest;
17 use Zend\Stdlib\ArrayUtils;
19 class Subscriber
21 /**
22 * An array of URLs for all Hub Servers to subscribe/unsubscribe.
24 * @var array
26 protected $hubUrls = array();
28 /**
29 * An array of optional parameters to be included in any
30 * (un)subscribe requests.
32 * @var array
34 protected $parameters = array();
36 /**
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.
41 * @var string
43 protected $topicUrl = '';
45 /**
46 * The URL Hub Servers must use when communicating with this Subscriber
48 * @var string
50 protected $callbackUrl = '';
52 /**
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.
57 * @var int
59 protected $leaseSeconds = null;
61 /**
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.
69 * @var string
71 protected $preferredVerificationMode = PubSubHubbub::VERIFICATION_MODE_SYNC;
73 /**
74 * An array of any errors including keys for 'response', 'hubUrl'.
75 * The response is the actual Zend\Http\Response object.
77 * @var array
79 protected $errors = array();
81 /**
82 * An array of Hub Server URLs for Hubs operating at this time in
83 * asynchronous verification mode.
85 * @var array
87 protected $asyncHubs = array();
89 /**
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;
97 /**
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.
102 * @var array
104 protected $authentications = array();
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()
117 * method.
119 * @var string
121 protected $usePathParameter = false;
124 * Constructor; accepts an array or Traversable instance to preset
125 * options for the Subscriber without calling all supported setter
126 * methods in turn.
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
141 * @return Subscriber
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']
183 return $this;
187 * Set the topic URL (RSS or Atom feed) to which the intended (un)subscribe
188 * event will relate
190 * @param string $url
191 * @return Subscriber
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'
199 .' URL');
201 $this->topicUrl = $url;
202 return $this;
206 * Set the topic URL (RSS or Atom feed) to which the intended (un)subscribe
207 * event will relate
209 * @return string
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
225 * @return Subscriber
226 * @throws Exception\InvalidArgumentException
228 public function setLeaseSeconds($seconds)
230 $seconds = intval($seconds);
231 if ($seconds <= 0) {
232 throw new Exception\InvalidArgumentException('Expected lease seconds'
233 . ' must be an integer greater than zero');
235 $this->leaseSeconds = $seconds;
236 return $this;
240 * Get the number of lease seconds on subscriptions
242 * @return int
244 public function getLeaseSeconds()
246 return $this->leaseSeconds;
250 * Set the callback URL to be used by Hub Servers when communicating with
251 * this Subscriber
253 * @param string $url
254 * @return Subscriber
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'
262 . ' URL');
264 $this->callbackUrl = $url;
265 return $this;
269 * Get the callback URL to be used by Hub Servers when communicating with
270 * this Subscriber
272 * @return string
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'
293 * @return Subscriber
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;
307 return $this;
311 * Get preferred verification mode (sync or async).
313 * @return string
315 public function getPreferredVerificationMode()
317 return $this->preferredVerificationMode;
321 * Add a Hub Server URL supported by Publisher
323 * @param string $url
324 * @return Subscriber
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'
332 . ' URL');
334 $this->hubUrls[] = $url;
335 return $this;
339 * Add an array of Hub Server URLs supported by Publisher
341 * @param array $urls
342 * @return Subscriber
344 public function addHubUrls(array $urls)
346 foreach ($urls as $url) {
347 $this->addHubUrl($url);
349 return $this;
353 * Remove a Hub Server URL
355 * @param string $url
356 * @return Subscriber
358 public function removeHubUrl($url)
360 if (!in_array($url, $this->getHubUrls())) {
361 return $this;
363 $key = array_search($url, $this->hubUrls);
364 unset($this->hubUrls[$key]);
365 return $this;
369 * Return an array of unique Hub Server URLs currently available
371 * @return array
373 public function getHubUrls()
375 $this->hubUrls = array_unique($this->hubUrls);
376 return $this->hubUrls;
380 * Add authentication credentials for a given URL
382 * @param string $url
383 * @param array $authentication
384 * @return Subscriber
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'
392 . ' URL');
394 $this->authentications[$url] = $authentication;
395 return $this;
399 * Add authentication credentials for hub URLs
401 * @param array $authentications
402 * @return Subscriber
404 public function addAuthentications(array $authentications)
406 foreach ($authentications as $url => $authentication) {
407 $this->addAuthentication($url, $authentication);
409 return $this;
413 * Get all hub URL authentication credentials
415 * @return array
417 public function getAuthentications()
419 return $this->authentications;
423 * Set flag indicating whether or not to use a path parameter
425 * @param bool $bool
426 * @return Subscriber
428 public function usePathParameter($bool = true)
430 $this->usePathParameter = $bool;
431 return $this;
435 * Add an optional parameter to the (un)subscribe requests
437 * @param string $name
438 * @param string|null $value
439 * @return Subscriber
440 * @throws Exception\InvalidArgumentException
442 public function setParameter($name, $value = null)
444 if (is_array($name)) {
445 $this->setParameters($name);
446 return $this;
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);
454 return $this;
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;
461 return $this;
465 * Add an optional parameter to the (un)subscribe requests
467 * @param array $parameters
468 * @return Subscriber
470 public function setParameters(array $parameters)
472 foreach ($parameters as $name => $value) {
473 $this->setParameter($name, $value);
475 return $this;
479 * Remove an optional parameter for the (un)subscribe requests
481 * @param string $name
482 * @return Subscriber
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]);
494 return $this;
498 * Return an array of optional parameters for (un)subscribe requests
500 * @return array
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
512 * @return Subscriber
514 public function setStorage(Model\SubscriptionPersistenceInterface $storage)
516 $this->storage = $storage;
517 return $this;
521 * Gets an instance of Zend\Feed\Pubsubhubbub\Storage\StoragePersistence used
522 * to background save any verification tokens associated with a subscription
523 * or other.
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 '
532 . 'has been set.');
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)
541 * @return void
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)
552 * @return void
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.
563 * @return bool
565 public function isSuccess()
567 if (count($this->errors) > 0) {
568 return false;
570 return true;
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
578 * @return array
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)
591 * @return array
593 public function getAsyncHubs()
595 return $this->asyncHubs;
599 * Executes an (un)subscribe request
601 * @param string $mode
602 * @return void
603 * @throws Exception\RuntimeException
605 protected function _doRequest($mode)
607 $client = $this->_getHttpClient();
608 $hubs = $this->getHubUrls();
609 if (empty($hubs)) {
610 throw new Exception\RuntimeException('No Hub Server URLs'
611 . ' have been set so no subscriptions can be attempted');
613 $this->errors = array();
614 $this->asyncHubs = array();
615 foreach ($hubs as $url) {
616 if (array_key_exists($url, $this->authentications)) {
617 $auth = $this->authentications[$url];
618 $client->setAuth($auth[0], $auth[1]);
620 $client->setUri($url);
621 $client->setRawBody($params = $this->_getRequestParameters($url, $mode));
622 $response = $client->send();
623 if ($response->getStatusCode() !== 204
624 && $response->getStatusCode() !== 202
626 $this->errors[] = array(
627 'response' => $response,
628 'hubUrl' => $url,
631 * At first I thought it was needed, but the backend storage will
632 * allow tracking async without any user interference. It's left
633 * here in case the user is interested in knowing what Hubs
634 * are using async verification modes so they may update Models and
635 * move these to asynchronous processes.
637 } elseif ($response->getStatusCode() == 202) {
638 $this->asyncHubs[] = array(
639 'response' => $response,
640 'hubUrl' => $url,
647 * Get a basic prepared HTTP client for use
649 * @return \Zend\Http\Client
651 protected function _getHttpClient()
653 $client = PubSubHubbub::getHttpClient();
654 $client->setMethod(HttpRequest::METHOD_POST);
655 $client->setOptions(array('useragent' => 'Zend_Feed_Pubsubhubbub_Subscriber/'
656 . Version::VERSION));
657 return $client;
661 * Return a list of standard protocol/optional parameters for addition to
662 * client's POST body that are specific to the current Hub Server URL
664 * @param string $hubUrl
665 * @param string $mode
666 * @return string
667 * @throws Exception\InvalidArgumentException
669 protected function _getRequestParameters($hubUrl, $mode)
671 if (!in_array($mode, array('subscribe', 'unsubscribe'))) {
672 throw new Exception\InvalidArgumentException('Invalid mode specified: "'
673 . $mode . '" which should have been "subscribe" or "unsubscribe"');
676 $params = array(
677 'hub.mode' => $mode,
678 'hub.topic' => $this->getTopicUrl(),
681 if ($this->getPreferredVerificationMode()
682 == PubSubHubbub::VERIFICATION_MODE_SYNC
684 $vmodes = array(
685 PubSubHubbub::VERIFICATION_MODE_SYNC,
686 PubSubHubbub::VERIFICATION_MODE_ASYNC,
688 } else {
689 $vmodes = array(
690 PubSubHubbub::VERIFICATION_MODE_ASYNC,
691 PubSubHubbub::VERIFICATION_MODE_SYNC,
694 $params['hub.verify'] = array();
695 foreach ($vmodes as $vmode) {
696 $params['hub.verify'][] = $vmode;
700 * Establish a persistent verify_token and attach key to callback
701 * URL's path/query_string
703 $key = $this->_generateSubscriptionKey($params, $hubUrl);
704 $token = $this->_generateVerifyToken();
705 $params['hub.verify_token'] = $token;
707 // Note: query string only usable with PuSH 0.2 Hubs
708 if (!$this->usePathParameter) {
709 $params['hub.callback'] = $this->getCallbackUrl()
710 . '?xhub.subscription=' . PubSubHubbub::urlencode($key);
711 } else {
712 $params['hub.callback'] = rtrim($this->getCallbackUrl(), '/')
713 . '/' . PubSubHubbub::urlencode($key);
715 if ($mode == 'subscribe' && $this->getLeaseSeconds() !== null) {
716 $params['hub.lease_seconds'] = $this->getLeaseSeconds();
719 // hub.secret not currently supported
720 $optParams = $this->getParameters();
721 foreach ($optParams as $name => $value) {
722 $params[$name] = $value;
725 // store subscription to storage
726 $now = new DateTime();
727 $expires = null;
728 if (isset($params['hub.lease_seconds'])) {
729 $expires = $now->add(new DateInterval('PT' . $params['hub.lease_seconds'] . 'S'))
730 ->format('Y-m-d H:i:s');
732 $data = array(
733 'id' => $key,
734 'topic_url' => $params['hub.topic'],
735 'hub_url' => $hubUrl,
736 'created_time' => $now->format('Y-m-d H:i:s'),
737 'lease_seconds' => $params['hub.lease_seconds'],
738 'verify_token' => hash('sha256', $params['hub.verify_token']),
739 'secret' => null,
740 'expiration_time' => $expires,
741 'subscription_state' => ($mode == 'unsubscribe')? PubSubHubbub::SUBSCRIPTION_TODELETE : PubSubHubbub::SUBSCRIPTION_NOTVERIFIED,
743 $this->getStorage()->setSubscription($data);
745 return $this->_toByteValueOrderedString(
746 $this->_urlEncode($params)
751 * Simple helper to generate a verification token used in (un)subscribe
752 * requests to a Hub Server. Follows no particular method, which means
753 * it might be improved/changed in future.
755 * @return string
757 protected function _generateVerifyToken()
759 if (!empty($this->testStaticToken)) {
760 return $this->testStaticToken;
762 return uniqid(rand(), true) . time();
766 * Simple helper to generate a verification token used in (un)subscribe
767 * requests to a Hub Server.
769 * @param array $params
770 * @param string $hubUrl The Hub Server URL for which this token will apply
771 * @return string
773 protected function _generateSubscriptionKey(array $params, $hubUrl)
775 $keyBase = $params['hub.topic'] . $hubUrl;
776 $key = md5($keyBase);
778 return $key;
782 * URL Encode an array of parameters
784 * @param array $params
785 * @return array
787 protected function _urlEncode(array $params)
789 $encoded = array();
790 foreach ($params as $key => $value) {
791 if (is_array($value)) {
792 $ekey = PubSubHubbub::urlencode($key);
793 $encoded[$ekey] = array();
794 foreach ($value as $duplicateKey) {
795 $encoded[$ekey][]
796 = PubSubHubbub::urlencode($duplicateKey);
798 } else {
799 $encoded[PubSubHubbub::urlencode($key)]
800 = PubSubHubbub::urlencode($value);
803 return $encoded;
807 * Order outgoing parameters
809 * @param array $params
810 * @return array
812 protected function _toByteValueOrderedString(array $params)
814 $return = array();
815 uksort($params, 'strnatcmp');
816 foreach ($params as $key => $value) {
817 if (is_array($value)) {
818 foreach ($value as $keyduplicate) {
819 $return[] = $key . '=' . $keyduplicate;
821 } else {
822 $return[] = $key . '=' . $value;
825 return implode('&', $return);
829 * This is STRICTLY for testing purposes only...
831 protected $testStaticToken = null;
833 final public function setTestStaticToken($token)
835 $this->testStaticToken = (string) $token;