aggregator.module 27.8 KB
Newer Older
1
<?php
2
// $Id$
3

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

9 10 11 12 13
/**
 * Denotes that a feed's items should never expire.
 */
define('AGGREGATOR_CLEAR_NEVER', 0);

14
/**
15
 * Implements hook_help().
16
 */
17 18
function aggregator_help($path, $arg) {
  switch ($path) {
19
    case 'admin/help#aggregator':
20 21 22 23 24 25 26 27 28 29 30 31
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Aggregator module is an on-site syndicator and news reader that gathers and displays 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 in feeds, using a number of standardized XML-based formats. For more information, see the online handbook entry for <a href="@aggregator-module">Aggregator module</a>.', array('@aggregator-module' => 'http://drupal.org/handbook/modules/aggregator', '@aggregator' => url('aggregator'))) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Viewing feeds') . '</dt>';
      $output .= '<dd>' . t('Feeds contain published content, and may be grouped in categories, generally by topic. Users view feed content in the <a href="@aggregator">main aggregator display</a>, or by <a href="@aggregator-sources">their source</a> (usually via an RSS feed reader). The most recent content in a feed or category can be displayed as a block through the <a href="@admin-block">Blocks administration page</a>.', array('@aggregator' => url('aggregator'), '@aggregator-sources' => url('aggregator/sources'), '@admin-block' => url('admin/structure/block'))) . '</a></dd>';
      $output .= '<dt>' . t('Adding, editing, and deleting feeds') . '</dt>';
      $output .= '<dd>' . t('Administrators can add, edit, and delete feeds, and choose how often to check each feed for newly updated items on the <a href="@feededit">Feed aggregator administration page</a>.', array('@feededit' => url('admin/config/services/aggregator'))) . '</dd>';
      $output .= '<dt>' . t('OPML integration') . '</dt>';
      $output .= '<dd>' .  t('A <a href="@aggregator-opml">machine-readable OPML file</a> of all feeds is available. OPML is an XML-based file format used to share outline-structured information such as a list of RSS feeds. Feeds can also be <a href="@import-opml">imported via an OPML file</a>.', array('@aggregator-opml' => url('aggregator/opml'), '@import-opml' => url('admin/config/services/aggregator'))) . '</dd>';
      $output .= '<dt>' . t('Configuring cron') . '</dt>';
32
      $output .= '<dd>' .  t('A correctly configured <a href="@cron">cron maintenance task</a> is required to update feeds automatically.', array('@cron' => 'http://drupal.org/cron')) . '</dd>';
33
      $output .= '</dl>';
34
      return $output;
35
    case 'admin/config/services/aggregator':
36
      $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>';
37
      $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/config/services/aggregator/add/feed'), '@block' => url('admin/structure/block'))) . '</p>';
38
      return $output;
39
    case 'admin/config/services/aggregator/add/feed':
40
      return '<p>' . t('Add a feed in RSS, RDF or Atom format. A feed may only have one entry.') . '</p>';
41
    case 'admin/config/services/aggregator/add/category':
42
      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>';
43
    case 'admin/config/services/aggregator/add/opml':
44
      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>';
45
  }
46 47
}

48
/**
49
 * Implements hook_theme().
50 51 52
 */
function aggregator_theme() {
  return array(
53
    'aggregator_wrapper' => array(
54
      'variables' => array('content' => NULL),
55
      'file' => 'aggregator.pages.inc',
56 57 58
      'template' => 'aggregator-wrapper',
    ),
    'aggregator_categorize_items' => array(
59
      'render element' => 'form',
60
      'file' => 'aggregator.pages.inc',
61
    ),
62
    'aggregator_feed_source' => array(
63
      'variables' => array('feed' => NULL),
64
      'file' => 'aggregator.pages.inc',
65
      'template' => 'aggregator-feed-source',
66 67
    ),
    'aggregator_block_item' => array(
68
      'variables' => array('item' => NULL, 'feed' => 0),
69
    ),
70
    'aggregator_summary_items' => array(
71
      'variables' => array('summary_items' => NULL, 'source' => NULL),
72
      'file' => 'aggregator.pages.inc',
73 74
      'template' => 'aggregator-summary-items',
    ),
75
    'aggregator_summary_item' => array(
76
      'variables' => array('item' => NULL),
77
      'file' => 'aggregator.pages.inc',
78
      'template' => 'aggregator-summary-item',
79
    ),
80
    'aggregator_item' => array(
81
      'variables' => array('item' => NULL),
82
      'file' => 'aggregator.pages.inc',
83 84 85
      'template' => 'aggregator-item',
    ),
    'aggregator_page_opml' => array(
86
      'variables' => array('feeds' => NULL),
87
      'file' => 'aggregator.pages.inc',
88 89
    ),
    'aggregator_page_rss' => array(
90
      'variables' => array('feeds' => NULL, 'category' => NULL),
91
      'file' => 'aggregator.pages.inc',
92 93
    ),
  );
94
}
95

96
/**
97
 * Implements hook_menu().
98
 */
99
function aggregator_menu() {
100
  $items['admin/config/services/aggregator'] = array(
101
    'title' => 'Feed aggregator',
102
    'description' => "Configure which content your site aggregates from other sites, how often it polls them, and how they're categorized.",
103 104
    'page callback' => 'aggregator_admin_overview',
    'access arguments' => array('administer news feeds'),
105
    'weight' => 10,
106
    'file' => 'aggregator.admin.inc',
107
  );
108
  $items['admin/config/services/aggregator/add/feed'] = array(
109
    'title' => 'Add feed',
110 111 112
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_feed'),
    'access arguments' => array('administer news feeds'),
113
    'type' => MENU_LOCAL_ACTION,
114
    'file' => 'aggregator.admin.inc',
115
  );
116
  $items['admin/config/services/aggregator/add/category'] = array(
117
    'title' => 'Add category',
118 119 120
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_category'),
    'access arguments' => array('administer news feeds'),
121
    'type' => MENU_LOCAL_ACTION,
122
    'file' => 'aggregator.admin.inc',
123
  );
124
  $items['admin/config/services/aggregator/add/opml'] = array(
125 126 127 128
    'title' => 'Import OPML',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_opml'),
    'access arguments' => array('administer news feeds'),
129
    'type' => MENU_LOCAL_ACTION,
130
    'file' => 'aggregator.admin.inc',
131
  );
132
  $items['admin/config/services/aggregator/remove/%aggregator_feed'] = array(
133
    'title' => 'Remove items',
Gábor Hojtsy's avatar
Gábor Hojtsy committed
134
    'page callback' => 'drupal_get_form',
135
    'page arguments' => array('aggregator_admin_remove_feed', 5),
136 137
    'access arguments' => array('administer news feeds'),
    'type' => MENU_CALLBACK,
138
    'file' => 'aggregator.admin.inc',
139
  );
140
  $items['admin/config/services/aggregator/update/%aggregator_feed'] = array(
141
    'title' => 'Update items',
142
    'page callback' => 'aggregator_admin_refresh_feed',
143
    'page arguments' => array(5),
144 145
    'access arguments' => array('administer news feeds'),
    'type' => MENU_CALLBACK,
146
    'file' => 'aggregator.admin.inc',
147
  );
148
  $items['admin/config/services/aggregator/list'] = array(
149
    'title' => 'List',
150 151 152
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
153 154
  $items['admin/config/services/aggregator/settings'] = array(
    'title' => 'Settings',
155
    'description' => 'Configure the behavior of the feed aggregator, including when to discard feed items and how to present feed items and categories.',
156
    'page callback' => 'drupal_get_form',
157
    'page arguments' => array('aggregator_admin_form'),
158
    'access arguments' => array('administer news feeds'),
159
    'type' => MENU_LOCAL_TASK,
160
    'file' => 'aggregator.admin.inc',
161 162
  );
  $items['aggregator'] = array(
163
    'title' => 'Feed aggregator',
164 165 166
    'page callback' => 'aggregator_page_last',
    'access arguments' => array('access news feeds'),
    'weight' => 5,
167
    'file' => 'aggregator.pages.inc',
168 169
  );
  $items['aggregator/sources'] = array(
170
    'title' => 'Sources',
171
    'page callback' => 'aggregator_page_sources',
172
    'access arguments' => array('access news feeds'),
173
    'file' => 'aggregator.pages.inc',
174
  );
175
  $items['aggregator/categories'] = array(
176
    'title' => 'Categories',
177
    'page callback' => 'aggregator_page_categories',
178
    'access callback' => '_aggregator_has_categories',
179
    'file' => 'aggregator.pages.inc',
180 181
  );
  $items['aggregator/rss'] = array(
182
    'title' => 'RSS feed',
183 184 185
    'page callback' => 'aggregator_page_rss',
    'access arguments' => array('access news feeds'),
    'type' => MENU_CALLBACK,
186
    'file' => 'aggregator.pages.inc',
187 188
  );
  $items['aggregator/opml'] = array(
189
    'title' => 'OPML feed',
190 191 192
    'page callback' => 'aggregator_page_opml',
    'access arguments' => array('access news feeds'),
    'type' => MENU_CALLBACK,
193
    'file' => 'aggregator.pages.inc',
194
  );
195 196 197 198 199 200 201
  $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'),
202
    'file' => 'aggregator.pages.inc',
203 204 205 206 207 208 209 210 211
  );
  $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',
212
    'page arguments' => array('aggregator_page_category_form', 2),
213 214
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_TASK,
215
    'file' => 'aggregator.pages.inc',
216 217 218 219 220 221 222 223
  );
  $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,
224
    'file' => 'aggregator.admin.inc',
225
  );
226
  $items['aggregator/sources/%aggregator_feed'] = array(
227
    'page callback' => 'aggregator_page_source',
228
    'page arguments' => array(2),
229
    'access arguments' => array('access news feeds'),
230
    'type' => MENU_CALLBACK,
231
    'file' => 'aggregator.pages.inc',
232
  );
233
  $items['aggregator/sources/%aggregator_feed/view'] = array(
234
    'title' => 'View',
235 236 237
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
238
  $items['aggregator/sources/%aggregator_feed/categorize'] = array(
239
    'title' => 'Categorize',
240
    'page callback' => 'drupal_get_form',
241
    'page arguments' => array('aggregator_page_source_form', 2),
242 243
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_TASK,
244
    'file' => 'aggregator.pages.inc',
245
  );
246
  $items['aggregator/sources/%aggregator_feed/configure'] = array(
247
    'title' => 'Configure',
248 249 250 251 252
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_feed', 2),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 1,
253
    'file' => 'aggregator.admin.inc',
254
  );
255
  $items['admin/config/services/aggregator/edit/feed/%aggregator_feed'] = array(
256
    'title' => 'Edit feed',
257
    'page callback' => 'drupal_get_form',
258
    'page arguments' => array('aggregator_form_feed', 6),
259 260
    'access arguments' => array('administer news feeds'),
    'type' => MENU_CALLBACK,
261
    'file' => 'aggregator.admin.inc',
262
  );
263
  $items['admin/config/services/aggregator/edit/category/%aggregator_category'] = array(
264
    'title' => 'Edit category',
265
    'page callback' => 'drupal_get_form',
266
    'page arguments' => array('aggregator_form_category', 6),
267 268
    'access arguments' => array('administer news feeds'),
    'type' => MENU_CALLBACK,
269
    'file' => 'aggregator.admin.inc',
270
  );
271 272 273 274

  return $items;
}

275 276 277 278 279 280
/**
 * Menu callback.
 *
 * @return
 *   An aggregator category title.
 */
281 282 283 284
function _aggregator_category_title($category) {
  return $category['title'];
}

285 286 287 288 289 290
/**
 * 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.
 */
291
function _aggregator_has_categories() {
292
  return user_access('access news feeds') && db_query('SELECT COUNT(*) FROM {aggregator_category}')->fetchField();
293
}
294

295
/**
296
 * Implements hook_permission().
297
 */
298
function aggregator_permission() {
299
  return array(
300 301 302 303
    'administer news feeds' => array(
      'title' => t('Administer news feeds'),
    ),
    'access news feeds' => array(
304
      'title' => t('View news feeds'),
305
    ),
306
  );
Dries's avatar
Dries committed
307 308
}

309
/**
310
 * Implements hook_cron().
311
 *
312
 * Queues news feeds for updates once their refresh interval has elapsed.
313
 */
314
function aggregator_cron() {
315
  $result = db_query('SELECT * FROM {aggregator_feed} WHERE queued = 0 AND checked + refresh < :time AND refresh != :never', array(
316 317 318
    ':time' => REQUEST_TIME,
    ':never' => AGGREGATOR_CLEAR_NEVER
  ));
319
  $queue = DrupalQueue::get('aggregator_feeds');
320
  foreach ($result as $feed) {
321 322 323 324 325 326 327
    if ($queue->createItem($feed)) {
      // Add timestamp to avoid queueing item more than once.
      db_update('aggregator_feed')
        ->fields(array('queued' => REQUEST_TIME))
        ->condition('fid', $feed->fid)
        ->execute();
    }
Dries's avatar
Dries committed
328
  }
329 330 331 332 333 334

  // Remove queued timestamp after 6 hours assuming the update has failed.
  db_update('aggregator_feed')
    ->fields(array('queued' => 0))
    ->condition('queued', REQUEST_TIME - (3600 * 6), '<')
    ->execute();
Dries's avatar
Dries committed
335 336
}

337
/**
338
 * Implements hook_cron_queue_info().
339 340 341 342 343 344 345 346 347
 */
function aggregator_cron_queue_info() {
  $queues['aggregator_feeds'] = array(
    'worker callback' => 'aggregator_refresh',
    'time' => 60,
  );
  return $queues;
}

348
/**
349
 * Implements hook_block_info().
350
 */
351
function aggregator_block_info() {
352 353 354 355 356 357 358 359 360 361 362 363 364
  $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;
}

/**
365
 * Implements hook_block_configure().
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
 */
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;
  }
}

/**
382
 * Implements hook_block_save().
383 384 385 386
 */
function aggregator_block_save($delta = '', $edit = array()) {
  list($type, $id) = explode('-', $delta);
  if ($type == 'category') {
387
    db_update('aggregator_category')
388
      ->fields(array('block' => $edit['block']))
389
      ->condition('cid', $id)
390 391 392 393 394
      ->execute();
  }
}

/**
395
 * Implements hook_block_view().
396 397 398
 *
 * Generates blocks for the latest news items in each category and feed.
 */
399
function aggregator_block_view($delta = '') {
400
  if (user_access('access news feeds')) {
401 402 403 404 405 406
    $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);
407
          $result = db_query_range("SELECT * FROM {aggregator_item} WHERE fid = :fid ORDER BY timestamp DESC, iid DESC", 0, $feed->block, array(':fid' => $id));
408
          $read_more = theme('more_link', array('url' => 'aggregator/sources/' . $feed->fid, 'title' => t("View this feed's recent news.")));
409 410 411 412 413 414
        }
        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);
415
          $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', 0, $category->block, array(':cid' => $category->cid));
416
          $read_more = theme('more_link', array('url' => 'aggregator/categories/' . $category->cid, 'title' => t("View this category's recent news.")));
417 418
        }
        break;
Dries's avatar
Dries committed
419
    }
420 421
    $items = array();
    foreach ($result as $item) {
422
      $items[] = theme('aggregator_block_item', array('item' => $item));
Dries's avatar
Dries committed
423
    }
424

425 426
    // Only display the block if there are items to show.
    if (count($items) > 0) {
427
      $block['content'] = theme('item_list', array('items' => $items)) . $read_more;
428
    }
429
    return $block;
430
  }
431 432
}

433 434
/**
 * Add/edit/delete aggregator categories.
435 436 437
 *
 * @param $edit
 *   An associative array describing the category to be added/edited/deleted.
438 439
 */
function aggregator_save_category($edit) {
440 441 442 443
  $link_path = 'aggregator/categories/';
  if (!empty($edit['cid'])) {
    $link_path .= $edit['cid'];
    if (!empty($edit['title'])) {
444 445 446 447 448 449 450
      db_merge('aggregator_category')
        ->key(array('cid' => $edit['cid']))
        ->fields(array(
          'title' => $edit['title'],
          'description' => $edit['description'],
        ))
        ->execute();
451 452 453
      $op = 'update';
    }
    else {
454 455 456
      db_delete('aggregator_category')
        ->condition('cid', $edit['cid'])
        ->execute();
457
      // Make sure there is no active block for this category.
458
      db_delete('block')
459 460 461
        ->condition('module', 'aggregator')
        ->condition('delta', 'category-' . $edit['cid'])
        ->execute();
462 463 464
      $edit['title'] = '';
      $op = 'delete';
    }
465
  }
466 467
  elseif (!empty($edit['title'])) {
    // A single unique id for bundles and feeds, to use in blocks.
468 469 470 471
    $link_path .= db_insert('aggregator_category')
      ->fields(array(
        'title' => $edit['title'],
        'description' => $edit['description'],
472
        'block' => 5,
473 474
      ))
      ->execute();
475 476 477 478
    $op = 'insert';
  }
  if (isset($op)) {
    menu_link_maintain('aggregator', $op, $link_path, $edit['title']);
479 480 481 482 483
  }
}

/**
 * Add/edit/delete an aggregator feed.
484 485 486
 *
 * @param $edit
 *   An associative array describing the feed to be added/edited/deleted.
487 488
 */
function aggregator_save_feed($edit) {
489
  if (!empty($edit['fid'])) {
490
    // An existing feed is being modified, delete the category listings.
491 492 493
    db_delete('aggregator_category_feed')
      ->condition('fid', $edit['fid'])
      ->execute();
494
  }
495
  if (!empty($edit['fid']) && !empty($edit['title'])) {
496 497 498 499 500 501 502 503 504
    db_update('aggregator_feed')
      ->condition('fid', $edit['fid'])
      ->fields(array(
        'title' => $edit['title'],
        'url' => $edit['url'],
        'refresh' => $edit['refresh'],
        'block' => $edit['block'],
      ))
      ->execute();
505
  }
506
  elseif (!empty($edit['fid'])) {
507 508 509 510 511
    $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();
512
    }
513 514 515 516 517 518
    db_delete('aggregator_feed')->
      condition('fid', $edit['fid'])
      ->execute();
    db_delete('aggregator_item')
      ->condition('fid', $edit['fid'])
      ->execute();
519
    // Make sure there is no active block for this feed.
520
    db_delete('block')
521 522 523
      ->condition('module', 'aggregator')
      ->condition('delta', 'feed-' . $edit['fid'])
      ->execute();
524
  }
525
  elseif (!empty($edit['title'])) {
526 527 528 529 530 531 532 533 534 535
    $edit['fid'] = db_insert('aggregator_feed')
      ->fields(array(
        'title' => $edit['title'],
        'url' => $edit['url'],
        'refresh' => $edit['refresh'],
        'block' => $edit['block'],
        'description' => '',
        'image' => '',
      ))
      ->execute();
536

537
  }
538
  if (!empty($edit['title'])) {
539
    // The feed is being saved, save the categories as well.
540
    if (!empty($edit['category'])) {
541 542
      foreach ($edit['category'] as $cid => $value) {
        if ($value) {
543
          db_insert('aggregator_category_feed')
544
            ->fields(array(
545
              'fid' => $edit['fid'],
546 547 548
              'cid' => $cid,
            ))
            ->execute();
549 550 551 552 553 554
        }
      }
    }
  }
}

555 556 557 558
/**
 * Removes all items from a feed.
 *
 * @param $feed
559
 *   An object describing the feed to be cleared.
560
 */
561
function aggregator_remove($feed) {
562
  _aggregator_get_variables();
563 564 565
  // Call hook_aggregator_remove() on all modules.
  module_invoke_all('aggregator_remove', $feed);
  // Reset feed.
566
  db_merge('aggregator_feed')
567
    ->key(array('fid' => $feed->fid))
568 569 570
    ->fields(array(
      'checked' => 0,
      'hash' => '',
571
      'etag' => '',
572
      'modified' => 0,
573 574
      'description' => $feed->description,
      'image' => $feed->image,
575 576
    ))
    ->execute();
577 578
}

579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
function _aggregator_get_variables() {
  // Fetch the feed.
  $fetcher = variable_get('aggregator_fetcher', 'aggregator');
  if ($fetcher == 'aggregator') {
    include_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'aggregator') . '/aggregator.fetcher.inc';
  }
  $parser = variable_get('aggregator_parser', 'aggregator');
  if ($parser == 'aggregator') {
    include_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'aggregator') . '/aggregator.parser.inc';
  }
  $processors = variable_get('aggregator_processors', array('aggregator'));
  if (in_array('aggregator', $processors)) {
    include_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'aggregator') . '/aggregator.processor.inc';
  }
  return array($fetcher, $parser, $processors);
}

596 597
/**
 * Checks a news feed for new items.
598 599
 *
 * @param $feed
600
 *   An object describing the feed to be refreshed.
601
 */
602
function aggregator_refresh($feed) {
603 604 605 606
  // Store feed URL to track changes.
  $feed_url = $feed->url;

  // Fetch the feed.
607
  list($fetcher, $parser, $processors) = _aggregator_get_variables();
608
  $success = module_invoke($fetcher, 'aggregator_fetch', $feed);
609

610
  // We store the hash of feed data in the database. When refreshing a
611 612
  // feed we compare stored hash and new hash calculated from downloaded
  // data. If both are equal we say that feed is not updated.
613
  $hash = hash('sha256', $feed->source_string);
614

615
  if ($success && ($feed->hash != $hash)) {
616
    // Parse the feed.
617 618 619 620 621 622 623 624 625
    if (module_invoke($parser, 'aggregator_parse', $feed)) {
      // Update feed with parsed data.
      db_merge('aggregator_feed')
        ->key(array('fid' => $feed->fid))
        ->fields(array(
          'url' => $feed->url,
          'link' => empty($feed->link) ? $feed->url : $feed->link,
          'description' => empty($feed->description) ? '' : $feed->description,
          'image' => empty($feed->image) ? '' : $feed->image,
626
          'hash' => $hash,
627
          'etag' => empty($feed->etag) ? '' : $feed->etag,
628
          'modified' => empty($feed->modified) ? 0 : $feed->modified,
629 630
        ))
        ->execute();
631

632 633 634 635 636 637 638 639 640 641 642 643 644
      // Log if feed URL has changed.
      if ($feed->url != $feed_url) {
        watchdog('aggregator', 'Updated URL for feed %title to %url.', array('%title' => $feed->title, '%url' => $feed->url));
      }

      watchdog('aggregator', 'There is new syndicated content from %site.', array('%site' => $feed->title));
      drupal_set_message(t('There is new syndicated content from %site.', array('%site' => $feed->title)));

      // If there are items on the feed, let all enabled processors do their work on it.
      if (@count($feed->items)) {
        foreach ($processors as $processor) {
          module_invoke($processor, 'aggregator_process', $feed);
        }
645 646
      }
    }
647
  }
648 649 650
  else {
    drupal_set_message(t('There is no new syndicated content from %site.', array('%site' => $feed->title)));
  }
651

652 653 654 655 656 657
  // Regardless of successful or not, indicate that this feed has been checked.
  db_update('aggregator_feed')
    ->fields(array('checked' => REQUEST_TIME, 'queued' => 0))
    ->condition('fid', $feed->fid)
    ->execute();

658
  // Expire old feed items.
659
  if (function_exists('aggregator_expire')) {
660
    aggregator_expire($feed);
661 662 663
  }
}

664 665 666 667 668 669
/**
 * Load an aggregator feed.
 *
 * @param $fid
 *   The feed id.
 * @return
670
 *   An object describing the feed.
671
 */
672
function aggregator_feed_load($fid) {
673
  $feeds = &drupal_static(__FUNCTION__);
674
  if (!isset($feeds[$fid])) {
675
    $feeds[$fid] = db_query('SELECT * FROM {aggregator_feed} WHERE fid = :fid', array(':fid' => $fid))->fetchObject();
676
  }
677

678
  return $feeds[$fid];
679 680
}

681 682 683 684 685 686 687 688
/**
 * Load an aggregator category.
 *
 * @param $cid
 *   The category id.
 * @return
 *   An associative array describing the category.
 */
689
function aggregator_category_load($cid) {
690
  $categories = &drupal_static(__FUNCTION__);
691
  if (!isset($categories[$cid])) {
692
    $categories[$cid] = db_query('SELECT * FROM {aggregator_category} WHERE cid = :cid', array(':cid' => $cid))->fetchAssoc();
693
  }
694

695
  return $categories[$cid];
696 697
}

698
/**
699
 * Returns HTML for an individual feed item for display in the block.
700
 *
701 702 703 704 705
 * @param $variables
 *   An associative array containing:
 *   - item: The item to be displayed.
 *   - feed: Not used.
 *
706 707
 * @ingroup themeable
 */
708
function theme_aggregator_block_item($variables) {
709
  // Display the external link to the item.
710
  return '<a href="' . check_url($variables['item']->link) . '">' . check_plain($variables['item']->title) . "</a>\n";
Dries's avatar
Dries committed
711 712
}

713 714
/**
 * Safely render HTML content, as allowed.
715 716 717 718 719
 *
 * @param $value
 *   The content to be filtered.
 * @return
 *   The filtered content.
720 721
 */
function aggregator_filter_xss($value) {
722
  return filter_xss($value, preg_split('/\s+|<|>/', variable_get('aggregator_allowed_html_tags', '<a> <b> <br> <dd> <dl> <dt> <em> <i> <li> <ol> <p> <strong> <u> <ul>'), -1, PREG_SPLIT_NO_EMPTY));
723
}
724

725 726
/**
 * Check and sanitize aggregator configuration.
Dries's avatar
Dries committed
727
 *
728 729
 * Goes through all fetchers, parsers and processors and checks whether they are available.
 * If one is missing resets to standard configuration.
Dries's avatar
Dries committed
730
 *
731 732 733 734 735
 * @return
 *   TRUE if this function reset the configuration FALSE if not.
 */
function aggregator_sanitize_configuration() {
  $reset = FALSE;
736
  list($fetcher, $parser, $processors) = _aggregator_get_variables();
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
  if (!module_exists($fetcher)) {
    $reset = TRUE;
  }
  if (!module_exists($parser)) {
    $reset = TRUE;
  }
  foreach ($processors as $processor) {
    if (!module_exists($processor)) {
      $reset = TRUE;
      break;
    }
  }
  if ($reset) {
    variable_del('aggregator_fetcher');
    variable_del('aggregator_parser');
    variable_del('aggregator_processors');
    return TRUE;
  }
  return FALSE;
}

758 759
/**
 * Helper function for drupal_map_assoc.
760 761 762 763 764
 *
 * @param $count
 *   Items count.
 * @return
 *   Plural-formatted "@count items"
765 766
 */
function _aggregator_items($count) {
767
  return format_plural($count, '1 item', '@count items');
768
}