aggregator.module 35.8 KB
Newer Older
1
<?php
Dries's avatar
Dries committed
2
// $Id$
Dries's avatar
 
Dries committed
3

Dries's avatar
 
Dries committed
4 5
/**
 * @file
6
 * Used to aggregate syndicated content (RSS, RDF, and Atom).
Dries's avatar
 
Dries committed
7 8
 */

Dries's avatar
 
Dries committed
9 10 11
/**
 * Implementation of hook_help().
 */
12 13
function aggregator_help($path, $arg) {
  switch ($path) {
Kjartan's avatar
Kjartan committed
14
    case 'admin/help#aggregator':
15 16 17
      $output = '<p>' . t('The aggregator is a powerful on-site syndicator and news reader that gathers fresh content from RSS-, RDF-, and Atom-based feeds made available across the web. Thousands of sites (particularly news sites and blogs) publish their latest headlines and posts in feeds, using a number of standardized XML-based formats. Formats supported by the aggregator include <a href="@rss">RSS</a>, <a href="@rdf">RDF</a>, and <a href="@atom">Atom</a>.', array('@rss' => 'http://cyber.law.harvard.edu/rss/', '@rdf' => 'http://www.w3.org/RDF/', '@atom' => 'http://www.atomenabled.org')) . '</p>';
      $output .= '<p>' . t('Feeds contain feed items, or individual posts published by the site providing the feed. Feeds may be grouped in categories, generally by topic. Users view feed items in the <a href="@aggregator">main aggregator display</a> or by <a href="@aggregator-sources">their source</a>. Administrators can <a href="@feededit">add, edit and delete feeds</a> and choose how often to check each feed for newly updated items. The most recent items in either a feed or category can be displayed as a block through the <a href="@admin-block">blocks administration page</a>. A <a href="@aggregator-opml">machine-readable OPML file</a> of all feeds is available. A correctly configured <a href="@cron">cron maintenance task</a> is required to update feeds automatically.', array('@aggregator' => url('aggregator'), '@aggregator-sources' => url('aggregator/sources'), '@feededit' => url('admin/content/aggregator'), '@admin-block' => url('admin/build/block'), '@aggregator-opml' => url('aggregator/opml'), '@cron' => url('admin/reports/status'))) . '</p>';
      $output .= '<p>' . t('For more information, see the online handbook entry for <a href="@aggregator">Aggregator module</a>.', array('@aggregator' => 'http://drupal.org/handbook/modules/aggregator/')) . '</p>';
18
      return $output;
19
    case 'admin/content/aggregator':
20
      $output = '<p>' . t('Thousands of sites (particularly news sites and blogs) publish their latest headlines and posts in feeds, using a number of standardized XML-based formats. Formats supported by the aggregator include <a href="@rss">RSS</a>, <a href="@rdf">RDF</a>, and <a href="@atom">Atom</a>.', array('@rss' => 'http://cyber.law.harvard.edu/rss/', '@rdf' => 'http://www.w3.org/RDF/', '@atom' => 'http://www.atomenabled.org')) . '</p>';
21
      $output .= '<p>' . t('Current feeds are listed below, and <a href="@addfeed">new feeds may be added</a>. For each feed or feed category, the <em>latest items</em> block may be enabled at the <a href="@block">blocks administration page</a>.', array('@addfeed' => url('admin/content/aggregator/add/feed'), '@block' => url('admin/build/block'))) . '</p>';
22
      return $output;
23
    case 'admin/content/aggregator/add/feed':
24
      return '<p>' . t('Add a feed in RSS, RDF or Atom format. A feed may only have one entry.') . '</p>';
25
    case 'admin/content/aggregator/add/category':
26
      return '<p>' . t('Categories allow feed items from different feeds to be grouped together. For example, several sport-related feeds may belong to a category named <em>Sports</em>. Feed items may be grouped automatically (by selecting a category when creating or editing a feed) or manually (via the <em>Categorize</em> page available from feed item listings). Each category provides its own feed page and block.') . '</p>';
27 28
    case 'admin/content/aggregator/add/opml':
      return '<p>' . t('<acronym title="Outline Processor Markup Language">OPML</acronym> is an XML format used to exchange multiple feeds between aggregators. A single OPML document may contain a collection of many feeds. Drupal can parse such a file and import all feeds at once, saving you the effort of adding them manually. You may either upload a local file from your computer or enter a URL where Drupal can download it.') . '</p>';
Dries's avatar
 
Dries committed
29
  }
30 31
}

32
/**
33
 * Implementation of hook_theme().
34 35 36
 */
function aggregator_theme() {
  return array(
37 38 39 40 41 42
    'aggregator_wrapper' => array(
      'arguments' => array('content' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-wrapper',
    ),
    'aggregator_categorize_items' => array(
43
      'arguments' => array('form' => NULL),
44
      'file' => 'aggregator.pages.inc',
45
    ),
46
    'aggregator_feed_source' => array(
47
      'arguments' => array('feed' => NULL),
48
      'file' => 'aggregator.pages.inc',
49
      'template' => 'aggregator-feed-source',
50 51 52 53
    ),
    'aggregator_block_item' => array(
      'arguments' => array('item' => NULL, 'feed' => 0),
    ),
54 55 56 57 58
    'aggregator_summary_items' => array(
      'arguments' => array('summary_items' => NULL, 'source' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-summary-items',
    ),
59 60
    'aggregator_summary_item' => array(
      'arguments' => array('item' => NULL),
61
      'file' => 'aggregator.pages.inc',
62
      'template' => 'aggregator-summary-item',
63
    ),
64
    'aggregator_item' => array(
65
      'arguments' => array('item' => NULL),
66 67 68 69 70 71 72 73 74
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-item',
    ),
    'aggregator_page_opml' => array(
      'arguments' => array('feeds' => NULL),
      'file' => 'aggregator.pages.inc',
    ),
    'aggregator_page_rss' => array(
      'arguments' => array('feeds' => NULL, 'category' => NULL),
75
      'file' => 'aggregator.pages.inc',
76 77
    ),
  );
78
}
79

80 81 82
/**
 * Implementation of hook_menu().
 */
83 84
function aggregator_menu() {
  $items['admin/content/aggregator'] = array(
85
    'title' => 'Feed aggregator',
86
    'description' => "Configure which content your site aggregates from other sites, how often it polls them, and how they're categorized.",
87 88 89 90
    'page callback' => 'aggregator_admin_overview',
    'access arguments' => array('administer news feeds'),
  );
  $items['admin/content/aggregator/add/feed'] = array(
91
    'title' => 'Add feed',
92 93 94 95
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_feed'),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_TASK,
96
    'parent' => 'admin/content/aggregator',
97 98
  );
  $items['admin/content/aggregator/add/category'] = array(
99
    'title' => 'Add category',
100 101 102 103
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_category'),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_TASK,
104
    'parent' => 'admin/content/aggregator',
105
  );
106 107 108 109 110 111 112 113
  $items['admin/content/aggregator/add/opml'] = array(
    'title' => 'Import OPML',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_opml'),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_TASK,
    'parent' => 'admin/content/aggregator',
  );
114
  $items['admin/content/aggregator/remove/%aggregator_feed'] = array(
115
    'title' => 'Remove items',
Gábor Hojtsy's avatar
Gábor Hojtsy committed
116 117
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_admin_remove_feed', 4),
118 119 120
    'access arguments' => array('administer news feeds'),
    'type' => MENU_CALLBACK,
  );
121
  $items['admin/content/aggregator/update/%aggregator_feed'] = array(
122
    'title' => 'Update items',
123 124 125 126 127 128
    'page callback' => 'aggregator_admin_refresh_feed',
    'page arguments' => array(4),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/content/aggregator/list'] = array(
129
    'title' => 'List',
130 131 132 133
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/content/aggregator/settings'] = array(
134
    'title' => 'Settings',
135 136 137 138 139 140 141
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_admin_settings'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
    'access arguments' => array('administer news feeds'),
  );
  $items['aggregator'] = array(
142
    'title' => 'Feed aggregator',
143 144 145 146 147
    'page callback' => 'aggregator_page_last',
    'access arguments' => array('access news feeds'),
    'weight' => 5,
  );
  $items['aggregator/sources'] = array(
148
    'title' => 'Sources',
149
    'page callback' => 'aggregator_page_sources',
150 151
    'access arguments' => array('access news feeds'),
  );
152
  $items['aggregator/categories'] = array(
153
    'title' => 'Categories',
154
    'page callback' => 'aggregator_page_categories',
155
    'access callback' => '_aggregator_has_categories',
156 157
  );
  $items['aggregator/rss'] = array(
158
    'title' => 'RSS feed',
159 160 161 162 163
    'page callback' => 'aggregator_page_rss',
    'access arguments' => array('access news feeds'),
    'type' => MENU_CALLBACK,
  );
  $items['aggregator/opml'] = array(
164
    'title' => 'OPML feed',
165 166 167 168
    'page callback' => 'aggregator_page_opml',
    'access arguments' => array('access news feeds'),
    'type' => MENU_CALLBACK,
  );
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
  $items['aggregator/categories/%aggregator_category'] = array(
    'title callback' => '_aggregator_category_title',
    'title arguments' => array(2),
    'page callback' => 'aggregator_page_category',
    'page arguments' => array(2),
    'access callback' => 'user_access',
    'access arguments' => array('access news feeds'),
  );
  $items['aggregator/categories/%aggregator_category/view'] = array(
    'title' => 'View',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['aggregator/categories/%aggregator_category/categorize'] = array(
    'title' => 'Categorize',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_page_category', 2),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_TASK,
  );
  $items['aggregator/categories/%aggregator_category/configure'] = array(
    'title' => 'Configure',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_category', 2),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 1,
  );
197
  $items['aggregator/sources/%aggregator_feed'] = array(
198
    'page callback' => 'aggregator_page_source',
199
    'page arguments' => array(2),
200
    'access arguments' => array('access news feeds'),
201 202
    'type' => MENU_CALLBACK,
  );
203
  $items['aggregator/sources/%aggregator_feed/view'] = array(
204
    'title' => 'View',
205 206 207
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
208
  $items['aggregator/sources/%aggregator_feed/categorize'] = array(
209
    'title' => 'Categorize',
210
    'page callback' => 'drupal_get_form',
211
    'page arguments' => array('aggregator_page_source', 2),
212 213 214
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_TASK,
  );
215
  $items['aggregator/sources/%aggregator_feed/configure'] = array(
216
    'title' => 'Configure',
217 218 219 220 221 222
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_feed', 2),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 1,
  );
223
  $items['admin/content/aggregator/edit/feed/%aggregator_feed'] = array(
224
    'title' => 'Edit feed',
225 226 227 228 229
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_feed', 5),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_CALLBACK,
  );
230
  $items['admin/content/aggregator/edit/category/%aggregator_category'] = array(
231
    'title' => 'Edit category',
232 233 234 235 236
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_category', 5),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_CALLBACK,
  );
237 238 239 240

  return $items;
}

241 242 243 244 245 246
/**
 * Menu callback.
 *
 * @return
 *   An aggregator category title.
 */
247 248 249 250
function _aggregator_category_title($category) {
  return $category['title'];
}

251 252 253
/**
 * Implementation of hook_init().
 */
254
function aggregator_init() {
255
  drupal_add_css(drupal_get_path('module', 'aggregator') . '/aggregator.css');
256
}
257

258 259 260 261 262 263
/**
 * Find out whether there are any aggregator categories.
 *
 * @return
 *   TRUE if there is at least one category and the user has access to them, FALSE otherwise.
 */
264
function _aggregator_has_categories() {
265
  return user_access('access news feeds') && db_query('SELECT COUNT(*) FROM {aggregator_category}')->fetchField();
266
}
267

Dries's avatar
 
Dries committed
268 269 270
/**
 * Implementation of hook_perm().
 */
Kjartan's avatar
Kjartan committed
271
function aggregator_perm() {
272
  return array(
273 274 275 276 277 278 279 280
    'administer news feeds' => array(
      'title' => t('Administer news feeds'),
      'description' => t('Add, edit or delete news feeds that are aggregated to your site.'),
    ),
    'access news feeds' => array(
      'title' => t('Access news feeds'),
      'description' => t('View aggregated news feed items.'),
    ),
281
  );
Dries's avatar
 
Dries committed
282 283
}

Dries's avatar
 
Dries committed
284 285 286 287 288
/**
 * Implementation of hook_cron().
 *
 * Checks news feeds for updates once their refresh interval has elapsed.
 */
Dries's avatar
 
Dries committed
289
function aggregator_cron() {
290 291 292
  $result = db_query('SELECT * FROM {aggregator_feed} WHERE checked + refresh < :time', array(':time' => REQUEST_TIME));
  foreach ($result as $feed) {
    aggregator_refresh((array)$feed);
Dries's avatar
 
Dries committed
293 294 295
  }
}

Dries's avatar
 
Dries committed
296
/**
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
 * Implementation of hook_block_list().
 */
function aggregator_block_list() {
  $block = array();
  $result = db_query('SELECT cid, title FROM {aggregator_category} ORDER BY title');
  foreach ($result as $category) {
    $block['category-' . $category->cid]['info'] = t('!title category latest items', array('!title' => $category->title));
  }
  $result = db_query('SELECT fid, title FROM {aggregator_feed} WHERE block <> 0 ORDER BY fid');
  foreach ($result as $feed) {
    $block['feed-' . $feed->fid]['info'] = t('!title feed latest items', array('!title' => $feed->title));
  }
  return $block;
}

/**
 * Implementation of hook_block_configure().
 */
function aggregator_block_configure($delta = '') {
  list($type, $id) = explode('-', $delta);
  if ($type == 'category') {
    $value = db_query('SELECT block FROM {aggregator_category} WHERE cid = :cid', array(':cid' => $id))->fetchField();
    $form['block'] = array(
      '#type' => 'select',
      '#title' => t('Number of news items in block'),
      '#default_value' => $value,
      '#options' => drupal_map_assoc(array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20))
    );
    return $form;
  }
}

/**
 * Implementation of hook_block_save().
 */
function aggregator_block_save($delta = '', $edit = array()) {
  list($type, $id) = explode('-', $delta);
  if ($type == 'category') {
    db_merge('aggregator_category')
      ->key(array('cid' => $id))
      ->fields(array('block' => $edit['block']))
      ->execute();
  }
}

/**
 * Implementation of hook_block_view().
Dries's avatar
 
Dries committed
344 345 346
 *
 * Generates blocks for the latest news items in each category and feed.
 */
347
function aggregator_block_view($delta = '') {
Dries's avatar
 
Dries committed
348
  if (user_access('access news feeds')) {
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    $block = array();
    list($type, $id) = explode('-', $delta);
    switch ($type) {
      case 'feed':
        if ($feed = db_query('SELECT fid, title, block FROM {aggregator_feed} WHERE block <> 0 AND fid = :fid', array(':fid' => $id))->fetchObject()) {
          $block['subject'] = check_plain($feed->title);
          $result = db_query_range("SELECT * FROM {aggregator_item} WHERE fid = :fid ORDER BY timestamp DESC, iid DESC", array(':fid' => $id), 0, $feed->block);
          $read_more = theme('more_link', url('aggregator/sources/' . $feed->fid), t("View this feed's recent news."));
        }
        break;

      case 'category':
        if ($category = db_query('SELECT cid, title, block FROM {aggregator_category} WHERE cid = :cid', array(':cid' => $id))->fetchObject()) {
          $block['subject'] = check_plain($category->title);
          $result = db_query_range('SELECT i.* FROM {aggregator_category_item} ci LEFT JOIN {aggregator_item} i ON ci.iid = i.iid WHERE ci.cid = :cid ORDER BY i.timestamp DESC, i.iid DESC', array(':cid' => $category->cid), 0, $category->block);
          $read_more = theme('more_link', url('aggregator/categories/' . $category->cid), t("View this category's recent news."));
        }
        break;
Dries's avatar
Dries committed
367
    }
368 369 370
    $items = array();
    foreach ($result as $item) {
      $items[] = theme('aggregator_block_item', $item);
Dries's avatar
Dries committed
371
    }
372

373 374 375
    // Only display the block if there are items to show.
    if (count($items) > 0) {
      $block['content'] = theme('item_list', $items) . $read_more;
376
    }
377
    return $block;
Dries's avatar
 
Dries committed
378
  }
Dries's avatar
 
Dries committed
379 380
}

381 382
/**
 * Add/edit/delete aggregator categories.
383 384 385
 *
 * @param $edit
 *   An associative array describing the category to be added/edited/deleted.
386 387
 */
function aggregator_save_category($edit) {
388 389 390 391
  $link_path = 'aggregator/categories/';
  if (!empty($edit['cid'])) {
    $link_path .= $edit['cid'];
    if (!empty($edit['title'])) {
392 393 394 395 396 397 398
      db_merge('aggregator_category')
        ->key(array('cid' => $edit['cid']))
        ->fields(array(
          'title' => $edit['title'],
          'description' => $edit['description'],
        ))
        ->execute();
399 400 401
      $op = 'update';
    }
    else {
402 403 404
      db_delete('aggregator_category')
        ->condition('cid', $edit['cid'])
        ->execute();
405
      // Make sure there is no active block for this category.
406
      db_delete('block')
407 408 409
        ->condition('module', 'aggregator')
        ->condition('delta', 'category-' . $edit['cid'])
        ->execute();
410 411 412
      $edit['title'] = '';
      $op = 'delete';
    }
413
  }
414 415
  elseif (!empty($edit['title'])) {
    // A single unique id for bundles and feeds, to use in blocks.
416 417 418 419 420 421
    $link_path .= db_insert('aggregator_category')
      ->fields(array(
        'title' => $edit['title'],
        'description' => $edit['description'],
      ))
      ->execute();
422 423 424 425
    $op = 'insert';
  }
  if (isset($op)) {
    menu_link_maintain('aggregator', $op, $link_path, $edit['title']);
426 427 428 429 430
  }
}

/**
 * Add/edit/delete an aggregator feed.
431 432 433
 *
 * @param $edit
 *   An associative array describing the feed to be added/edited/deleted.
434 435
 */
function aggregator_save_feed($edit) {
436
  if (!empty($edit['fid'])) {
437
    // An existing feed is being modified, delete the category listings.
438 439 440
    db_delete('aggregator_category_feed')
      ->condition('fid', $edit['fid'])
      ->execute();
441
  }
442
  if (!empty($edit['fid']) && !empty($edit['title'])) {
443 444 445 446 447 448 449 450 451
    db_update('aggregator_feed')
      ->condition('fid', $edit['fid'])
      ->fields(array(
        'title' => $edit['title'],
        'url' => $edit['url'],
        'refresh' => $edit['refresh'],
        'block' => $edit['block'],
      ))
      ->execute();
452
  }
453
  elseif (!empty($edit['fid'])) {
454 455 456 457 458
    $iids = db_query('SELECT iid FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $edit['fid']))->fetchCol();
    if ($iids) {
      db_delete('aggregator_category_item')
        ->condition('iid', $iids, 'IN')
        ->execute();
459
    }
460 461 462 463 464 465
    db_delete('aggregator_feed')->
      condition('fid', $edit['fid'])
      ->execute();
    db_delete('aggregator_item')
      ->condition('fid', $edit['fid'])
      ->execute();
466
    // Make sure there is no active block for this feed.
467
    db_delete('block')
468 469 470
      ->condition('module', 'aggregator')
      ->condition('delta', 'feed-' . $edit['fid'])
      ->execute();
471
  }
472
  elseif (!empty($edit['title'])) {
473 474 475 476 477 478 479 480 481 482
    $edit['fid'] = db_insert('aggregator_feed')
      ->fields(array(
        'title' => $edit['title'],
        'url' => $edit['url'],
        'refresh' => $edit['refresh'],
        'block' => $edit['block'],
        'description' => '',
        'image' => '',
      ))
      ->execute();
483

484
  }
485
  if (!empty($edit['title'])) {
486
    // The feed is being saved, save the categories as well.
487
    if (!empty($edit['category'])) {
488 489
      foreach ($edit['category'] as $cid => $value) {
        if ($value) {
490
          db_merge('aggregator_category_feed')
491
            ->key(array('fid' => $edit['fid']))
492 493 494 495
            ->fields(array(
              'cid' => $cid,
            ))
            ->execute();
496 497 498 499 500 501
        }
      }
    }
  }
}

502 503 504 505 506 507
/**
 * Removes all items from a feed.
 *
 * @param $feed
 *   An associative array describing the feed to be cleared.
 */
Dries's avatar
 
Dries committed
508
function aggregator_remove($feed) {
509 510 511 512 513
  $iids = db_query('SELECT iid FROM {aggregator_item} WHERE fid = :fid', array(':fid' => $feed['fid']))->fetchCol();
  if ($iids) {
    db_delete('aggregator_category_item')
      ->condition('iid', $iids, 'IN')
      ->execute();
Dries's avatar
 
Dries committed
514
  }
515

516 517 518 519 520 521 522 523 524 525 526 527 528
  db_delete('aggregator_item')
    ->condition('fid', $feed['fid'])
    ->execute();
  db_merge('aggregator_feed')
    ->key(array('fid' => $feed['fid']))
    ->fields(array(
      'checked' => 0,
      'hash' => '',
      'modified' => 0,
      'description' => $feed['description'],
      'image' => $feed['image'],
    ))
    ->execute();
529
  drupal_set_message(t('The news items from %site have been removed.', array('%site' => $feed['title'])));
Dries's avatar
 
Dries committed
530 531
}

Dries's avatar
 
Dries committed
532
/**
533
 * Callback function used by the XML parser.
Dries's avatar
 
Dries committed
534
 */
Kjartan's avatar
Kjartan committed
535
function aggregator_element_start($parser, $name, $attributes) {
536
  global $item, $element, $tag, $items, $channel;
Dries's avatar
 
Dries committed
537 538

  switch ($name) {
Dries's avatar
 
Dries committed
539 540
    case 'IMAGE':
    case 'TEXTINPUT':
541 542 543 544 545 546
    case 'CONTENT':
    case 'SUMMARY':
    case 'TAGLINE':
    case 'SUBTITLE':
    case 'LOGO':
    case 'INFO':
Dries's avatar
 
Dries committed
547 548
      $element = $name;
      break;
549 550 551 552
    case 'ID':
      if ($element != 'ITEM') {
        $element = $name;
      }
553
    case 'LINK':
554
      if (!empty($attributes['REL']) && $attributes['REL'] == 'alternate') {
555 556 557 558 559 560 561 562
        if ($element == 'ITEM') {
          $items[$item]['LINK'] = $attributes['HREF'];
        }
        else {
          $channel['LINK'] = $attributes['HREF'];
        }
      }
      break;
Dries's avatar
 
Dries committed
563
    case 'ITEM':
Dries's avatar
 
Dries committed
564 565
      $element = $name;
      $item += 1;
566 567 568 569 570
      break;
    case 'ENTRY':
      $element = 'ITEM';
      $item += 1;
      break;
571 572 573 574 575
  }

  $tag = $name;
}

Dries's avatar
 
Dries committed
576 577 578
/**
 * Call-back function used by the XML parser.
 */
Kjartan's avatar
Kjartan committed
579
function aggregator_element_end($parser, $name) {
Dries's avatar
 
Dries committed
580 581
  global $element;

Dries's avatar
 
Dries committed
582
  switch ($name) {
Dries's avatar
 
Dries committed
583 584 585
    case 'IMAGE':
    case 'TEXTINPUT':
    case 'ITEM':
586 587 588
    case 'ENTRY':
    case 'CONTENT':
    case 'INFO':
589 590
      $element = '';
      break;
591
    case 'ID':
592
      if ($element == 'ID') {
593 594
        $element = '';
      }
Dries's avatar
 
Dries committed
595
  }
596 597
}

Dries's avatar
 
Dries committed
598
/**
599
 * Callback function used by the XML parser.
Dries's avatar
 
Dries committed
600
 */
Kjartan's avatar
Kjartan committed
601
function aggregator_element_data($parser, $data) {
Dries's avatar
 
Dries committed
602
  global $channel, $element, $items, $item, $image, $tag;
603
  $items += array($item => array());
Dries's avatar
 
Dries committed
604
  switch ($element) {
Dries's avatar
 
Dries committed
605
    case 'ITEM':
606
      $items[$item] += array($tag => '');
Dries's avatar
 
Dries committed
607 608
      $items[$item][$tag] .= $data;
      break;
Dries's avatar
 
Dries committed
609
    case 'IMAGE':
610
    case 'LOGO':
611
      $image += array($tag => '');
Dries's avatar
 
Dries committed
612 613
      $image[$tag] .= $data;
      break;
614 615
    case 'LINK':
      if ($data) {
616
        $items[$item] += array($tag => '');
617 618 619 620
        $items[$item][$tag] .= $data;
      }
      break;
    case 'CONTENT':
621
      $items[$item] += array('CONTENT' => '');
622
      $items[$item]['CONTENT'] .= $data;
623 624
      break;
    case 'SUMMARY':
625
      $items[$item] += array('SUMMARY' => '');
626
      $items[$item]['SUMMARY'] .= $data;
627 628 629
      break;
    case 'TAGLINE':
    case 'SUBTITLE':
630
      $channel += array('DESCRIPTION' => '');
631 632 633 634
      $channel['DESCRIPTION'] .= $data;
      break;
    case 'INFO':
    case 'ID':
Dries's avatar
 
Dries committed
635 636 637
    case 'TEXTINPUT':
      // The sub-element is not supported. However, we must recognize
      // it or its contents will end up in the item array.
Dries's avatar
 
Dries committed
638 639
      break;
    default:
640
      $channel += array($tag => '');
Dries's avatar
 
Dries committed
641
      $channel[$tag] .= $data;
642 643 644
  }
}

Dries's avatar
 
Dries committed
645 646
/**
 * Checks a news feed for new items.
647 648 649
 *
 * @param $feed
 *   An associative array describing the feed to be refreshed.
Dries's avatar
 
Dries committed
650
 */
Kjartan's avatar
Kjartan committed
651
function aggregator_refresh($feed) {
Dries's avatar
 
Dries committed
652 653
  global $channel, $image;

Dries's avatar
 
Dries committed
654 655 656 657 658 659
  // Generate conditional GET headers.
  $headers = array();
  if ($feed['etag']) {
    $headers['If-None-Match'] = $feed['etag'];
  }
  if ($feed['modified']) {
660
    $headers['If-Modified-Since'] = gmdate('D, d M Y H:i:s', $feed['modified']) . ' GMT';
Dries's avatar
 
Dries committed
661 662 663 664 665
  }

  // Request feed.
  $result = drupal_http_request($feed['url'], $headers);

666
  // Process HTTP response code.
Dries's avatar
 
Dries committed
667 668
  switch ($result->code) {
    case 304:
669 670 671 672
      db_update('aggregator_feed')
        ->fields(array('checked' => REQUEST_TIME))
        ->condition('fid', $feed['fid'])
        ->execute();
673
      drupal_set_message(t('There is no new syndicated content from %site.', array('%site' => $feed['title'])));
Dries's avatar
 
Dries committed
674
      break;
Dries's avatar
 
Dries committed
675 676
    case 301:
      $feed['url'] = $result->redirect_url;
677
      // Do not break here.
Dries's avatar
 
Dries committed
678 679 680
    case 200:
    case 302:
    case 307:
681 682 683 684 685
      // We store the md5 hash of feed data in the database. When refreshing a
      // feed we compare stored hash and new hash calculated from downloaded
      // data. If both are equal we say that feed is not updated.
      $md5 = md5($result->data);
      if ($feed['hash'] == $md5) {
686 687 688 689
        db_update('aggregator_feed')
          ->condition('fid', $feed['fid'])
          ->fields(array('checked' => REQUEST_TIME))
          ->execute();
690 691 692 693
        drupal_set_message(t('There is no new syndicated content from %site.', array('%site' => $feed['title'])));
        break;
      }

694
      // Filter the input data.
695
      if (aggregator_parse_feed($result->data, $feed)) {
696
        $modified = empty($result->headers['Last-Modified']) ? 0 : strtotime($result->headers['Last-Modified']);
Dries's avatar
Dries committed
697

698
        // Prepare the channel data.
699
        foreach ($channel as $key => $value) {
700
          $channel[$key] = trim($value);
701 702
        }

703
        // Prepare the image data (if any).
Dries's avatar
 
Dries committed
704 705 706
        foreach ($image as $key => $value) {
          $image[$key] = trim($value);
        }
Dries's avatar
 
Dries committed
707

708
        if (!empty($image['LINK']) && !empty($image['URL']) && !empty($image['TITLE'])) {
709
          $image = l(theme('image', $image['URL'], $image['TITLE']), $image['LINK'], array('html' => TRUE));
Dries's avatar
 
Dries committed
710
        }
Dries's avatar
 
Dries committed
711
        else {
712
          $image = '';
Dries's avatar
 
Dries committed
713
        }
Dries's avatar
 
Dries committed
714

715
        $etag = empty($result->headers['ETag']) ? '' : $result->headers['ETag'];
716
        // Update the feed data.
717 718 719 720 721 722 723 724 725 726 727 728 729
        db_merge('aggregator_feed')
          ->key(array('fid' => $feed['fid']))
          ->fields(array(
            'url' => $feed['url'],
            'checked' => REQUEST_TIME,
            'link' => $channel['LINK'],
            'description' => $channel['DESCRIPTION'],
            'image' => $image,
            'hash' => $md5,
            'etag' => $etag,
            'modified' => $modified,
          ))
          ->execute();
Dries's avatar
 
Dries committed
730

731
        // Clear the cache.
Dries's avatar
 
Dries committed
732
        cache_clear_all();
Dries's avatar
 
Dries committed
733

734 735 736 737
        if (isset($result->redirect_url)) {
          watchdog('aggregator', 'Updated URL for feed %title to %url.', array('%title' => $feed['title'], '%url' => $feed['url']));
        }

738
        watchdog('aggregator', 'There is new syndicated content from %site.', array('%site' => $feed['title']));
739
        drupal_set_message(t('There is new syndicated content from %site.', array('%site' => $feed['title'])));
Dries's avatar
 
Dries committed
740
      }
741
      break;
Dries's avatar
 
Dries committed
742
    default:
743 744
      watchdog('aggregator', 'The feed from %site seems to be broken, due to "%error".', array('%site' => $feed['title'], '%error' => $result->code . ' ' . $result->error), WATCHDOG_WARNING);
      drupal_set_message(t('The feed from %site seems to be broken, because of error "%error".', array('%site' => $feed['title'], '%error' => $result->code . ' ' . $result->error)));
745
      module_invoke('system', 'check_http_request');
Dries's avatar
 
Dries committed
746
  }
Dries's avatar
 
Dries committed
747
}
Dries's avatar
 
Dries committed
748

Dries's avatar
 
Dries committed
749
/**
750 751 752
 * Parse the W3C date/time format, a subset of ISO 8601.
 *
 * PHP date parsing functions do not handle this format.
Dries's avatar
 
Dries committed
753
 * See http://www.w3.org/TR/NOTE-datetime for more information.
754
 * Originally from MagpieRSS (http://magpierss.sourceforge.net/).
Dries's avatar
 
Dries committed
755
 *
756 757 758 759
 * @param $date_str
 *   A string with a potentially W3C DTF date.
 * @return
 *   A timestamp if parsed successfully or FALSE if not.
Dries's avatar
 
Dries committed
760 761 762 763
 */
function aggregator_parse_w3cdtf($date_str) {
  if (preg_match('/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/', $date_str, $match)) {
    list($year, $month, $day, $hours, $minutes, $seconds) = array($match[1], $match[2], $match[3], $match[4], $match[5], $match[6]);
764
    // Calculate the epoch for current date assuming GMT.
Dries's avatar
 
Dries committed
765 766 767
    $epoch = gmmktime($hours, $minutes, $seconds, $month, $day, $year);
    if ($match[10] != 'Z') { // Z is zulu time, aka GMT
      list($tz_mod, $tz_hour, $tz_min) = array($match[8], $match[9], $match[10]);
768
      // Zero out the variables.
Dries's avatar
 
Dries committed
769 770 771 772 773 774 775
      if (!$tz_hour) {
        $tz_hour = 0;
      }
      if (!$tz_min) {
        $tz_min = 0;
      }
      $offset_secs = (($tz_hour * 60) + $tz_min) * 60;
776
      // Is timezone ahead of GMT?  If yes, subtract offset.
Dries's avatar
 
Dries committed
777 778 779 780 781 782 783 784
      if ($tz_mod == '+') {
        $offset_secs *= -1;
      }
      $epoch += $offset_secs;
    }
    return $epoch;
  }
  else {
785
    return FALSE;
Dries's avatar
 
Dries committed
786 787 788
  }
}

789 790 791 792 793 794 795 796
/**
 * Parse a feed and store its items.
 *
 * @param $data
 *   The feed data.
 * @param $feed
 *   An associative array describing the feed to be parsed.
 * @return
797
 *   FALSE on error, TRUE otherwise.
798
 */
Dries's avatar
 
Dries committed
799
function aggregator_parse_feed(&$data, $feed) {
Dries's avatar
 
Dries committed
800
  global $items, $image, $channel;
Dries's avatar
 
Dries committed
801

802
  // Unset the global variables before we use them.
Dries's avatar
 
Dries committed
803
  unset($GLOBALS['element'], $GLOBALS['item'], $GLOBALS['tag']);
Dries's avatar
 
Dries committed
804
  $items = array();
Dries's avatar
 
Dries committed
805
  $image = array();
Dries's avatar
 
Dries committed
806
  $channel = array();
807

808
  // Parse the data.
Dries's avatar
 
Dries committed
809
  $xml_parser = drupal_xml_parser_create($data);
Dries's avatar
 
Dries committed
810 811
  xml_set_element_handler($xml_parser, 'aggregator_element_start', 'aggregator_element_end');
  xml_set_character_data_handler($xml_parser, 'aggregator_element_data');
Dries's avatar
 
Dries committed
812

Dries's avatar
 
Dries committed
813
  if (!xml_parse($xml_parser, $data, 1)) {
814
    watchdog('aggregator', 'The feed from %site seems to be broken, due to an error "%error" on line %line.', array('%site' => $feed['title'], '%error' => xml_error_string(xml_get_error_code($xml_parser)), '%line' => xml_get_current_line_number($xml_parser)), WATCHDOG_WARNING);
815
    drupal_set_message(t('The feed from %site seems to be broken, because of error "%error" on line %line.', array('%site' => $feed['title'], '%error' => xml_error_string(xml_get_error_code($xml_parser)), '%line' => xml_get_current_line_number($xml_parser))), 'error');
816
    return FALSE;
Dries's avatar
 
Dries committed
817 818
  }
  xml_parser_free($xml_parser);
Dries's avatar
 
Dries committed
819

820 821
  // We reverse the array such that we store the first item last, and the last
  // item first. In the database, the newest item should be at the top.
Dries's avatar
 
Dries committed
822
  $items = array_reverse($items);
Dries's avatar
 
Dries committed
823

824
  // Initialize variables.
825
  $title = $link = $author = $description = $guid = NULL;
Dries's avatar
 
Dries committed
826
  foreach ($items as $item) {
827
    unset($title, $link, $author, $description, $guid);
828

Dries's avatar
 
Dries committed
829 830
    // Prepare the item:
    foreach ($item as $key => $value) {
831
      $item[$key] = trim($value);
Dries's avatar
 
Dries committed
832
    }
Dries's avatar
Dries committed
833

834
    // Resolve the item's title. If no title is found, we use up to 40
835
    // characters of the description ending at a word boundary, but not
836
    // splitting potential entities.
837
    if (!empty($item['TITLE'])) {
Dries's avatar
 
Dries committed
838
      $title = $item['TITLE'];
Dries's avatar
 
Dries committed
839
    }
840
    elseif (!empty($item['DESCRIPTION'])) {
Dries's avatar
 
Dries committed
841
      $title = preg_replace('/^(.*)[^\w;&].*?$/', "\\1", truncate_utf8($item['DESCRIPTION'], 40));
Dries's avatar
 
Dries committed
842
    }
843 844 845
    else {
      $title = '';
    }
Dries's avatar
 
Dries committed
846

847
    // Resolve the items link.
848
    if (!empty($item['LINK'])) {
Dries's avatar
 
Dries committed
849
      $link = $item['LINK'];
Dries's avatar
 
Dries committed
850 851
    }
    else {
Dries's avatar
 
Dries committed
852
      $link = $feed['link'];
Dries's avatar
 
Dries committed
853
    }
854
    $guid = isset($item['GUID']) ? $item['GUID'] : '';
855

856
    // Atom feeds have a CONTENT and/or SUMMARY tag instead of a DESCRIPTION tag.
857
    if (!empty($item['CONTENT:ENCODED'])) {
858
      $item['DESCRIPTION'] = $item['CONTENT:ENCODED'];
859
    }
860
    elseif (!empty($item['SUMMARY'])) {
861 862
      $item['DESCRIPTION'] = $item['SUMMARY'];
    }
863
    elseif (!empty($item['CONTENT'])) {
864 865
      $item['DESCRIPTION'] = $item['CONTENT'];
    }
866

867 868
    // Try to resolve and parse the item's publication date.
    $date = '';
869 870 871 872 873 874
    foreach (array('PUBDATE', 'DC:DATE', 'DCTERMS:ISSUED', 'DCTERMS:CREATED', 'DCTERMS:MODIFIED', 'ISSUED', 'CREATED', 'MODIFIED', 'PUBLISHED', 'UPDATED') as $key) {
      if (!empty($item[$key])) {
        $date = $item[$key];
        break;
      }
    }
Dries's avatar
 
Dries committed
875

876
    $timestamp = strtotime($date);
877

878
    if ($timestamp === FALSE) {
879
      $timestamp = aggregator_parse_w3cdtf($date); // Aggregator_parse_w3cdtf() returns FALSE on failure.
880
    }
Dries's avatar
 
Dries committed
881

882 883 884
    // Save this item. Try to avoid duplicate entries as much as possible. If
    // we find a duplicate entry, we resolve it and pass along its ID is such
    // that we can update it if needed.
885
    if (!empty($guid)) {
886
      $entry = db_query("SELECT iid, timestamp FROM {aggregator_item} WHERE fid = :fid AND guid = :guid", array(':fid' => $feed['fid'], ':guid' => $guid))->fetchObject();