feedpoll.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * Store last poll time in db, then check if they should be renewed (if so, enqueue).
  4. * Can be called from a queue handler on a per-feed status to poll stuff.
  5. *
  6. * Used as internal feed polling mechanism (atom/rss)
  7. *
  8. * @category OStatus
  9. * @package GNUsocial
  10. * @author Mikael Nordfeldth <mmn@hethane.se>
  11. * @license http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
  12. * @link http://www.gnu.org/software/social/
  13. */
  14. if (!defined('GNUSOCIAL')) { exit(1); }
  15. class FeedPoll {
  16. const DEFAULT_INTERVAL = 5; // in minutes
  17. const QUEUE_CHECK = 'feedpoll-check';
  18. // TODO: Find some smart way to add feeds only once, so they don't get more than 1 feedpoll in the queue each
  19. // probably through sub_start sub_end trickery.
  20. public static function enqueueNewFeeds(array $args=array()) {
  21. if (!isset($args['interval']) || !is_int($args['interval']) || $args['interval']<=0) {
  22. $args['interval'] = self::DEFAULT_INTERVAL;
  23. }
  24. $args['interval'] *= 60; // minutes to seconds
  25. $feedsub = new FeedSub();
  26. $feedsub->sub_state = 'nohub';
  27. // Find feeds that haven't been polled within the desired interval,
  28. // though perhaps we're abusing the "last_update" field here?
  29. $feedsub->whereAdd(sprintf('last_update < "%s"', common_sql_date(time()-$args['interval'])));
  30. $feedsub->find();
  31. $qm = QueueManager::get();
  32. while ($feedsub->fetch()) {
  33. $orig = clone($feedsub);
  34. $item = array('id' => $feedsub->id);
  35. $qm->enqueue($item, self::QUEUE_CHECK);
  36. $feedsub->last_update = common_sql_now();
  37. $feedsub->update($orig);
  38. }
  39. }
  40. public function setupFeedSub(FeedSub $feedsub, $interval=300)
  41. {
  42. $orig = clone($feedsub);
  43. $feedsub->sub_state = 'nohub';
  44. $feedsub->sub_start = common_sql_date(time());
  45. $feedsub->sub_end = '';
  46. $feedsub->last_update = common_sql_date(time()-$interval); // force polling as soon as we can
  47. $feedsub->update($orig);
  48. }
  49. public function checkUpdates(FeedSub $feedsub)
  50. {
  51. $request = new HTTPClient();
  52. $feed = $request->get($feedsub->uri);
  53. if (!$feed->isOk()) {
  54. throw new ServerException('FeedSub could not fetch id='.$feedsub->id.' (Error '.$feed->getStatus().': '.$feed->getBody());
  55. }
  56. $feedsub->receive($feed->getBody(), null);
  57. }
  58. }