publisher.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. // a PHP client library for pubsubhubbub
  3. // as defined at http://code.google.com/p/pubsubhubbub/
  4. // written by Josh Fraser | joshfraser.com | josh@eventvue.com
  5. // Released under Apache License 2.0
  6. class Publisher {
  7. protected $hub_url;
  8. protected $last_response;
  9. // create a new Publisher
  10. public function __construct($hub_url) {
  11. if (!isset($hub_url))
  12. throw new Exception('Please specify a hub url');
  13. if (!preg_match("|^https?://|i",$hub_url))
  14. throw new Exception('The specified hub url does not appear to be valid: '.$hub_url);
  15. $this->hub_url = $hub_url;
  16. }
  17. // accepts either a single url or an array of urls
  18. public function publish_update($topic_urls, $http_function = false) {
  19. if (!isset($topic_urls))
  20. throw new Exception('Please specify a topic url');
  21. // check that we're working with an array
  22. if (!is_array($topic_urls)) {
  23. $topic_urls = array($topic_urls);
  24. }
  25. // set the mode to publish
  26. $post_string = "hub.mode=publish";
  27. // loop through each topic url
  28. foreach ($topic_urls as $topic_url) {
  29. // lightweight check that we're actually working w/ a valid url
  30. if (!preg_match("|^https?://|i",$topic_url))
  31. throw new Exception('The specified topic url does not appear to be valid: '.$topic_url);
  32. // append the topic url parameters
  33. $post_string .= "&hub.url=".urlencode($topic_url);
  34. }
  35. // make the http post request and return true/false
  36. // easy to over-write to use your own http function
  37. if ($http_function)
  38. return $http_function($this->hub_url,$post_string);
  39. else
  40. return $this->http_post($this->hub_url,$post_string);
  41. }
  42. // returns any error message from the latest request
  43. public function last_response() {
  44. return $this->last_response;
  45. }
  46. // default http function that uses curl to post to the hub endpoint
  47. private function http_post($url, $post_string) {
  48. // add any additional curl options here
  49. $options = array(CURLOPT_URL => $url,
  50. CURLOPT_POST => true,
  51. CURLOPT_POSTFIELDS => $post_string,
  52. CURLOPT_USERAGENT => "PubSubHubbub-Publisher-PHP/1.0");
  53. $ch = curl_init();
  54. curl_setopt_array($ch, $options);
  55. $response = curl_exec($ch);
  56. $this->last_response = $response;
  57. $info = curl_getinfo($ch);
  58. curl_close($ch);
  59. // all good
  60. if ($info['http_code'] == 204)
  61. return true;
  62. return false;
  63. }
  64. }
  65. ?>