PuSHSubscriber.inc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. <?php
  2. /**
  3. * @file
  4. * Pubsubhubbub subscriber library.
  5. *
  6. * Readme
  7. * http://github.com/lxbarth/PuSHSubscriber
  8. *
  9. * License
  10. * http://github.com/lxbarth/PuSHSubscriber/blob/master/LICENSE.txt
  11. */
  12. /**
  13. * PubSubHubbub subscriber.
  14. */
  15. class PuSHSubscriber {
  16. protected $domain;
  17. protected $subscriber_id;
  18. protected $subscription_class;
  19. protected $env;
  20. /**
  21. * Singleton.
  22. *
  23. * PuSHSubscriber identifies a unique subscription by a domain and a numeric
  24. * id. The numeric id is assumed to e unique in its domain.
  25. *
  26. * @param $domain
  27. * A string that identifies the domain in which $subscriber_id is unique.
  28. * @param $subscriber_id
  29. * A numeric subscriber id.
  30. * @param $subscription_class
  31. * The class to use for handling subscriptions. Class MUST implement
  32. * PuSHSubscriberSubscriptionInterface
  33. * @param PuSHSubscriberEnvironmentInterface $env
  34. * Environmental object for messaging and logging.
  35. */
  36. public static function instance($domain, $subscriber_id, $subscription_class, PuSHSubscriberEnvironmentInterface $env) {
  37. static $subscribers;
  38. if (!isset($subscriber[$domain][$subscriber_id])) {
  39. $subscriber = new PuSHSubscriber($domain, $subscriber_id, $subscription_class, $env);
  40. }
  41. return $subscriber;
  42. }
  43. /**
  44. * Protect constructor.
  45. */
  46. protected function __construct($domain, $subscriber_id, $subscription_class, PuSHSubscriberEnvironmentInterface $env) {
  47. $this->domain = $domain;
  48. $this->subscriber_id = $subscriber_id;
  49. $this->subscription_class = $subscription_class;
  50. $this->env = $env;
  51. }
  52. /**
  53. * Subscribe to a given URL. Attempt to retrieve 'hub' and 'self' links from
  54. * document at $url and issue a subscription request to the hub.
  55. *
  56. * @param $url
  57. * The URL of the feed to subscribe to.
  58. * @param $callback_url
  59. * The full URL that hub should invoke for subscription verification or for
  60. * notifications.
  61. * @param $hub
  62. * The URL of a hub. If given overrides the hub URL found in the document
  63. * at $url.
  64. */
  65. public function subscribe($url, $callback_url, $hub = '') {
  66. // Fetch document, find rel=hub and rel=self.
  67. // If present, issue subscription request.
  68. $request = curl_init($url);
  69. curl_setopt($request, CURLOPT_FOLLOWLOCATION, TRUE);
  70. curl_setopt($request, CURLOPT_RETURNTRANSFER, TRUE);
  71. $data = curl_exec($request);
  72. if (curl_getinfo($request, CURLINFO_HTTP_CODE) == 200) {
  73. try {
  74. $xml = @ new SimpleXMLElement($data);
  75. $xml->registerXPathNamespace('atom', 'http://www.w3.org/2005/Atom');
  76. if (empty($hub) && $hub = @current($xml->xpath("//atom:link[attribute::rel='hub']"))) {
  77. $hub = (string) $hub->attributes()->href;
  78. }
  79. if ($self = @current($xml->xpath("//atom:link[attribute::rel='self']"))) {
  80. $self = (string) $self->attributes()->href;
  81. }
  82. }
  83. catch (Exception $e) {
  84. // Do nothing.
  85. }
  86. }
  87. curl_close($request);
  88. // Fall back to $url if $self is not given.
  89. if (!$self) {
  90. $self = $url;
  91. }
  92. if (!empty($hub) && !empty($self)) {
  93. $this->request($hub, $self, 'subscribe', $callback_url);
  94. }
  95. }
  96. /**
  97. * @todo Unsubscribe from a hub.
  98. * @todo Make sure we unsubscribe with the correct topic URL as it can differ
  99. * from the initial subscription URL.
  100. *
  101. * @param $topic_url
  102. * The URL of the topic to unsubscribe from.
  103. * @param $callback_url
  104. * The callback to unsubscribe.
  105. */
  106. public function unsubscribe($topic_url, $callback_url) {
  107. if ($sub = $this->subscription()) {
  108. $this->request($sub->hub, $sub->topic, 'unsubscribe', $callback_url);
  109. $sub->delete();
  110. }
  111. }
  112. /**
  113. * Request handler for subscription callbacks.
  114. */
  115. public function handleRequest($callback) {
  116. if (isset($_GET['hub_challenge'])) {
  117. $this->verifyRequest();
  118. }
  119. // No subscription notification has ben sent, we are being notified.
  120. else {
  121. if ($raw = $this->receive()) {
  122. $callback($raw, $this->domain, $this->subscriber_id);
  123. }
  124. }
  125. }
  126. /**
  127. * Receive a notification.
  128. *
  129. * @param $ignore_signature
  130. * If FALSE, only accept payload if there is a signature present and the
  131. * signature matches the payload. Warning: setting to TRUE results in
  132. * unsafe behavior.
  133. *
  134. * @return
  135. * An XML string that is the payload of the notification if valid, FALSE
  136. * otherwise.
  137. */
  138. public function receive($ignore_signature = FALSE) {
  139. /**
  140. * Verification steps:
  141. *
  142. * 1) Verify that this is indeed a POST reuest.
  143. * 2) Verify that posted string is XML.
  144. * 3) Per default verify sender of message by checking the message's
  145. * signature against the shared secret.
  146. */
  147. if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  148. $raw = file_get_contents('php://input');
  149. if (@simplexml_load_string($raw)) {
  150. if ($ignore_signature) {
  151. return $raw;
  152. }
  153. if (isset($_SERVER['HTTP_X_HUB_SIGNATURE']) && ($sub = $this->subscription())) {
  154. $result = array();
  155. parse_str($_SERVER['HTTP_X_HUB_SIGNATURE'], $result);
  156. if (isset($result['sha1']) && $result['sha1'] === hash_hmac('sha1', $raw, $sub->secret)) {
  157. return $raw;
  158. }
  159. else {
  160. $this->log('Could not verify signature.', 'error');
  161. }
  162. }
  163. else {
  164. $this->log('No signature present.', 'error');
  165. }
  166. }
  167. }
  168. return FALSE;
  169. }
  170. /**
  171. * Verify a request. After a hub has received a subscribe or unsubscribe
  172. * request (see PuSHSubscriber::request()) it sends back a challenge verifying
  173. * that an action indeed was requested ($_GET['hub_challenge']). This
  174. * method handles the challenge.
  175. */
  176. public function verifyRequest() {
  177. if (!isset($_GET['hub_challenge'])) {
  178. return $this->rejectRequest();
  179. }
  180. // Don't accept modes of 'subscribed' or 'unsubscribed'.
  181. if ($_GET['hub_mode'] !== 'subscribe' && $_GET['hub_mode'] !== 'unsubscribe') {
  182. return $this->rejectRequest();
  183. }
  184. // No available subscription.
  185. if (!$sub = $this->subscription()) {
  186. return $this->rejectRequest();
  187. }
  188. // Not what we asked for.
  189. if ($_GET['hub_mode'] !== $sub->status) {
  190. return $this->rejectRequest();
  191. }
  192. // Wrong URL.
  193. if ($_GET['hub_topic'] !== $sub->topic) {
  194. return $this->rejectRequest();
  195. }
  196. if ($sub->status === 'subscribe') {
  197. $sub->status = 'subscribed';
  198. $this->log('Verified "subscribe" request.');
  199. }
  200. else {
  201. $sub->status = 'unsubscribed';
  202. $this->log('Verified "unsubscribe" request.');
  203. }
  204. $sub->post_fields = array();
  205. $sub->save();
  206. header('HTTP/1.1 200 "Found"', NULL, 200);
  207. print check_plain($_GET['hub_challenge']);
  208. drupal_exit();
  209. }
  210. /**
  211. * Issue a subscribe or unsubcribe request to a PubsubHubbub hub.
  212. *
  213. * @param $hub
  214. * The URL of the hub's subscription endpoint.
  215. * @param $topic
  216. * The topic URL of the feed to subscribe to.
  217. * @param $mode
  218. * 'subscribe' or 'unsubscribe'.
  219. * @param $callback_url
  220. * The subscriber's notifications callback URL.
  221. *
  222. * Compare to http://pubsubhubbub.googlecode.com/svn/trunk/pubsubhubbub-core-0.2.html#anchor5
  223. *
  224. * @todo Make concurrency safe.
  225. */
  226. protected function request($hub, $topic, $mode, $callback_url) {
  227. $secret = drupal_random_key(40);
  228. $post_fields = array(
  229. 'hub.callback' => $callback_url,
  230. 'hub.mode' => $mode,
  231. 'hub.topic' => $topic,
  232. 'hub.verify' => 'sync',
  233. 'hub.lease_seconds' => '', // Permanent subscription.
  234. 'hub.secret' => $secret,
  235. );
  236. $sub = new $this->subscription_class($this->domain, $this->subscriber_id, $hub, $topic, $secret, $mode, $post_fields);
  237. $sub->save();
  238. // Issue subscription request.
  239. $request = curl_init($hub);
  240. curl_setopt($request, CURLOPT_POST, TRUE);
  241. curl_setopt($request, CURLOPT_POSTFIELDS, $post_fields);
  242. curl_setopt($request, CURLOPT_RETURNTRANSFER, TRUE);
  243. curl_exec($request);
  244. $code = curl_getinfo($request, CURLINFO_HTTP_CODE);
  245. if (in_array($code, array(202, 204))) {
  246. $this->log("Positive response to \"$mode\" request ($code).");
  247. }
  248. else {
  249. $sub->status = $mode . ' failed';
  250. $sub->save();
  251. $this->log("Error issuing \"$mode\" request to $hub ($code).", 'error');
  252. }
  253. curl_close($request);
  254. }
  255. /**
  256. * Get the subscription associated with this subscriber.
  257. *
  258. * @return
  259. * A PuSHSubscriptionInterface object if a subscription exist, NULL
  260. * otherwise.
  261. */
  262. public function subscription() {
  263. return call_user_func(array($this->subscription_class, 'load'), $this->domain, $this->subscriber_id);
  264. }
  265. /**
  266. * Determine whether this subscriber is successfully subscribed or not.
  267. */
  268. public function subscribed() {
  269. if ($sub = $this->subscription()) {
  270. if ($sub->status == 'subscribed') {
  271. return TRUE;
  272. }
  273. }
  274. return FALSE;
  275. }
  276. /**
  277. * Helper for messaging.
  278. */
  279. protected function msg($msg, $level = 'status') {
  280. $this->env->msg($msg, $level);
  281. }
  282. /**
  283. * Helper for logging.
  284. */
  285. protected function log($msg, $level = 'status') {
  286. $this->env->log("{$this->domain}:{$this->subscriber_id}\t$msg", $level);
  287. }
  288. /**
  289. * Rejects a request subscription request.
  290. */
  291. protected function rejectRequest() {
  292. header('HTTP/1.1 404 "Not Found"', NULL, 404);
  293. $this->log('Could not verify subscription.', 'error');
  294. drupal_exit();
  295. }
  296. }
  297. /**
  298. * Implement to provide a storage backend for subscriptions.
  299. *
  300. * Variables passed in to the constructor must be accessible as public class
  301. * variables.
  302. */
  303. interface PuSHSubscriptionInterface {
  304. /**
  305. * @param $domain
  306. * A string that defines the domain in which the subscriber_id is unique.
  307. * @param $subscriber_id
  308. * A unique numeric subscriber id.
  309. * @param $hub
  310. * The URL of the hub endpoint.
  311. * @param $topic
  312. * The topic to subscribe to.
  313. * @param $secret
  314. * A secret key used for message authentication.
  315. * @param $status
  316. * The status of the subscription.
  317. * 'subscribe' - subscribing to a feed.
  318. * 'unsubscribe' - unsubscribing from a feed.
  319. * 'subscribed' - subscribed.
  320. * 'unsubscribed' - unsubscribed.
  321. * 'subscribe failed' - subscribe request failed.
  322. * 'unsubscribe failed' - unsubscribe request failed.
  323. * @param $post_fields
  324. * An array of the fields posted to the hub.
  325. */
  326. public function __construct($domain, $subscriber_id, $hub, $topic, $secret, $status = '', $post_fields = '');
  327. /**
  328. * Save a subscription.
  329. */
  330. public function save();
  331. /**
  332. * Load a subscription.
  333. *
  334. * @return
  335. * A PuSHSubscriptionInterface object if a subscription exist, NULL
  336. * otherwise.
  337. */
  338. public static function load($domain, $subscriber_id);
  339. /**
  340. * Delete a subscription.
  341. */
  342. public function delete();
  343. }
  344. /**
  345. * Implement to provide environmental functionality like user messages and
  346. * logging.
  347. */
  348. interface PuSHSubscriberEnvironmentInterface {
  349. /**
  350. * A message to be displayed to the user on the current page load.
  351. *
  352. * @param $msg
  353. * A string that is the message to be displayed.
  354. * @param $level
  355. * A string that is either 'status', 'warning' or 'error'.
  356. */
  357. public function msg($msg, $level = 'status');
  358. /**
  359. * A log message to be logged to the database or the file system.
  360. *
  361. * @param $msg
  362. * A string that is the message to be displayed.
  363. * @param $level
  364. * A string that is either 'status', 'warning' or 'error'.
  365. */
  366. public function log($msg, $level = 'status');
  367. }