aggregator.module 32.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
      $output = '<p>'. t('The news aggregator is a powerful on-site RSS syndicator/news reader that can gather fresh content from news sites and weblogs around the web.') .'</p>';
16 17
      $output .= '<p>'. t('Users can view the latest news chronologically in the <a href="@aggregator">main news aggregator display</a> or by <a href="@aggregator-sources">source</a>. Administrators can add, edit and delete feeds and choose how often to check for newly updated news for each individual feed. Administrators can also tag individual feeds with categories, offering selective grouping of some feeds into separate displays. Listings of the latest news for individual sources or categorized sources can be enabled as blocks for display in the sidebar through the <a href="@admin-block">block administration page</a>. The news aggregator requires cron to check for the latest news from the sites to which you have subscribed. Drupal also provides a <a href="@aggregator-opml">machine-readable OPML file</a> of all of your subscribed feeds.', array('@aggregator' => url('aggregator'), '@aggregator-sources' => url('aggregator/sources'), '@admin-block' => url('admin/build/block'), '@aggregator-opml' => url('aggregator/opml'))) .'</p>';
      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="@aggregator">Aggregator page</a>.', array('@aggregator' => 'http://drupal.org/handbook/modules/aggregator/')) .'</p>';
18
      return $output;
19
    case 'admin/content/aggregator':
20
      return '<p>'. t('Thousands of sites (particularly news sites and weblogs) publish their latest headlines and/or stories in a machine-readable format so that other sites can easily link to them. This content is usually in the form of an <a href="http://blogs.law.harvard.edu/tech/rss">RSS</a> feed (which is an XML-based syndication standard). To display the feed or category in a block you must decide how many items to show by editing the feed or block and turning on the <a href="@block">feed\'s block</a>.', array('@block' => url('admin/build/block'))) .'</p>';
21
    case 'admin/content/aggregator/add/feed':
22
      return '<p>'. t('Add a site that has an RSS/RDF/Atom feed. The URL is the full path to the feed file. For the feed to update automatically you must run "cron.php" on a regular basis. If you already have a feed with the URL you are planning to use, the system will not accept another feed with the same URL.') .'</p>';
23
    case 'admin/content/aggregator/add/category':
24
      return '<p>'. t('Categories provide a way to group items from different news feeds together. Each news category has its own feed page and block. For example, you could tag various sport-related feeds as belonging to a category called <em>Sports</em>. News items can be added to a category automatically by setting a feed to automatically place its item into that category, or by using the categorize items link in any listing of news items.') .'</p>';
Dries's avatar
 
Dries committed
25
  }
26 27
}

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

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

  return $items;
}

247 248 249 250
function _aggregator_category_title($category) {
  return $category['title'];
}

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

function _aggregator_has_categories() {
  return user_access('access news feeds') && db_result(db_query('SELECT COUNT(*) FROM {aggregator_category}'));
}
258

Dries's avatar
Dries committed
259

Dries's avatar
 
Dries committed
260

Dries's avatar
 
Dries committed
261 262 263
/**
 * Implementation of hook_perm().
 */
Kjartan's avatar
Kjartan committed
264
function aggregator_perm() {
Dries's avatar
 
Dries committed
265
  return array('administer news feeds', 'access news feeds');
Dries's avatar
 
Dries committed
266 267
}

Dries's avatar
 
Dries committed
268 269 270 271 272
/**
 * Implementation of hook_cron().
 *
 * Checks news feeds for updates once their refresh interval has elapsed.
 */
Dries's avatar
 
Dries committed
273
function aggregator_cron() {
Dries's avatar
 
Dries committed
274
  $result = db_query('SELECT * FROM {aggregator_feed} WHERE checked + refresh < %d', time());
Dries's avatar
 
Dries committed
275 276
  while ($feed = db_fetch_array($result)) {
    aggregator_refresh($feed);
Dries's avatar
 
Dries committed
277 278 279
  }
}

Dries's avatar
 
Dries committed
280 281 282 283 284
/**
 * Implementation of hook_block().
 *
 * Generates blocks for the latest news items in each category and feed.
 */
285
function aggregator_block($op = 'list', $delta = 0, $edit = array()) {
Dries's avatar
 
Dries committed
286
  if (user_access('access news feeds')) {
Dries's avatar
 
Dries committed
287
    if ($op == 'list') {
Dries's avatar
Dries committed
288
      $result = db_query('SELECT cid, title FROM {aggregator_category} ORDER BY title');
Dries's avatar
 
Dries committed
289
      while ($category = db_fetch_object($result)) {
290
        $block['category-'. $category->cid]['info'] = t('!title category latest items', array('!title' => $category->title));
Kjartan's avatar
Kjartan committed
291
      }
Dries's avatar
Dries committed
292
      $result = db_query('SELECT fid, title FROM {aggregator_feed} ORDER BY fid');
Kjartan's avatar
Kjartan committed
293
      while ($feed = db_fetch_object($result)) {
294
        $block['feed-'. $feed->fid]['info'] = t('!title feed latest items', array('!title' => $feed->title));
Kjartan's avatar
Kjartan committed
295
      }
Dries's avatar
 
Dries committed
296
    }
Dries's avatar
Dries committed
297
    else if ($op == 'configure') {
298
      list($type, $id) = explode('-', $delta);
Dries's avatar
Dries committed
299 300 301 302 303 304
      if ($type == 'category') {
        $value = db_result(db_query('SELECT block FROM {aggregator_category} WHERE cid = %d', $id));
      }
      else {
        $value = db_result(db_query('SELECT block FROM {aggregator_feed} WHERE fid = %d', $id));
      }
305
      $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)));
306
      return $form;
Dries's avatar
Dries committed
307 308
    }
    else if ($op == 'save') {
309
      list($type, $id) = explode('-', $delta);
Dries's avatar
Dries committed
310 311 312 313 314 315 316
      if ($type == 'category') {
        $value = db_query('UPDATE {aggregator_category} SET block = %d WHERE cid = %d', $edit['block'], $id);
      }
      else {
        $value = db_query('UPDATE {aggregator_feed} SET block = %d WHERE fid = %d', $edit['block'], $id);
      }
    }
317
    else if ($op == 'view') {
318
      list($type, $id) = explode('-', $delta);
Kjartan's avatar
Kjartan committed
319
      switch ($type) {
Dries's avatar
 
Dries committed
320
        case 'feed':
321
          if ($feed = db_fetch_object(db_query('SELECT fid, title, block FROM {aggregator_feed} WHERE fid = %d', $id))) {
322
            $block['subject'] = check_plain($feed->title);
323
            $result = db_query_range('SELECT * FROM {aggregator_item} WHERE fid = %d ORDER BY timestamp DESC, iid DESC', $feed->fid, 0, $feed->block);
324
            $read_more = theme('more_link', url('aggregator/sources/'. $feed->fid), t("View this feed's recent news."));
325
          }
Kjartan's avatar
Kjartan committed
326
          break;
327

Dries's avatar
 
Dries committed
328
        case 'category':
329
          if ($category = db_fetch_object(db_query('SELECT cid, title, block FROM {aggregator_category} WHERE cid = %d', $id))) {
330
            $block['subject'] = check_plain($category->title);
331
            $result = db_query_range('SELECT i.* FROM {aggregator_category_item} ci LEFT JOIN {aggregator_item} i ON ci.iid = i.iid WHERE ci.cid = %d ORDER BY i.timestamp DESC, i.iid DESC', $category->cid, 0, $category->block);
332
            $read_more = theme('more_link', url('aggregator/categories/'. $category->cid), t("View this category's recent news."));
333
          }
Kjartan's avatar
Kjartan committed
334 335
          break;
      }
Dries's avatar
 
Dries committed
336 337
      $items = array();
      while ($item = db_fetch_object($result)) {
Dries's avatar
 
Dries committed
338
        $items[] = theme('aggregator_block_item', $item);
Dries's avatar
 
Dries committed
339
      }
340 341 342 343 344

      // Only display the block if there are items to show.
      if (count($items) > 0) {
        $block['content'] = theme('item_list', $items) . $read_more;
      }
Dries's avatar
 
Dries committed
345
    }
346 347 348
    if (isset($block)) {
      return $block;
    }
Dries's avatar
 
Dries committed
349
  }
Dries's avatar
 
Dries committed
350 351
}

352 353 354 355
/**
 * Add/edit/delete aggregator categories.
 */
function aggregator_save_category($edit) {
356 357 358 359 360 361 362 363 364 365 366 367
  $link_path = 'aggregator/categories/';
  if (!empty($edit['cid'])) {
    $link_path .= $edit['cid'];
    if (!empty($edit['title'])) {
      db_query("UPDATE {aggregator_category} SET title = '%s', description = '%s' WHERE cid = %d", $edit['title'], $edit['description'], $edit['cid']);
      $op = 'update';
    }
    else {
      db_query('DELETE FROM {aggregator_category} WHERE cid = %d', $edit['cid']);
      $edit['title'] = '';
      $op = 'delete';
    }
368
  }
369
  else if (!empty($edit['title'])) {
370
    // A single unique id for bundles and feeds, to use in blocks
371
    db_query("INSERT INTO {aggregator_category} (title, description, block) VALUES ('%s', '%s', 5)", $edit['title'], $edit['description']);
372 373 374 375 376
    $link_path .= db_last_insert_id('aggregator', 'cid');
    $op = 'insert';
  }
  if (isset($op)) {
    menu_link_maintain('aggregator', $op, $link_path, $edit['title']);
377 378 379 380 381 382 383
  }
}

/**
 * Add/edit/delete an aggregator feed.
 */
function aggregator_save_feed($edit) {
384
  if (!empty($edit['fid'])) {
385 386 387
    // An existing feed is being modified, delete the category listings.
    db_query('DELETE FROM {aggregator_category_feed} WHERE fid = %d', $edit['fid']);
  }
388
  if (!empty($edit['fid']) && !empty($edit['title'])) {
389 390
    db_query("UPDATE {aggregator_feed} SET title = '%s', url = '%s', refresh = %d WHERE fid = %d", $edit['title'], $edit['url'], $edit['refresh'], $edit['fid']);
  }
391
  else if (!empty($edit['fid'])) {
392
    $items = array();
393 394 395 396
    $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = %d', $edit['fid']);
    while ($item = db_fetch_object($result)) {
      $items[] = "iid = $item->iid";
    }
397
    if (!empty($items)) {
398 399 400 401 402
      db_query('DELETE FROM {aggregator_category_item} WHERE '. implode(' OR ', $items));
    }
    db_query('DELETE FROM {aggregator_feed} WHERE fid = %d', $edit['fid']);
    db_query('DELETE FROM {aggregator_item} WHERE fid = %d', $edit['fid']);
  }
403
  else if (!empty($edit['title'])) {
404
    db_query("INSERT INTO {aggregator_feed} (title, url, refresh, block, description, image) VALUES ('%s', '%s', %d, 5, '', '')", $edit['title'], $edit['url'], $edit['refresh']);
405
    // A single unique id for bundles and feeds, to use in blocks.
406
    $edit['fid'] = db_last_insert_id('aggregator_feed', 'fid');
407
  }
408
  if (!empty($edit['title'])) {
409
    // The feed is being saved, save the categories as well.
410
    if (!empty($edit['category'])) {
411 412 413 414 415 416 417 418 419
      foreach ($edit['category'] as $cid => $value) {
        if ($value) {
          db_query('INSERT INTO {aggregator_category_feed} (fid, cid) VALUES (%d, %d)', $edit['fid'], $cid);
        }
      }
    }
  }
}

Dries's avatar
 
Dries committed
420 421 422 423
function aggregator_remove($feed) {
  $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = %d', $feed['fid']);
  while ($item = db_fetch_object($result)) {
    $items[] = "iid = $item->iid";
Dries's avatar
 
Dries committed
424
  }
425
  if (!empty($items)) {
Dries's avatar
 
Dries committed
426
    db_query('DELETE FROM {aggregator_category_item} WHERE '. implode(' OR ', $items));
Dries's avatar
 
Dries committed
427
  }
Dries's avatar
 
Dries committed
428
  db_query('DELETE FROM {aggregator_item} WHERE fid = %d', $feed['fid']);
Kjartan's avatar
Kjartan committed
429
  db_query("UPDATE {aggregator_feed} SET checked = 0, etag = '', modified = 0 WHERE fid = %d", $feed['fid']);
430
  drupal_set_message(t('The news items from %site have been removed.', array('%site' => $feed['title'])));
Dries's avatar
 
Dries committed
431 432
}

Dries's avatar
 
Dries committed
433 434 435
/**
 * Call-back function used by the XML parser.
 */
Kjartan's avatar
Kjartan committed
436
function aggregator_element_start($parser, $name, $attributes) {
437
  global $item, $element, $tag, $items, $channel;
Dries's avatar
 
Dries committed
438 439

  switch ($name) {
Dries's avatar
 
Dries committed
440 441
    case 'IMAGE':
    case 'TEXTINPUT':
442 443 444 445 446 447
    case 'CONTENT':
    case 'SUMMARY':
    case 'TAGLINE':
    case 'SUBTITLE':
    case 'LOGO':
    case 'INFO':
Dries's avatar
 
Dries committed
448 449
      $element = $name;
      break;
450 451 452 453
    case 'ID':
      if ($element != 'ITEM') {
        $element = $name;
      }
454
    case 'LINK':
455
      if (!empty($attributes['REL']) && $attributes['REL'] == 'alternate') {
456 457 458 459 460 461 462 463
        if ($element == 'ITEM') {
          $items[$item]['LINK'] = $attributes['HREF'];
        }
        else {
          $channel['LINK'] = $attributes['HREF'];
        }
      }
      break;
Dries's avatar
 
Dries committed
464
    case 'ITEM':
Dries's avatar
 
Dries committed
465 466
      $element = $name;
      $item += 1;
467 468 469 470 471
      break;
    case 'ENTRY':
      $element = 'ITEM';
      $item += 1;
      break;
472 473 474 475 476
  }

  $tag = $name;
}

Dries's avatar
 
Dries committed
477 478 479
/**
 * Call-back function used by the XML parser.
 */
Kjartan's avatar
Kjartan committed
480
function aggregator_element_end($parser, $name) {
Dries's avatar
 
Dries committed
481 482
  global $element;

Dries's avatar
 
Dries committed
483
  switch ($name) {
Dries's avatar
 
Dries committed
484 485 486
    case 'IMAGE':
    case 'TEXTINPUT':
    case 'ITEM':
487 488 489
    case 'ENTRY':
    case 'CONTENT':
    case 'INFO':
490 491
      $element = '';
      break;
492
    case 'ID':
493
      if ($element == 'ID') {
494 495
        $element = '';
      }
Dries's avatar
 
Dries committed
496
  }
497 498
}

Dries's avatar
 
Dries committed
499 500 501
/**
 * Call-back function used by the XML parser.
 */
Kjartan's avatar
Kjartan committed
502
function aggregator_element_data($parser, $data) {
Dries's avatar
 
Dries committed
503
  global $channel, $element, $items, $item, $image, $tag;
504
  $items += array($item => array());
Dries's avatar
 
Dries committed
505
  switch ($element) {
Dries's avatar
 
Dries committed
506
    case 'ITEM':
507
      $items[$item] += array($tag => '');
Dries's avatar
 
Dries committed
508 509
      $items[$item][$tag] .= $data;
      break;
Dries's avatar
 
Dries committed
510
    case 'IMAGE':
511
    case 'LOGO':
512
      $image += array($tag => '');
Dries's avatar
 
Dries committed
513 514
      $image[$tag] .= $data;
      break;
515 516
    case 'LINK':
      if ($data) {
517
        $items[$item] += array($tag => '');
518 519 520 521
        $items[$item][$tag] .= $data;
      }
      break;
    case 'CONTENT':
522
      $items[$item] += array('CONTENT' => '');
523
      $items[$item]['CONTENT'] .= $data;
524 525
      break;
    case 'SUMMARY':
526
      $items[$item] += array('SUMMARY' => '');
527
      $items[$item]['SUMMARY'] .= $data;
528 529 530
      break;
    case 'TAGLINE':
    case 'SUBTITLE':
531
      $channel += array('DESCRIPTION' => '');
532 533 534 535
      $channel['DESCRIPTION'] .= $data;
      break;
    case 'INFO':
    case 'ID':
Dries's avatar
 
Dries committed
536 537 538
    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
539 540
      break;
    default:
541
      $channel += array($tag => '');
Dries's avatar
 
Dries committed
542
      $channel[$tag] .= $data;
543 544 545
  }
}

Dries's avatar
 
Dries committed
546 547 548
/**
 * Checks a news feed for new items.
 */
Kjartan's avatar
Kjartan committed
549
function aggregator_refresh($feed) {
Dries's avatar
 
Dries committed
550 551
  global $channel, $image;

Dries's avatar
 
Dries committed
552 553 554 555 556 557
  // Generate conditional GET headers.
  $headers = array();
  if ($feed['etag']) {
    $headers['If-None-Match'] = $feed['etag'];
  }
  if ($feed['modified']) {
Dries's avatar
 
Dries committed
558
    $headers['If-Modified-Since'] = gmdate('D, d M Y H:i:s', $feed['modified']) .' GMT';
Dries's avatar
 
Dries committed
559 560 561 562 563
  }

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

564
  // Process HTTP response code.
Dries's avatar
 
Dries committed
565 566
  switch ($result->code) {
    case 304:
Dries's avatar
 
Dries committed
567
      db_query('UPDATE {aggregator_feed} SET checked = %d WHERE fid = %d', time(), $feed['fid']);
568
      drupal_set_message(t('There is no new syndicated content from %site.', array('%site' => $feed['title'])));
Dries's avatar
 
Dries committed
569
      break;
Dries's avatar
 
Dries committed
570 571
    case 301:
      $feed['url'] = $result->redirect_url;
572
      watchdog('aggregator', 'Updated URL for feed %title to %url.', array('%title' => $feed['title'], '%url' => $feed['url']));
573

Dries's avatar
 
Dries committed
574 575 576 577
    case 200:
    case 302:
    case 307:
      // Filter the input data:
578
     if (aggregator_parse_feed($result->data, $feed)) {
579

580
        $modified = empty($result->headers['Last-Modified']) ? 0 : strtotime($result->headers['Last-Modified']);
Dries's avatar
Dries committed
581

582 583 584 585 586
        /*
        ** Prepare the channel data:
        */

        foreach ($channel as $key => $value) {
587
          $channel[$key] = trim($value);
588 589
        }

Dries's avatar
 
Dries committed
590 591 592
        /*
        ** Prepare the image data (if any):
        */
Dries's avatar
 
Dries committed
593

Dries's avatar
 
Dries committed
594 595 596
        foreach ($image as $key => $value) {
          $image[$key] = trim($value);
        }
Dries's avatar
 
Dries committed
597

598
        if (!empty($image['LINK']) && !empty($image['URL']) && !empty($image['TITLE'])) {
599 600
          // Note, we should really use theme_image() here but that only works with local images it won't work with images fetched with a URL unless PHP version > 5
          $image = '<a href="'. check_url($image['LINK']) .'" class="feed-image"><img src="'. check_url($image['URL']) .'" alt="'. check_plain($image['TITLE']) .'" /></a>';
Dries's avatar
 
Dries committed
601
        }
Dries's avatar
 
Dries committed
602 603 604
        else {
          $image = NULL;
        }
Dries's avatar
 
Dries committed
605

606
        $etag = empty($result->headers['ETag']) ? '' : $result->headers['ETag'];
Dries's avatar
 
Dries committed
607 608 609
        /*
        ** Update the feed data:
        */
Dries's avatar
 
Dries committed
610

611
        db_query("UPDATE {aggregator_feed} SET url = '%s', checked = %d, link = '%s', description = '%s', image = '%s', etag = '%s', modified = %d WHERE fid = %d", $feed['url'], time(), $channel['LINK'], $channel['DESCRIPTION'], $image, $etag, $modified, $feed['fid']);
Dries's avatar
 
Dries committed
612

Dries's avatar
 
Dries committed
613 614 615
        /*
        ** Clear the cache:
        */
Dries's avatar
 
Dries committed
616

Dries's avatar
 
Dries committed
617
        cache_clear_all();
Dries's avatar
 
Dries committed
618

619
        watchdog('aggregator', 'There is new syndicated content from %site.', array('%site' => $feed['title']));
620
        drupal_set_message(t('There is new syndicated content from %site.', array('%site' => $feed['title'])));
Dries's avatar
 
Dries committed
621 622
      }
      break;
Dries's avatar
 
Dries committed
623
    default:
624
      watchdog('aggregator', 'The feed from %site seems to be broken, due to "%error".', array('%site' => $feed['title'], '%error' => $result->code .' '. $result->error), WATCHDOG_WARNING);
625
      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)));
Dries's avatar
 
Dries committed
626
  }
Dries's avatar
 
Dries committed
627
}
Dries's avatar
 
Dries committed
628

Dries's avatar
 
Dries committed
629 630 631 632
/**
 * Parse the W3C date/time format, a subset of ISO 8601. PHP date parsing
 * functions do not handle this format.
 * See http://www.w3.org/TR/NOTE-datetime for more information.
633
 * Originally from MagpieRSS (http://magpierss.sourceforge.net/).
Dries's avatar
 
Dries committed
634 635
 *
 * @param $date_str A string with a potentially W3C DTF date.
636
 * @return A timestamp if parsed successfully or -1 if not.
Dries's avatar
 
Dries committed
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
 */
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]);
    // calc epoch for current date assuming GMT
    $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]);
      // zero out the variables
      if (!$tz_hour) {
        $tz_hour = 0;
      }
      if (!$tz_min) {
        $tz_min = 0;
      }
      $offset_secs = (($tz_hour * 60) + $tz_min) * 60;
      // is timezone ahead of GMT?  then subtract offset
      if ($tz_mod == '+') {
        $offset_secs *= -1;
      }
      $epoch += $offset_secs;
    }
    return $epoch;
  }
  else {
662
    return FALSE;
Dries's avatar
 
Dries committed
663 664 665
  }
}

Dries's avatar
 
Dries committed
666
function aggregator_parse_feed(&$data, $feed) {
Dries's avatar
 
Dries committed
667
  global $items, $image, $channel;
Dries's avatar
 
Dries committed
668

Dries's avatar
 
Dries committed
669
  // Unset the global variables before we use them:
Dries's avatar
 
Dries committed
670
  unset($GLOBALS['element'], $GLOBALS['item'], $GLOBALS['tag']);
Dries's avatar
 
Dries committed
671
  $items = array();
Dries's avatar
 
Dries committed
672
  $image = array();
Dries's avatar
 
Dries committed
673
  $channel = array();
674

Dries's avatar
 
Dries committed
675 676
  // parse the data:
  $xml_parser = drupal_xml_parser_create($data);
Dries's avatar
 
Dries committed
677 678
  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
679

Dries's avatar
 
Dries committed
680
  if (!xml_parse($xml_parser, $data, 1)) {
681
    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);
682
    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');
Dries's avatar
 
Dries committed
683
    return 0;
Dries's avatar
 
Dries committed
684 685
  }
  xml_parser_free($xml_parser);
Dries's avatar
 
Dries committed
686

Dries's avatar
 
Dries committed
687 688
  /*
  ** We reverse the array such that we store the first item last,
689
  ** and the last item first. In the database, the newest item
Dries's avatar
 
Dries committed
690 691
  ** should be at the top.
  */
Dries's avatar
 
Dries committed
692

Dries's avatar
 
Dries committed
693
  $items = array_reverse($items);
Dries's avatar
 
Dries committed
694

695 696
  // Initialize variables
  $title = $link = $author = $description = $guid = NULL;
Dries's avatar
 
Dries committed
697
  foreach ($items as $item) {
698
    unset($title, $link, $author, $description, $guid);
699

Dries's avatar
 
Dries committed
700 701
    // Prepare the item:
    foreach ($item as $key => $value) {
702
      $item[$key] = trim($value);
Dries's avatar
 
Dries committed
703
    }
Dries's avatar
Dries committed
704

Dries's avatar
 
Dries committed
705
    /*
706
    ** Resolve the item's title. If no title is found, we use
Dries's avatar
 
Dries committed
707 708 709 710
    ** up to 40 characters of the description ending at a word
    ** boundary but not splitting potential entities.
    */

711
    if (!empty($item['TITLE'])) {
Dries's avatar
 
Dries committed
712
      $title = $item['TITLE'];
Dries's avatar
 
Dries committed
713
    }
714
    elseif (!empty($item['DESCRIPTION'])) {
Dries's avatar
 
Dries committed
715
      $title = preg_replace('/^(.*)[^\w;&].*?$/', "\\1", truncate_utf8($item['DESCRIPTION'], 40));
Dries's avatar
 
Dries committed
716
    }
717 718 719
    else {
      $title = '';
    }
Dries's avatar
 
Dries committed
720

Dries's avatar
 
Dries committed
721 722 723 724
    /*
    ** Resolve the items link.
    */

725
    if (!empty($item['LINK'])) {
Dries's avatar
 
Dries committed
726
      $link = $item['LINK'];
Dries's avatar
 
Dries committed
727 728
    }
    else {
Dries's avatar
 
Dries committed
729
      $link = $feed['link'];
Dries's avatar
 
Dries committed
730
    }
731
    $guid = isset($item['GUID']) ? $item['GUID'] : '';
732

733 734 735
    /**
     * Atom feeds have a CONTENT and/or SUMMARY tag instead of a DESCRIPTION tag
     */
736
    if (!empty($item['CONTENT:ENCODED'])) {
737
      $item['DESCRIPTION'] = $item['CONTENT:ENCODED'];
738
    }
739
    else if (!empty($item['SUMMARY'])) {
740 741
      $item['DESCRIPTION'] = $item['SUMMARY'];
    }
742
    else if (!empty($item['CONTENT'])) {
743 744
      $item['DESCRIPTION'] = $item['CONTENT'];
    }
745

Dries's avatar
 
Dries committed
746
    /*
747
    ** Try to resolve and parse the item's publication date. If no
Dries's avatar
 
Dries committed
748 749 750
    ** date is found, we use the current date instead.
    */

751 752 753 754 755 756 757
    $date = 'now';
    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
758

759 760 761 762
    $timestamp = strtotime($date); // As of PHP 5.1.0, strtotime returns FALSE on failure instead of -1.
    if ($timestamp <= 0) {
      $timestamp = aggregator_parse_w3cdtf($date); // Returns FALSE on failure
      if (!$timestamp) {
Dries's avatar
 
Dries committed
763 764
        $timestamp = time(); // better than nothing
      }
765
    }
Dries's avatar
 
Dries committed
766 767

    /*
768 769
    ** Save this item. Try to avoid duplicate entries as much as
    ** possible. If we find a duplicate entry, we resolve it and
770
    ** pass along its ID is such that we can update it if needed.
Dries's avatar
 
Dries committed
771 772
    */

773
    if (!empty($guid)) {
774 775 776
      $entry = db_fetch_object(db_query("SELECT iid FROM {aggregator_item} WHERE fid = %d AND guid = '%s'", $feed['fid'], $guid));
    }
    else if ($link && $link != $feed['link'] && $link != $feed['url']) {
Dries's avatar
 
Dries committed
777
      $entry = db_fetch_object(db_query("SELECT iid FROM {aggregator_item} WHERE fid = %d AND link = '%s'", $feed['fid'], $link));
Dries's avatar
 
Dries committed
778 779
    }
    else {
Dries's avatar
 
Dries committed
780
      $entry = db_fetch_object(db_query("SELECT iid FROM {aggregator_item} WHERE fid = %d AND title = '%s'", $feed['fid'], $title));
Dries's avatar
 
Dries committed
781
    }
782 783
    $item += array('AUTHOR' => '', 'DESCRIPTION' => '');
    aggregator_save_item(array('iid' => (isset($entry->iid) ? $entry->iid:  ''), 'fid' => $feed['fid'], 'timestamp' => $timestamp, 'title' => $title, 'link' => $link, 'author' => $item['AUTHOR'], 'description' => $item['DESCRIPTION'], 'guid' => $guid));
Dries's avatar
 
Dries committed
784
  }
Dries's avatar
 
Dries committed
785

Dries's avatar
 
Dries committed
786
  /*
787
  ** Remove all items that are older than flush item timer:
Dries's avatar
 
Dries committed
788
  */
Dries's avatar
 
Dries committed
789

790
  $age = time() - variable_get('aggregator_clear', 9676800);
Dries's avatar
 
Dries committed
791
  $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = %d AND timestamp < %d', $feed['fid'], $age);
Dries's avatar