You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.4 KiB

  1. <?php
  2. function push_error(&$app, $msg) {
  3. $app->response()->status(400);
  4. echo $msg . "\n";
  5. die();
  6. }
  7. ///////////////////////////////////////////////////////////////
  8. // These are just test routes
  9. $app->get('/callback-success', function() use($app) {
  10. $params = $app->request()->params();
  11. $app->response()->status(200);
  12. echo $params['hub_challenge'];
  13. });
  14. $app->get('/callback-fail', function() use($app) {
  15. $params = $app->request()->params();
  16. $app->response()->status(404);
  17. });
  18. ///////////////////////////////////////////////////////////////
  19. $app->post('/', function() use($app) {
  20. $params = $app->request()->params();
  21. switch(k($params, 'hub_mode')) {
  22. case 'subscribe':
  23. // Sanity check the request params
  24. $topic = k($params, 'hub_topic');
  25. $callback = k($params, 'hub_callback');
  26. if(!is_valid_push_url($topic)) {
  27. push_error($app, 'Topic URL was invalid');
  28. }
  29. if(!is_valid_push_url($callback)) {
  30. push_error($app, 'Callback URL was invalid');
  31. }
  32. // If we've already seen the topic, assume it's valid and don't check it again
  33. if(!db\feed_from_url($topic)) {
  34. $topic_head = request\get_head($topic);
  35. if($topic_head && !request\response_is($topic_head['status'], 2)) {
  36. push_error($app, "The topic URL returned a " . $topic_head['status'] . " status code");
  37. } else {
  38. push_error($app, 'We tried to verify the topic URL exists but it didn\'t respond to a HEAD request.');
  39. }
  40. }
  41. // Find or create the feed given the topic URL
  42. $feed = db\find_or_create('feeds', ['feed_url'=>$topic], [
  43. 'hash' => db\random_hash(),
  44. ], true);
  45. // Find or create the subscription for this callback URL and feed
  46. $subscription = db\find_or_create('subscriptions', ['feed_id'=>$feed->id, 'callback_url'=>$callback], [
  47. 'hash' => db\random_hash()
  48. ], true);
  49. // Always set a new requested date and challenge
  50. $subscription->date_requested = db\now();
  51. $subscription->challenge = db\random_hash();
  52. $subscription->save();
  53. // Queue the worker to validate the subscription
  54. DeferredTask::queue('PushTask', 'verify_subscription', $subscription->id);
  55. $app->response()->status(202);
  56. echo "The subscription request is being validated. Check the status here:\n";
  57. echo Config::$base_url . '/subscription/' . $subscription->hash . "\n";
  58. break;
  59. case 'unsubscribe':
  60. break;
  61. }
  62. });