aggregator.module 56.5 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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
/**
 * Implementation of hook_theme()
 */
function aggregator_theme() {
  return array(
    'aggregator_page_list' => array(
      'arguments' => array('form' => NULL),
    ),
    'aggregator_feed' => array(
      'arguments' => array('feed' => NULL),
    ),
    'aggregator_block_item' => array(
      'arguments' => array('item' => NULL, 'feed' => 0),
    ),
    'aggregator_summary_item' => array(
      'arguments' => array('item' => NULL),
    ),
    'aggregator_page_item' => array(
      'arguments' => array('item' => NULL),
    ),
  );
49
}
50

51 52 53
/**
 * Implementation of hook_menu().
 */
54 55
function aggregator_menu() {
  $items['admin/content/aggregator'] = array(
56 57
    'title' => 'News aggregator',
    'description' => "Configure which content your site aggregates from other sites, how often it polls them, and how they're categorized.",
58 59 60 61
    'page callback' => 'aggregator_admin_overview',
    'access arguments' => array('administer news feeds'),
  );
  $items['admin/content/aggregator/add/feed'] = array(
62
    'title' => 'Add feed',
63 64 65 66
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_feed'),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_TASK,
67
    'parent' => 'admin/content/aggregator',
68 69
  );
  $items['admin/content/aggregator/add/category'] = array(
70
    'title' => 'Add category',
71 72 73 74
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_category'),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_TASK,
75
    'parent' => 'admin/content/aggregator',
76
  );
77
  $items['admin/content/aggregator/remove/%aggregator_feed'] = array(
78
    'title' => 'Remove items',
79 80 81 82 83
    'page callback' => 'aggregator_admin_remove_feed',
    'page arguments' => array(4),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_CALLBACK,
  );
84
  $items['admin/content/aggregator/update/%aggregator_feed'] = array(
85
    'title' => 'Update items',
86 87 88 89 90 91
    '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(
92
    'title' => 'List',
93 94 95 96
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/content/aggregator/settings'] = array(
97
    'title' => 'Settings',
98 99 100 101 102 103 104
    '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(
105
    'title' => 'News aggregator',
106 107 108 109 110
    'page callback' => 'aggregator_page_last',
    'access arguments' => array('access news feeds'),
    'weight' => 5,
  );
  $items['aggregator/sources'] = array(
111
    'title' => 'Sources',
112 113 114
    'page callback' => 'aggregator_page_sources',
    'access arguments' => array('access news feeds'));
  $items['aggregator/categories'] = array(
115
    'title' => 'Categories',
116
    'page callback' => 'aggregator_page_categories',
117
    'access callback' => '_aggregator_has_categories',
118 119
  );
  $items['aggregator/rss'] = array(
120
    'title' => 'RSS feed',
121 122 123 124 125
    'page callback' => 'aggregator_page_rss',
    'access arguments' => array('access news feeds'),
    'type' => MENU_CALLBACK,
  );
  $items['aggregator/opml'] = array(
126
    'title' => 'OPML feed',
127 128 129 130 131 132 133 134 135 136
    'page callback' => 'aggregator_page_opml',
    'access arguments' => array('access news feeds'),
    'type' => MENU_CALLBACK,
  );
  $result = db_query('SELECT title, cid FROM {aggregator_category} ORDER BY title');
  while ($category = db_fetch_array($result)) {
    $path = 'aggregator/categories/'. $category['cid'];
    $items[$path] = array(
      'title' => $category['title'],
      'page callback' => 'aggregator_page_category',
137
      'access callback' => 'user_access',
138 139 140
      'access arguments' => array('access news feeds'),
    );
    $items[$path .'/view'] = array(
141
      'title' => 'View',
142
      'type' => MENU_DEFAULT_LOCAL_TASK,
143 144 145
      'weight' => -10,
    );
    $items[$path .'/categorize'] = array(
146
      'title' => 'Categorize',
147 148 149
      'page callback' => 'drupal_get_form',
      'page arguments' => array('aggregator_page_category'),
      'access arguments' => array('administer news feeds', 2),
150
      'type' => MENU_LOCAL_TASK,
151 152
    );
    $items[$path .'/configure'] = array(
153
      'title' => 'Configure',
154 155 156 157 158 159
      'page callback' => 'drupal_get_form',
      'page arguments' => array('aggregator_form_category', 2),
      'access arguments' => array('administer news feeds', 2),
      'type' => MENU_LOCAL_TASK,
      'weight' => 1,
    );
160
  }
161
  $items['aggregator/sources/%aggregator_feed'] = array(
162 163 164
    'page callback' => 'aggregator_page_source',
    'type' => MENU_CALLBACK,
  );
165
  $items['aggregator/sources/%aggregator_feed/view'] = array(
166
    'title' => 'View',
167 168 169
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
170
  $items['aggregator/sources/%aggregator_feed/categorize'] = array(
171
    'title' => 'Categorize',
172 173 174 175 176
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_page_source'),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_TASK,
  );
177
  $items['aggregator/sources/%aggregator_feed/configure'] = array(
178
    'title' => 'Configure',
179 180 181 182 183 184
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_feed', 2),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 1,
  );
185
  $items['admin/content/aggregator/edit/feed/%aggregator_feed'] = array(
186
    'title' => 'Edit feed',
187 188 189 190 191
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_feed', 5),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_CALLBACK,
  );
192
  $items['admin/content/aggregator/edit/category/%aggregator_category'] = array(
193
    'title' => 'Edit category',
194 195 196 197 198
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_category', 5),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_CALLBACK,
  );
199 200 201 202

  return $items;
}

203 204 205
function aggregator_init() {
  drupal_add_css(drupal_get_path('module', 'aggregator') .'/aggregator.css');
}
206 207 208 209

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

Dries's avatar
Dries committed
211
function aggregator_admin_settings() {
212
  $items = array(0 => t('none')) + drupal_map_assoc(array(3, 5, 10, 15, 20, 25), '_aggregator_items');
213
  $period = drupal_map_assoc(array(3600, 10800, 21600, 32400, 43200, 86400, 172800, 259200, 604800, 1209600, 2419200, 4838400, 9676800), 'format_interval');
Dries's avatar
 
Dries committed
214

215
  $form['aggregator_allowed_html_tags'] = array(
216 217 218
    '#type' => 'textfield', '#title' => t('Allowed HTML tags'), '#size' => 80, '#maxlength' => 255,
    '#default_value' => variable_get('aggregator_allowed_html_tags', '<a> <b> <br> <dd> <dl> <dt> <em> <i> <li> <ol> <p> <strong> <u> <ul>'),
    '#description' => t('The list of tags which are allowed in feeds, i.e., which will not be removed by Drupal.')
219 220 221
  );

  $form['aggregator_summary_items'] = array(
222 223 224
    '#type' => 'select', '#title' => t('Items shown in sources and categories pages') ,
    '#default_value' => variable_get('aggregator_summary_items', 3), '#options' => $items,
    '#description' =>  t('The number of items which will be shown with each feed or category in the feed and category summary pages.')
225 226 227
  );

  $form['aggregator_clear'] = array(
228 229
    '#type' => 'select', '#title' => t('Discard news items older than'),
    '#default_value' => variable_get('aggregator_clear', 9676800), '#options' => $period,
230
    '#description' => t('Older news items will be automatically discarded. Requires crontab.')
231
  );
232

233
  $form['aggregator_category_selector'] = array(
234
    '#type' => 'radios', '#title' => t('Category selection type'), '#default_value' => variable_get('aggregator_category_selector', 'checkboxes'),
235
    '#options' => array('checkboxes' => t('checkboxes'), 'select' => t('multiple selector')),
236
    '#description' => t('The type of category selection widget which is shown on categorization pages. Checkboxes are easier to use; a multiple selector is good for working with large numbers of categories.')
237
  );
Dries's avatar
Dries committed
238

239
  return system_settings_form($form);
Dries's avatar
 
Dries committed
240 241
}

Dries's avatar
 
Dries committed
242 243 244
/**
 * Implementation of hook_perm().
 */
Kjartan's avatar
Kjartan committed
245
function aggregator_perm() {
Dries's avatar
 
Dries committed
246
  return array('administer news feeds', 'access news feeds');
Dries's avatar
 
Dries committed
247 248
}

Dries's avatar
 
Dries committed
249 250 251 252 253
/**
 * Implementation of hook_cron().
 *
 * Checks news feeds for updates once their refresh interval has elapsed.
 */
Dries's avatar
 
Dries committed
254
function aggregator_cron() {
Dries's avatar
 
Dries committed
255
  $result = db_query('SELECT * FROM {aggregator_feed} WHERE checked + refresh < %d', time());
Dries's avatar
 
Dries committed
256 257
  while ($feed = db_fetch_array($result)) {
    aggregator_refresh($feed);
Dries's avatar
 
Dries committed
258 259 260
  }
}

Dries's avatar
 
Dries committed
261 262 263 264 265
/**
 * Implementation of hook_block().
 *
 * Generates blocks for the latest news items in each category and feed.
 */
266
function aggregator_block($op = 'list', $delta = 0, $edit = array()) {
Dries's avatar
 
Dries committed
267
  if (user_access('access news feeds')) {
Dries's avatar
 
Dries committed
268
    if ($op == 'list') {
Dries's avatar
Dries committed
269
      $result = db_query('SELECT cid, title FROM {aggregator_category} ORDER BY title');
Dries's avatar
 
Dries committed
270
      while ($category = db_fetch_object($result)) {
271
        $block['category-'. $category->cid]['info'] = t('!title category latest items', array('!title' => $category->title));
Kjartan's avatar
Kjartan committed
272
      }
Dries's avatar
Dries committed
273
      $result = db_query('SELECT fid, title FROM {aggregator_feed} ORDER BY fid');
Kjartan's avatar
Kjartan committed
274
      while ($feed = db_fetch_object($result)) {
275
        $block['feed-'. $feed->fid]['info'] = t('!title feed latest items', array('!title' => $feed->title));
Kjartan's avatar
Kjartan committed
276
      }
Dries's avatar
 
Dries committed
277
    }
Dries's avatar
Dries committed
278
    else if ($op == 'configure') {
279
      list($type, $id) = explode('-', $delta);
Dries's avatar
Dries committed
280 281 282 283 284 285
      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));
      }
286
      $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)));
287
      return $form;
Dries's avatar
Dries committed
288 289
    }
    else if ($op == 'save') {
290
      list($type, $id) = explode('-', $delta);
Dries's avatar
Dries committed
291 292 293 294 295 296 297
      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);
      }
    }
298
    else if ($op == 'view') {
299
      list($type, $id) = explode('-', $delta);
Kjartan's avatar
Kjartan committed
300
      switch ($type) {
Dries's avatar
 
Dries committed
301
        case 'feed':
302
          if ($feed = db_fetch_object(db_query('SELECT fid, title, block FROM {aggregator_feed} WHERE fid = %d', $id))) {
303
            $block['subject'] = check_plain($feed->title);
304
            $result = db_query_range('SELECT * FROM {aggregator_item} WHERE fid = %d ORDER BY timestamp DESC, iid DESC', $feed->fid, 0, $feed->block);
305
            $read_more = '<div class="more-link">'. l(t('more'), 'aggregator/sources/'. $feed->fid, array('title' => t("View this feed's recent news."))) .'</div>';
306
          }
Kjartan's avatar
Kjartan committed
307
          break;
308

Dries's avatar
 
Dries committed
309
        case 'category':
310
          if ($category = db_fetch_object(db_query('SELECT cid, title, block FROM {aggregator_category} WHERE cid = %d', $id))) {
311
            $block['subject'] = check_plain($category->title);
312
            $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);
313
            $read_more = '<div class="more-link">'. l(t('more'), 'aggregator/categories/'. $category->cid, array('title' => t("View this category's recent news."))) .'</div>';
314
          }
Kjartan's avatar
Kjartan committed
315 316
          break;
      }
Dries's avatar
 
Dries committed
317 318
      $items = array();
      while ($item = db_fetch_object($result)) {
Dries's avatar
 
Dries committed
319
        $items[] = theme('aggregator_block_item', $item);
Dries's avatar
 
Dries committed
320
      }
321 322 323 324 325

      // 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
326
    }
327 328 329
    if (isset($block)) {
      return $block;
    }
Dries's avatar
 
Dries committed
330
  }
Dries's avatar
 
Dries committed
331 332
}

333 334 335
/**
 * Generate a form to add/edit/delete aggregator categories.
 */
336
function aggregator_form_category(&$form_state, $edit = array('title' => '', 'description' => '', 'cid' => NULL)) {
337 338 339 340 341 342 343 344 345 346
  $form['title'] = array('#type' => 'textfield',
    '#title' => t('Title'),
    '#default_value' => $edit['title'],
    '#maxlength' => 64,
    '#required' => TRUE,
  );
  $form['description'] = array('#type' => 'textarea',
    '#title' => t('Description'),
    '#default_value' => $edit['description'],
  );
347
  $form['submit'] = array('#type' => 'submit', '#value' => t('Save'));
348 349

  if ($edit['cid']) {
350
    $form['delete'] = array('#type' => 'submit', '#value' => t('Delete'));
351 352 353
    $form['cid'] = array('#type' => 'hidden', '#value' => $edit['cid']);
  }

354
  return $form;
355 356 357 358 359
}

/**
 * Validate aggregator_form_feed form submissions.
 */
360
function aggregator_form_category_validate($form, &$form_state) {
361
  if ($form_state['values']['op'] == t('Save')) {
362
    // Check for duplicate titles
363 364
    if (isset($form_state['values']['cid'])) {
      $category = db_fetch_object(db_query("SELECT cid FROM {aggregator_category} WHERE title = '%s' AND cid != %d", $form_state['values']['title'], $form_state['values']['cid']));
365 366
    }
    else {
367
      $category = db_fetch_object(db_query("SELECT cid FROM {aggregator_category} WHERE title = '%s'", $form_state['values']['title']));
368 369
    }
    if ($category) {
370
      form_set_error('title', t('A category named %category already exists. Please enter a unique title.', array('%category' => $form_state['values']['title'])));
371 372 373 374 375 376 377 378
    }
  }
}

/**
 * Process aggregator_form_category form submissions.
 * @todo Add delete confirmation dialog.
 */
379 380 381
function aggregator_form_category_submit($form, &$form_state) {
  if ($form_state['values']['op'] == t('Delete')) {
    $title = $form_state['values']['title'];
382
    // Unset the title:
383
    unset($form_state['values']['title']);
384
  }
385
  aggregator_save_category($form_state['values']);
386
  menu_rebuild();
387 388 389
  if (isset($form_state['values']['cid'])) {
    if (isset($form_state['values']['title'])) {
      drupal_set_message(t('The category %category has been updated.', array('%category' => $form_state['values']['title'])));
390
      if (arg(0) == 'admin') {
391 392
        $form_state['redirect'] = 'admin/content/aggregator/';
        return;
393 394
      }
      else {
395
        $form_state['redirect'] = 'aggregator/categories/'. $form_state['values']['cid'];
396
        return;
397 398 399
      }
    }
    else {
400
      watchdog('aggregator', 'Category %category deleted.', array('%category' => $title));
401
      drupal_set_message(t('The category %category has been deleted.', array('%category' => $title)));
402
      if (arg(0) == 'admin') {
403 404
        $form_state['redirect'] = 'admin/content/aggregator/';
        return;
405 406
      }
      else {
407 408
        $form_state['redirect'] = 'aggregator/categories/';
        return;
409 410 411 412
      }
    }
  }
  else {
413 414
    watchdog('aggregator', 'Category %category added.', array('%category' => $form_state['values']['title']), WATCHDOG_NOTICE, l(t('view'), 'admin/content/aggregator'));
    drupal_set_message(t('The category %category has been added.', array('%category' => $form_state['values']['title'])));
415 416 417 418 419 420 421
  }
}

/**
 * Add/edit/delete aggregator categories.
 */
function aggregator_save_category($edit) {
422
  if (!empty($edit['cid']) && !empty($edit['title'])) {
423 424
    db_query("UPDATE {aggregator_category} SET title = '%s', description = '%s' WHERE cid = %d", $edit['title'], $edit['description'], $edit['cid']);
  }
425
  else if (!empty($edit['cid'])) {
426 427
    db_query('DELETE FROM {aggregator_category} WHERE cid = %d', $edit['cid']);
  }
428
  else if (!empty($edit['title'])) {
429
    // A single unique id for bundles and feeds, to use in blocks
430
    db_query("INSERT INTO {aggregator_category} (title, description, block) VALUES ('%s', '%s', 5)", $edit['title'], $edit['description']);
431 432 433 434 435 436
  }
}

/**
 * Generate a form to add/edit feed sources.
 */
437
function aggregator_form_feed(&$form_state, $edit = array('refresh' => 900, 'title' => '', 'url' => '', 'fid' => NULL)) {
438 439 440 441 442 443 444 445 446
  $period = drupal_map_assoc(array(900, 1800, 3600, 7200, 10800, 21600, 32400, 43200, 64800, 86400, 172800, 259200, 604800, 1209600, 2419200), 'format_interval');

  if ($edit['refresh'] == '') {
    $edit['refresh'] = 3600;
  }

  $form['title'] = array('#type' => 'textfield',
    '#title' => t('Title'),
    '#default_value' => $edit['title'],
447
    '#maxlength' => 255,
448
    '#description' => t('The name of the feed; typically the name of the website you syndicate content from.'),
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
    '#required' => TRUE,
  );
  $form['url'] = array('#type' => 'textfield',
    '#title' => t('URL'),
    '#default_value' => $edit['url'],
    '#maxlength' => 255,
    '#description' => t('The fully-qualified URL of the feed.'),
    '#required' => TRUE,
  );
  $form['refresh'] = array('#type' => 'select',
    '#title' => t('Update interval'),
    '#default_value' => $edit['refresh'],
    '#options' => $period,
    '#description' => t('The refresh interval indicating how often you want to update this feed. Requires crontab.'),
  );

  // Handling of categories:
  $options = array();
  $values = array();
  $categories = db_query('SELECT c.cid, c.title, f.fid FROM {aggregator_category} c LEFT JOIN {aggregator_category_feed} f ON c.cid = f.cid AND f.fid = %d ORDER BY title', $edit['fid']);
  while ($category = db_fetch_object($categories)) {
470 471
    $options[$category->cid] = check_plain($category->title);
    if ($category->fid) $values[] = $category->cid;
472 473 474 475 476 477 478 479 480
  }
  if ($options) {
    $form['category'] = array('#type' => 'checkboxes',
      '#title' => t('Categorize news items'),
      '#default_value' => $values,
      '#options' => $options,
      '#description' => t('New items in this feed will be automatically filed in the checked categories as they are received.'),
    );
  }
481
  $form['submit'] = array('#type' => 'submit', '#value' => t('Save'));
482 483

  if ($edit['fid']) {
484
    $form['delete'] = array('#type' => 'submit', '#value' => t('Delete'));
485 486 487
    $form['fid'] = array('#type' => 'hidden', '#value' => $edit['fid']);
  }

488
  return $form;
489 490 491 492 493
}

/**
 * Validate aggregator_form_feed form submissions.
 */
494
function aggregator_form_feed_validate($form, &$form_state) {
495
  if ($form_state['values']['op'] == t('Save')) {
496
    // Check for duplicate titles
497 498
    if (isset($form_state['values']['fid'])) {
      $result = db_query("SELECT title, url FROM {aggregator_feed} WHERE (title = '%s' OR url='%s') AND fid != %d", $form_state['values']['title'], $form_state['values']['url'], $form_state['values']['fid']);
499 500
    }
    else {
501
      $result = db_query("SELECT title, url FROM {aggregator_feed} WHERE title = '%s' OR url='%s'", $form_state['values']['title'], $form_state['values']['url']);
502 503
    }
    while ($feed = db_fetch_object($result)) {
504 505
      if (strcasecmp($feed->title, $form_state['values']['title']) == 0) {
        form_set_error('title', t('A feed named %feed already exists. Please enter a unique title.', array('%feed' => $form_state['values']['title'])));
506
      }
507 508
      if (strcasecmp($feed->url, $form_state['values']['url']) == 0) {
        form_set_error('url', t('A feed with this URL %url already exists. Please enter a unique URL.', array('%url' => $form_state['values']['url'])));
509
      }
510 511 512 513 514 515 516 517
    }
  }
}

/**
 * Process aggregator_form_feed form submissions.
 * @todo Add delete confirmation dialog.
 */
518 519 520
function aggregator_form_feed_submit($form, &$form_state) {
  if ($form_state['values']['op'] == t('Delete')) {
    $title = $form_state['values']['title'];
521
    // Unset the title:
522
    unset($form_state['values']['title']);
523
  }
524
  aggregator_save_feed($form_state['values']);
525
  menu_rebuild();
526 527 528
  if (isset($form_state['values']['fid'])) {
    if (isset($form_state['values']['title'])) {
      drupal_set_message(t('The feed %feed has been updated.', array('%feed' => $form_state['values']['title'])));
529
      if (arg(0) == 'admin') {
530 531
        $form_state['redirect'] = 'admin/content/aggregator/';
        return;
532 533
      }
      else {
534
        $form_state['redirect'] = 'aggregator/sources/'. $form_state['values']['fid'];
535
        return;
536 537 538
      }
    }
    else {
539
      watchdog('aggregator', 'Feed %feed deleted.', array('%feed' => $title));
540
      drupal_set_message(t('The feed %feed has been deleted.', array('%feed' => $title)));
541
      if (arg(0) == 'admin') {
542 543
        $form_state['redirect'] = 'admin/content/aggregator/';
        return;
544 545
      }
      else {
546 547
        $form_state['redirect'] = 'aggregator/sources/';
        return;
548 549 550 551
      }
    }
  }
  else {
552 553
    watchdog('aggregator', 'Feed %feed added.', array('%feed' => $form_state['values']['title']), WATCHDOG_NOTICE, l(t('view'), 'admin/content/aggregator'));
    drupal_set_message(t('The feed %feed has been added.', array('%feed' => $form_state['values']['title'])));
554 555 556 557 558 559 560
  }
}

/**
 * Add/edit/delete an aggregator feed.
 */
function aggregator_save_feed($edit) {
561
  if (!empty($edit['fid'])) {
562 563 564
    // An existing feed is being modified, delete the category listings.
    db_query('DELETE FROM {aggregator_category_feed} WHERE fid = %d', $edit['fid']);
  }
565
  if (!empty($edit['fid']) && !empty($edit['title'])) {
566 567
    db_query("UPDATE {aggregator_feed} SET title = '%s', url = '%s', refresh = %d WHERE fid = %d", $edit['title'], $edit['url'], $edit['refresh'], $edit['fid']);
  }
568
  else if (!empty($edit['fid'])) {
569 570 571 572 573 574 575 576 577 578 579
    $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = %d', $edit['fid']);
    while ($item = db_fetch_object($result)) {
      $items[] = "iid = $item->iid";
    }
    if ($items) {
      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']);
  }
  else if ($edit['title']) {
580
    db_query("INSERT INTO {aggregator_feed} (title, url, refresh, block, description) VALUES ('%s', '%s', %d, 5, '')", $edit['title'], $edit['url'], $edit['refresh']);
581
    // A single unique id for bundles and feeds, to use in blocks.
582
    $edit['fid'] = db_last_insert_id('aggregator_feed', 'fid');
583 584 585 586 587 588 589 590 591 592 593 594 595
  }
  if ($edit['title']) {
    // The feed is being saved, save the categories as well.
    if ($edit['category']) {
      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
596 597 598 599
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
600
  }
601
  if (!empty($items)) {
Dries's avatar
 
Dries committed
602
    db_query('DELETE FROM {aggregator_category_item} WHERE '. implode(' OR ', $items));
Dries's avatar
 
Dries committed
603
  }
Dries's avatar
 
Dries committed
604
  db_query('DELETE FROM {aggregator_item} WHERE fid = %d', $feed['fid']);
Kjartan's avatar
Kjartan committed
605
  db_query("UPDATE {aggregator_feed} SET checked = 0, etag = '', modified = 0 WHERE fid = %d", $feed['fid']);
606
  drupal_set_message(t('The news items from %site have been removed.', array('%site' => $feed['title'])));
Dries's avatar
 
Dries committed
607 608
}

Dries's avatar
 
Dries committed
609 610 611
/**
 * Call-back function used by the XML parser.
 */
Kjartan's avatar
Kjartan committed
612
function aggregator_element_start($parser, $name, $attributes) {
613
  global $item, $element, $tag, $items, $channel;
Dries's avatar
 
Dries committed
614 615

  switch ($name) {
Dries's avatar
 
Dries committed
616 617
    case 'IMAGE':
    case 'TEXTINPUT':
618 619 620 621 622 623
    case 'CONTENT':
    case 'SUMMARY':
    case 'TAGLINE':
    case 'SUBTITLE':
    case 'LOGO':
    case 'INFO':
Dries's avatar
 
Dries committed
624 625
      $element = $name;
      break;
626 627 628 629
    case 'ID':
      if ($element != 'ITEM') {
        $element = $name;
      }
630
    case 'LINK':
631
      if (!empty($attributes['REL']) && $attributes['REL'] == 'alternate') {
632 633 634 635 636 637 638 639
        if ($element == 'ITEM') {
          $items[$item]['LINK'] = $attributes['HREF'];
        }
        else {
          $channel['LINK'] = $attributes['HREF'];
        }
      }
      break;
Dries's avatar
 
Dries committed
640
    case 'ITEM':
Dries's avatar
 
Dries committed
641 642
      $element = $name;
      $item += 1;
643 644 645 646 647
      break;
    case 'ENTRY':
      $element = 'ITEM';
      $item += 1;
      break;
648 649 650 651 652
  }

  $tag = $name;
}

Dries's avatar
 
Dries committed
653 654 655
/**
 * Call-back function used by the XML parser.
 */
Kjartan's avatar
Kjartan committed
656
function aggregator_element_end($parser, $name) {
Dries's avatar
 
Dries committed
657 658
  global $element;

Dries's avatar
 
Dries committed
659
  switch ($name) {
Dries's avatar
 
Dries committed
660 661 662
    case 'IMAGE':
    case 'TEXTINPUT':
    case 'ITEM':
663 664 665
    case 'ENTRY':
    case 'CONTENT':
    case 'INFO':
666 667
      $element = '';
      break;
668
    case 'ID':
669
      if ($element == 'ID') {
670 671
        $element = '';
      }
Dries's avatar
 
Dries committed
672
  }
673 674
}

Dries's avatar
 
Dries committed
675 676 677
/**
 * Call-back function used by the XML parser.
 */
Kjartan's avatar
Kjartan committed
678
function aggregator_element_data($parser, $data) {
Dries's avatar
 
Dries committed
679
  global $channel, $element, $items, $item, $image, $tag;
Dries's avatar
 
Dries committed
680
  switch ($element) {
Dries's avatar
 
Dries committed
681
    case 'ITEM':
682 683 684
      if(empty($items[$item][$tag])) {
        $items[$item][$tag] = '';
      }
Dries's avatar
 
Dries committed
685 686
      $items[$item][$tag] .= $data;
      break;
Dries's avatar
 
Dries committed
687
    case 'IMAGE':
688
    case 'LOGO':
Dries's avatar
 
Dries committed
689 690
      $image[$tag] .= $data;
      break;
691 692 693 694 695 696
    case 'LINK':
      if ($data) {
        $items[$item][$tag] .= $data;
      }
      break;
    case 'CONTENT':
697
      $items[$item]['CONTENT'] .= $data;
698 699
      break;
    case 'SUMMARY':
700
      $items[$item]['SUMMARY'] .= $data;
701 702 703 704 705 706 707
      break;
    case 'TAGLINE':
    case 'SUBTITLE':
      $channel['DESCRIPTION'] .= $data;
      break;
    case 'INFO':
    case 'ID':
Dries's avatar
 
Dries committed
708 709 710
    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
711 712
      break;
    default:
713
      $channel += array($tag => '');
Dries's avatar
 
Dries committed
714
      $channel[$tag] .= $data;
715 716 717
  }
}

Dries's avatar
 
Dries committed
718 719 720
/**
 * Checks a news feed for new items.
 */
Kjartan's avatar
Kjartan committed
721
function aggregator_refresh($feed) {
Dries's avatar
 
Dries committed
722 723
  global $channel, $image;

Dries's avatar
 
Dries committed
724 725 726 727 728 729
  // Generate conditional GET headers.
  $headers = array();
  if ($feed['etag']) {
    $headers['If-None-Match'] = $feed['etag'];
  }
  if ($feed['modified']) {
Dries's avatar
 
Dries committed
730
    $headers['If-Modified-Since'] = gmdate('D, d M Y H:i:s', $feed['modified']) .' GMT';
Dries's avatar
 
Dries committed
731 732 733 734 735
  }

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

736
  // Process HTTP response code.
Dries's avatar
 
Dries committed
737 738
  switch ($result->code) {
    case 304:
Dries's avatar
 
Dries committed
739
      db_query('UPDATE {aggregator_feed} SET checked = %d WHERE fid = %d', time(), $feed['fid']);
740
      drupal_set_message(t('There is no new syndicated content from %site.', array('%site' => $feed['title'])));
Dries's avatar
 
Dries committed
741
      break;
Dries's avatar
 
Dries committed
742 743
    case 301:
      $feed['url'] = $result->redirect_url;
744
      watchdog('aggregator', 'Updated URL for feed %title to %url.', array('%title' => $feed['title'], '%url' => $feed['url']));
745

Dries's avatar
 
Dries committed
746 747 748 749
    case 200:
    case 302:
    case 307:
      // Filter the input data:
750
     if (aggregator_parse_feed($result->data, $feed)) {
751

Dries's avatar
 
Dries committed
752 753 754
        if ($result->headers['Last-Modified']) {
          $modified = strtotime($result->headers['Last-Modified']);
        }
Dries's avatar
Dries committed
755

756 757 758 759 760
        /*
        ** Prepare the channel data:
        */

        foreach ($channel as $key => $value) {
761
          $channel[$key] = trim($value);
762 763
        }

Dries's avatar
 
Dries committed
764 765 766
        /*
        ** Prepare the image data (if any):
        */
Dries's avatar
 
Dries committed
767

Dries's avatar
 
Dries committed
768 769 770
        foreach ($image as $key => $value) {
          $image[$key] = trim($value);
        }
Dries's avatar
 
Dries committed
771

772
        if (!empty($image['LINK']) && !empty($image['URL']) && !empty($image['TITLE'])) {
773 774
          // 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
775
        }
Dries's avatar
 
Dries committed
776 777 778
        else {
          $image = NULL;
        }
Dries's avatar
 
Dries committed
779

Dries's avatar
 
Dries committed
780 781 782
        /*
        ** Update the feed data:
        */
Dries's avatar
 
Dries committed
783

784
        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, $result->headers['ETag'], $modified, $feed['fid']);
Dries's avatar
 
Dries committed
785

Dries's avatar
 
Dries committed
786 787 788
        /*
        ** Clear the cache:
        */
Dries's avatar
 
Dries committed
789

Dries's avatar
 
Dries committed
790
        cache_clear_all();
Dries's avatar
 
Dries committed
791

792
        watchdog('aggregator', 'There is new syndicated content from %site.', array('%site' => $feed['title']));
793
        drupal_set_message(t('There is new syndicated content from %site.', array('%site' => $feed['title'])));
Dries's avatar
 
Dries committed
794 795
      }
      break;
Dries's avatar
 
Dries committed
796
    default:
797
      watchdog('aggregator', 'The feed from %site seems to be broken, due to "%error".', array('%site' => $feed['title'], '%error' => $result->code .' '. $result->error), WATCHDOG_WARNING);
798
      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
799
  }
Dries's avatar
 
Dries committed
800
}
Dries's avatar
 
Dries committed
801

Dries's avatar
 
Dries committed
802 803 804 805
/**
 * 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.
806
 * Originally from MagpieRSS (http://magpierss.sourceforge.net/).
Dries's avatar
 
Dries committed
807 808
 *
 * @param $date_str A string with a potentially W3C DTF date.
809
 * @return A timestamp if parsed successfully or -1 if not.
Dries's avatar
 
Dries committed
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
 */
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 {
835
    return FALSE;
Dries's avatar
 
Dries committed
836 837 838
  }
}

Dries's avatar
 
Dries committed
839
function aggregator_parse_feed(&$data, $feed) {
Dries's avatar
 
Dries committed
840
  global $items, $image, $channel;
Dries's avatar
 
Dries committed
841

Dries's avatar
 
Dries committed
842
  // Unset the global variables before we use them:
Dries's avatar
 
Dries committed
843
  unset($GLOBALS['element'], $GLOBALS['item'], $GLOBALS['tag']);
Dries's avatar
 
Dries committed
844
  $items = array();
Dries's avatar
 
Dries committed
845
  $image = array();
Dries's avatar
 
Dries committed
846
  $channel = array();
847

Dries's avatar
 
Dries committed
848 849
  // parse the data:
  $xml_parser = drupal_xml_parser_create($data);
Dries's avatar
 
Dries committed
850 851
  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
852

Dries's avatar
 
Dries committed
853
  if (!xml_parse($xml_parser, $data, 1)) {
854
    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);
855
    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
856
    return 0;
Dries's avatar
 
Dries committed
857 858
  }
  xml_parser_free($xml_parser);
Dries's avatar
 
Dries committed
859

Dries's avatar