PuSHSubscriber.inc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. /**
  179. * If a subscription is present, compare the verify token. If the token
  180. * matches, set the status on the subscription record and confirm
  181. * positive.
  182. *
  183. * If we cannot find a matching subscription and the hub checks on
  184. * 'unsubscribe' confirm positive.
  185. *
  186. * In all other cases confirm negative.
  187. */
  188. if ($sub = $this->subscription()) {
  189. if ($_GET['hub_verify_token'] == $sub->post_fields['hub.verify_token']) {
  190. if ($_GET['hub_mode'] == 'subscribe' && $sub->status == 'subscribe') {
  191. $sub->status = 'subscribed';
  192. $sub->post_fields = array();
  193. $sub->save();
  194. $this->log('Verified "subscribe" request.');
  195. $verify = TRUE;
  196. }
  197. elseif ($_GET['hub_mode'] == 'unsubscribe' && $sub->status == 'unsubscribe') {
  198. $sub->status = 'unsubscribed';
  199. $sub->post_fields = array();
  200. $sub->save();
  201. $this->log('Verified "unsubscribe" request.');
  202. $verify = TRUE;
  203. }
  204. }
  205. }
  206. elseif ($_GET['hub_mode'] == 'unsubscribe') {
  207. $this->log('Verified "unsubscribe" request.');
  208. $verify = TRUE;
  209. }
  210. if ($verify) {
  211. header('HTTP/1.1 200 "Found"', NULL, 200);
  212. print $_GET['hub_challenge'];
  213. drupal_exit();
  214. }
  215. }
  216. header('HTTP/1.1 404 "Not Found"', NULL, 404);
  217. $this->log('Could not verify subscription.', 'error');
  218. drupal_exit();
  219. }
  220. /**
  221. * Issue a subscribe or unsubcribe request to a PubsubHubbub hub.
  222. *
  223. * @param $hub
  224. * The URL of the hub's subscription endpoint.
  225. * @param $topic
  226. * The topic URL of the feed to subscribe to.
  227. * @param $mode
  228. * 'subscribe' or 'unsubscribe'.
  229. * @param $callback_url
  230. * The subscriber's notifications callback URL.
  231. *
  232. * Compare to http://pubsubhubbub.googlecode.com/svn/trunk/pubsubhubbub-core-0.2.html#anchor5
  233. *
  234. * @todo Make concurrency safe.
  235. */
  236. protected function request($hub, $topic, $mode, $callback_url) {
  237. $secret = hash('sha1', uniqid(rand(), TRUE));
  238. $post_fields = array(
  239. 'hub.callback' => $callback_url,
  240. 'hub.mode' => $mode,
  241. 'hub.topic' => $topic,
  242. 'hub.verify' => 'sync',
  243. 'hub.lease_seconds' => '', // Permanent subscription.
  244. 'hub.secret' => $secret,
  245. 'hub.verify_token' => md5(session_id() . rand()),
  246. );
  247. $sub = new $this->subscription_class($this->domain, $this->subscriber_id, $hub, $topic, $secret, $mode, $post_fields);
  248. $sub->save();
  249. // Issue subscription request.
  250. $request = curl_init($hub);
  251. curl_setopt($request, CURLOPT_POST, TRUE);
  252. curl_setopt($request, CURLOPT_POSTFIELDS, $post_fields);
  253. curl_setopt($request, CURLOPT_RETURNTRANSFER, TRUE);
  254. curl_exec($request);
  255. $code = curl_getinfo($request, CURLINFO_HTTP_CODE);
  256. if (in_array($code, array(202, 204))) {
  257. $this->log("Positive response to \"$mode\" request ($code).");
  258. }
  259. else {
  260. $sub->status = $mode . ' failed';
  261. $sub->save();
  262. $this->log("Error issuing \"$mode\" request to $hub ($code).", 'error');
  263. }
  264. curl_close($request);
  265. }
  266. /**
  267. * Get the subscription associated with this subscriber.
  268. *
  269. * @return
  270. * A PuSHSubscriptionInterface object if a subscription exist, NULL
  271. * otherwise.
  272. */
  273. public function subscription() {
  274. return call_user_func(array($this->subscription_class, 'load'), $this->domain, $this->subscriber_id);
  275. }
  276. /**
  277. * Determine whether this subscriber is successfully subscribed or not.
  278. */
  279. public function subscribed() {
  280. if ($sub = $this->subscription()) {
  281. if ($sub->status == 'subscribed') {
  282. return TRUE;
  283. }
  284. }
  285. return FALSE;
  286. }
  287. /**
  288. * Helper for messaging.
  289. */
  290. protected function msg($msg, $level = 'status') {
  291. $this->env->msg($msg, $level);
  292. }
  293. /**
  294. * Helper for logging.
  295. */
  296. protected function log($msg, $level = 'status') {
  297. $this->env->log("{$this->domain}:{$this->subscriber_id}\t$msg", $level);
  298. }
  299. }
  300. /**
  301. * Implement to provide a storage backend for subscriptions.
  302. *
  303. * Variables passed in to the constructor must be accessible as public class
  304. * variables.
  305. */
  306. interface PuSHSubscriptionInterface {
  307. /**
  308. * @param $domain
  309. * A string that defines the domain in which the subscriber_id is unique.
  310. * @param $subscriber_id
  311. * A unique numeric subscriber id.
  312. * @param $hub
  313. * The URL of the hub endpoint.
  314. * @param $topic
  315. * The topic to subscribe to.
  316. * @param $secret
  317. * A secret key used for message authentication.
  318. * @param $status
  319. * The status of the subscription.
  320. * 'subscribe' - subscribing to a feed.
  321. * 'unsubscribe' - unsubscribing from a feed.
  322. * 'subscribed' - subscribed.
  323. * 'unsubscribed' - unsubscribed.
  324. * 'subscribe failed' - subscribe request failed.
  325. * 'unsubscribe failed' - unsubscribe request failed.
  326. * @param $post_fields
  327. * An array of the fields posted to the hub.
  328. */
  329. public function __construct($domain, $subscriber_id, $hub, $topic, $secret, $status = '', $post_fields = '');
  330. /**
  331. * Save a subscription.
  332. */
  333. public function save();
  334. /**
  335. * Load a subscription.
  336. *
  337. * @return
  338. * A PuSHSubscriptionInterface object if a subscription exist, NULL
  339. * otherwise.
  340. */
  341. public static function load($domain, $subscriber_id);
  342. /**
  343. * Delete a subscription.
  344. */
  345. public function delete();
  346. }
  347. /**
  348. * Implement to provide environmental functionality like user messages and
  349. * logging.
  350. */
  351. interface PuSHSubscriberEnvironmentInterface {
  352. /**
  353. * A message to be displayed to the user on the current page load.
  354. *
  355. * @param $msg
  356. * A string that is the message to be displayed.
  357. * @param $level
  358. * A string that is either 'status', 'warning' or 'error'.
  359. */
  360. public function msg($msg, $level = 'status');
  361. /**
  362. * A log message to be logged to the database or the file system.
  363. *
  364. * @param $msg
  365. * A string that is the message to be displayed.
  366. * @param $level
  367. * A string that is either 'status', 'warning' or 'error'.
  368. */
  369. public function log($msg, $level = 'status');
  370. }