initial import from onelab svn codebase
[plewww.git] / modules / aggregator.module
1 <?php
2 // $Id: aggregator.module 144 2007-03-28 07:52:20Z thierry $
3
4 /**
5  * @file
6  * Used to aggregate syndicated content (RSS, RDF, and Atom).
7  */
8
9 /**
10  * Implementation of hook_help().
11  */
12 function aggregator_help($section) {
13   switch ($section) {
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       $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/block'), '%aggregator-opml' => url('aggregator/opml'))) .'</p>';
17       $output .= t('<p>You can</p>
18 <ul>
19 <li>administer your list of news feeds <a href="%admin-aggregator">administer &gt;&gt;  aggregator</a>.</li>
20 <li>add a new feed <a href="%admin-aggregator-add-feed">administer &gt;&gt; aggregator &gt;&gt; add feed</a>.</li>
21 <li>add a new category <a href="%admin-aggregator-add-category">administer &gt;&gt; aggregator &gt;&gt; add category</a>.</li>
22 <li>configure global settings for the news aggregator <a href="%admin-settings-aggregator">administer &gt;&gt; settings &gt;&gt; aggregator</a>.</li>
23 <li>control access to the aggregator module through access permissions <a href="%admin-access">administer &gt;&gt; access control &gt;&gt; permissions</a>.</li>
24 <li>set permissions to access new feeds for user roles such as anonymous users at <a href="%admin-access">administer &gt;&gt; access control</a>.</li>
25 <li>view the <a href="%aggregator">aggregator page</a>.</li>
26 </ul>
27 ', array('%admin-aggregator' => url('admin/aggregator'), '%admin-aggregator-add-feed' => url('admin/aggregator/add/feed'), '%admin-aggregator-add-category' => url('admin/aggregator/add/category'), '%admin-settings-aggregator' => url('admin/settings/aggregator'), '%admin-access' => url('admin/access'), '%aggregator' => url('aggregator')));
28       $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>';
29       return $output;
30     case 'admin/modules#description':
31       return t('Aggregates syndicated content (RSS, RDF, and Atom feeds).');
32     case 'admin/aggregator':
33       return t('<p>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>.</p>', array('%block' => url('admin/block')));
34     case 'admin/aggregator/add/feed':
35       return t('<p>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>');
36     case 'admin/aggregator/add/category':
37       return t('<p>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>');
38   }
39 }
40
41 /**
42  * Implementation of hook_menu().
43  */
44 function aggregator_menu($may_cache) {
45   $items = array();
46   $edit = user_access('administer news feeds');
47   $view = user_access('access news feeds');
48
49   if ($may_cache) {
50     $items[] = array('path' => 'admin/aggregator',
51       'title' => t('aggregator'),
52       'callback' => 'aggregator_admin_overview',
53       'access' => $edit);
54     $items[] = array('path' => 'admin/aggregator/add/feed',
55       'title' => t('add feed'),
56       'callback' => 'aggregator_form_feed',
57       'access' => $edit,
58       'type' => MENU_LOCAL_TASK);
59     $items[] = array('path' => 'admin/aggregator/add/category',
60       'title' => t('add category'),
61       'callback' => 'aggregator_form_category',
62       'access' => $edit,
63       'type' => MENU_LOCAL_TASK);
64     $items[] = array('path' => 'admin/aggregator/remove',
65       'title' => t('remove items'),
66       'callback' => 'aggregator_admin_remove_feed',
67       'access' => $edit,
68       'type' => MENU_CALLBACK);
69     $items[] = array('path' => 'admin/aggregator/update',
70       'title' => t('update items'),
71       'callback' => 'aggregator_admin_refresh_feed',
72       'access' => $edit,
73       'type' => MENU_CALLBACK);
74     $items[] = array('path' => 'admin/aggregator/list',
75       'title' => t('list'),
76       'type' => MENU_DEFAULT_LOCAL_TASK,
77       'weight' => -10);
78
79     $items[] = array('path' => 'aggregator',
80       'title' => t('news aggregator'),
81       'callback' => 'aggregator_page_last',
82       'access' => $view,
83       'weight' => 5);
84     $items[] = array('path' => 'aggregator/sources',
85       'title' => t('sources'),
86       'callback' => 'aggregator_page_sources',
87       'access' => $view);
88     $items[] = array('path' => 'aggregator/categories',
89       'title' => t('categories'),
90       'callback' => 'aggregator_page_categories',
91       'access' => $view,
92       'type' => MENU_ITEM_GROUPING);
93     $items[] = array('path' => 'aggregator/rss',
94       'title' => t('RSS feed'),
95       'callback' => 'aggregator_page_rss',
96       'access' => $view,
97       'type' => MENU_CALLBACK);
98     $items[] = array('path' => 'aggregator/opml',
99       'title' => t('OPML feed'),
100       'callback' => 'aggregator_page_opml',
101       'access' => $view,
102       'type' => MENU_CALLBACK);
103
104     $result = db_query('SELECT title, cid FROM {aggregator_category} ORDER BY title');
105     while ($category = db_fetch_array($result)) {
106       $items[] = array('path' => 'aggregator/categories/'. $category['cid'],
107         'title' => $category['title'],
108         'callback' => 'aggregator_page_category',
109         'access' => $view);
110     }
111   }
112   else {
113     if (arg(0) == 'aggregator' && is_numeric(arg(2))) {
114       if (arg(1) == 'sources') {
115         $feed = aggregator_get_feed(arg(2));
116         if ($feed) {
117           $items[] = array('path' => 'aggregator/sources/'. $feed['fid'],
118             'title' => $feed['title'],
119             'callback' => 'aggregator_page_source',
120             'access' => $view,
121             'type' => MENU_CALLBACK);
122           $items[] = array('path' => 'aggregator/sources/'. $feed['fid'] .'/view',
123             'title' => t('view'),
124             'type' => MENU_DEFAULT_LOCAL_TASK,
125             'weight' => -10);
126           $items[] = array('path' => 'aggregator/sources/'. $feed['fid'] .'/categorize',
127             'title' => t('categorize'),
128             'callback' => 'aggregator_page_source',
129             'access' => $edit,
130             'type' => MENU_LOCAL_TASK);
131           $items[] = array('path' => 'aggregator/sources/'. $feed['fid'] .'/configure',
132             'title' => t('configure'),
133             'callback' => 'aggregator_form_feed',
134             'callback arguments' => array($feed),
135             'access' => $edit,
136             'type' => MENU_LOCAL_TASK,
137             'weight' => 1);
138         }
139       }
140       else if (arg(1) == 'categories') {
141         $category = aggregator_get_category(arg(2));
142         if ($category) {
143           $items[] = array('path' => 'aggregator/categories/'. $category['cid'] .'/view',
144             'title' => t('view'),
145             'type' => MENU_DEFAULT_LOCAL_TASK,
146             'weight' => -10);
147           $items[] = array('path' => 'aggregator/categories/'. $category['cid'] .'/categorize',
148             'title' => t('categorize'),
149             'callback' => 'aggregator_page_category',
150             'access' => $edit,
151             'type' => MENU_LOCAL_TASK);
152           $items[] = array('path' => 'aggregator/categories/'. $category['cid'] .'/configure',
153             'title' => t('configure'),
154             'callback' => 'aggregator_form_category',
155             'callback arguments' => array($category),
156             'access' => $edit,
157             'type' => MENU_LOCAL_TASK,
158             'weight' => 1);
159         }
160       }
161     }
162     else if (arg(1) == 'aggregator' && is_numeric(arg(4))) {
163       if (arg(3) == 'feed') {
164         $feed = aggregator_get_feed(arg(4));
165         if ($feed) {
166           $items[] = array('path' => 'admin/aggregator/edit/feed/'. $feed['fid'],
167             'title' => t('edit feed'),
168             'callback' => 'aggregator_form_feed',
169             'callback arguments' => array($feed),
170             'access' => $edit,
171             'type' => MENU_CALLBACK);
172         }
173       }
174       else {
175         $category = aggregator_get_category(arg(4));
176         if ($category) {
177           $items[] = array('path' => 'admin/aggregator/edit/category/'. $category['cid'],
178             'title' => t('edit category'),
179             'callback' => 'aggregator_form_category',
180             'callback arguments' => array($category),
181             'access' => $edit,
182             'type' => MENU_CALLBACK);
183         }
184       }
185     }
186   }
187
188   return $items;
189 }
190
191 /**
192  * Implementation of hook_settings().
193  */
194 function aggregator_settings() {
195   $items = array(0 => t('none')) + drupal_map_assoc(array(3, 5, 10, 15, 20, 25), '_aggregator_items');
196   $period = drupal_map_assoc(array(3600, 10800, 21600, 32400, 43200, 86400, 172800, 259200, 604800, 1209600, 2419200, 4838400, 9676800), 'format_interval');
197
198   $form['aggregator_allowed_html_tags'] = array(
199     '#type' => 'textfield', '#title' => t('Allowed HTML tags'), '#size' => 80, '#maxlength' => 255,
200     '#default_value' => variable_get('aggregator_allowed_html_tags', '<a> <b> <br> <dd> <dl> <dt> <em> <i> <li> <ol> <p> <strong> <u> <ul>'),
201     '#description' => t('The list of tags which are allowed in feeds, i.e., which will not be removed by Drupal.')
202   );
203
204   $form['aggregator_summary_items'] = array(
205     '#type' => 'select', '#title' => t('Items shown in sources and categories pages') ,
206     '#default_value' => variable_get('aggregator_summary_items', 3), '#options' => $items,
207     '#description' =>  t('The number of items which will be shown with each feed or category in the feed and category summary pages.')
208   );
209
210   $form['aggregator_clear'] = array(
211     '#type' => 'select', '#title' => t('Discard news items older than'),
212     '#default_value' => variable_get('aggregator_clear', 9676800), '#options' => $period,
213     '#description' => t('Older news items will be automatically discarded.  Requires crontab.')
214   );
215
216   $form['aggregator_category_selector'] = array(
217     '#type' => 'radios', '#title' => t('Category selection type'), '#default_value' => variable_get('aggregator_category_selector', 'check'),
218     '#options' => array('checkboxes' => t('checkboxes'), 'select' => t('multiple selector')),
219     '#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.')
220   );
221   return $form;
222 }
223
224 /**
225  * Implementation of hook_perm().
226  */
227 function aggregator_perm() {
228   return array('administer news feeds', 'access news feeds');
229 }
230
231 /**
232  * Implementation of hook_cron().
233  *
234  * Checks news feeds for updates once their refresh interval has elapsed.
235  */
236 function aggregator_cron() {
237   $result = db_query('SELECT * FROM {aggregator_feed} WHERE checked + refresh < %d', time());
238   while ($feed = db_fetch_array($result)) {
239     aggregator_refresh($feed);
240   }
241 }
242
243 /**
244  * Implementation of hook_block().
245  *
246  * Generates blocks for the latest news items in each category and feed.
247  */
248 function aggregator_block($op, $delta = 0, $edit = array()) {
249   if (user_access('access news feeds')) {
250     if ($op == 'list') {
251       $result = db_query('SELECT cid, title FROM {aggregator_category} ORDER BY title');
252       while ($category = db_fetch_object($result)) {
253         $block['category-'. $category->cid]['info'] = t('%title category latest items', array('%title' => theme('placeholder', $category->title)));
254       }
255       $result = db_query('SELECT fid, title FROM {aggregator_feed} ORDER BY fid');
256       while ($feed = db_fetch_object($result)) {
257         $block['feed-'. $feed->fid]['info'] = t('%title feed latest items', array('%title' => theme('placeholder', $feed->title)));
258       }
259     }
260     else if ($op == 'configure') {
261       list($type, $id) = explode('-', $delta);
262       if ($type == 'category') {
263         $value = db_result(db_query('SELECT block FROM {aggregator_category} WHERE cid = %d', $id));
264       }
265       else {
266         $value = db_result(db_query('SELECT block FROM {aggregator_feed} WHERE fid = %d', $id));
267       }
268       $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)));
269       return $form;
270     }
271     else if ($op == 'save') {
272       list($type, $id) = explode('-', $delta);
273       if ($type == 'category') {
274         $value = db_query('UPDATE {aggregator_category} SET block = %d WHERE cid = %d', $edit['block'], $id);
275       }
276       else {
277         $value = db_query('UPDATE {aggregator_feed} SET block = %d WHERE fid = %d', $edit['block'], $id);
278       }
279     }
280     else if ($op == 'view') {
281       list($type, $id) = explode('-', $delta);
282       switch ($type) {
283         case 'feed':
284           if ($feed = db_fetch_object(db_query('SELECT fid, title, block FROM {aggregator_feed} WHERE fid = %d', $id))) {
285             $block['subject'] = check_plain($feed->title);
286             $result = db_query_range('SELECT * FROM {aggregator_item} WHERE fid = %d ORDER BY timestamp DESC, iid DESC', $feed->fid, 0, $feed->block);
287             $block['content'] = '<div class="more-link">'. l(t('more'), 'aggregator/sources/'. $feed->fid, array('title' => t('View this feed\'s recent news.'))) .'</div>';
288           }
289           break;
290
291         case 'category':
292           if ($category = db_fetch_object(db_query('SELECT cid, title, block FROM {aggregator_category} WHERE cid = %d', $id))) {
293             $block['subject'] = check_plain($category->title);
294             $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);
295             $block['content'] = '<div class="more-link">'. l(t('more'), 'aggregator/categories/'. $category->cid, array('title' => t('View this category\'s recent news.'))) .'</div>';
296           }
297           break;
298       }
299       $items = array();
300       while ($item = db_fetch_object($result)) {
301         $items[] = theme('aggregator_block_item', $item);
302       }
303       $block['content'] = theme('item_list', $items) . $block['content'];
304     }
305     return $block;
306   }
307 }
308
309 /**
310  * Generate a form to add/edit/delete aggregator categories.
311  */
312  function aggregator_form_category($edit = array()) {
313   $form['title'] = array('#type' => 'textfield',
314     '#title' => t('Title'),
315     '#default_value' => $edit['title'],
316     '#maxlength' => 64,
317     '#required' => TRUE,
318   );
319   $form['description'] = array('#type' => 'textarea',
320     '#title' => t('Description'),
321     '#default_value' => $edit['description'],
322   );
323   $form['submit'] = array('#type' => 'submit', '#value' =>t('Submit'));
324
325   if ($edit['cid']) {
326     $form['delete'] = array('#type' => 'submit', '#value' =>t('Delete'));
327     $form['cid'] = array('#type' => 'hidden', '#value' => $edit['cid']);
328   }
329
330   return drupal_get_form('aggregator_form_category', $form);
331 }
332
333 /**
334  * Validate aggregator_form_feed form submissions.
335  */
336 function aggregator_form_category_validate($form_id, $form_values) {
337   if ($_POST['op'] == t('Submit')) {
338     // Check for duplicate titles
339     if (isset($form_values['cid'])) {
340       $category = db_fetch_object(db_query("SELECT cid FROM {aggregator_category} WHERE title = '%s' AND cid != %d", $form_values['title'], $form_values['cid']));
341     }
342     else {
343       $category = db_fetch_object(db_query("SELECT cid FROM {aggregator_category} WHERE title = '%s'", $form_values['title']));
344     }
345     if ($category) {
346       form_set_error('title', t('A category named %category already exists. Please enter a unique title.', array('%category' => theme('placeholder', $form_values['title']))));
347     }
348   }
349 }
350
351 /**
352  * Process aggregator_form_category form submissions.
353  * @todo Add delete confirmation dialog.
354  */
355 function aggregator_form_category_submit($form_id, $form_values) {
356   if ($_POST['op'] == t('Delete')) {
357     $title = $form_values['title'];
358     // Unset the title:
359     unset($form_values['title']);
360   }
361   aggregator_save_category($form_values);
362   menu_rebuild();
363   if (isset($form_values['cid'])) {
364     if (isset($form_values['title'])) {
365       drupal_set_message(t('The category %category has been updated.', array('%category' => theme('placeholder', $form_values['title']))));
366       if (arg(0) == 'admin') {
367         return 'admin/aggregator/';
368       }
369       else {
370         return 'aggregator/categories/'. $form_values['cid'];
371       }
372     }
373     else {
374       watchdog('aggregator', t('Category %category deleted.', array('%category' => theme('placeholder', $title))));
375       drupal_set_message(t('The category %category has been deleted.', array('%category' => theme('placeholder', $title))));
376       if (arg(0) == 'admin') {
377         return 'admin/aggregator/';
378       }
379       else {
380         return 'aggregator/categories/';
381       }
382     }
383   }
384   else {
385     watchdog('aggregator', t('Category %category added.', array('%category' => theme('placeholder', $form_values['title']))), WATCHDOG_NOTICE, l(t('view'), 'admin/aggregator'));
386     drupal_set_message(t('The category %category has been added.', array('%category' => theme('placeholder', $form_values['title']))));
387   }
388 }
389
390 /**
391  * Add/edit/delete aggregator categories.
392  */
393 function aggregator_save_category($edit) {
394   if ($edit['cid'] && $edit['title']) {
395     db_query("UPDATE {aggregator_category} SET title = '%s', description = '%s' WHERE cid = %d", $edit['title'], $edit['description'], $edit['cid']);
396   }
397   else if ($edit['cid']) {
398     db_query('DELETE FROM {aggregator_category} WHERE cid = %d', $edit['cid']);
399   }
400   else if ($edit['title']) {
401     // A single unique id for bundles and feeds, to use in blocks
402     $next_id = db_next_id('{aggregator_category}_cid');
403     db_query("INSERT INTO {aggregator_category} (cid, title, description, block) VALUES (%d, '%s', '%s', 5)", $next_id, $edit['title'], $edit['description']);
404   }
405 }
406
407 /**
408  * Generate a form to add/edit feed sources.
409  */
410 function aggregator_form_feed($edit = array()) {
411   $period = drupal_map_assoc(array(900, 1800, 3600, 7200, 10800, 21600, 32400, 43200, 64800, 86400, 172800, 259200, 604800, 1209600, 2419200), 'format_interval');
412
413   if ($edit['refresh'] == '') {
414     $edit['refresh'] = 3600;
415   }
416
417   $form['title'] = array('#type' => 'textfield',
418     '#title' => t('Title'),
419     '#default_value' => $edit['title'],
420     '#maxlength' => 64,
421     '#description' => t('The name of the feed; typically the name of the web site you syndicate content from.'),
422     '#required' => TRUE,
423   );
424   $form['url'] = array('#type' => 'textfield',
425     '#title' => t('URL'),
426     '#default_value' => $edit['url'],
427     '#maxlength' => 255,
428     '#description' => t('The fully-qualified URL of the feed.'),
429     '#required' => TRUE,
430   );
431   $form['refresh'] = array('#type' => 'select',
432     '#title' => t('Update interval'),
433     '#default_value' => $edit['refresh'],
434     '#options' => $period,
435     '#description' => t('The refresh interval indicating how often you want to update this feed. Requires crontab.'),
436   );
437
438   // Handling of categories:
439   $options = array();
440   $values = array();
441   $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']);
442   while ($category = db_fetch_object($categories)) {
443     $options[$category->cid] = $category->title;
444     if ($category->fid) $values[] = check_plain($category->cid);
445   }
446   if ($options) {
447     $form['category'] = array('#type' => 'checkboxes',
448       '#title' => t('Categorize news items'),
449       '#default_value' => $values,
450       '#options' => $options,
451       '#description' => t('New items in this feed will be automatically filed in the checked categories as they are received.'),
452     );
453   }
454   $form['submit'] = array('#type' => 'submit', '#value' =>t('Submit'));
455
456   if ($edit['fid']) {
457     $form['delete'] = array('#type' => 'submit', '#value' =>t('Delete'));
458     $form['fid'] = array('#type' => 'hidden', '#value' => $edit['fid']);
459   }
460
461   return drupal_get_form('aggregator_form_feed', $form);
462 }
463
464 /**
465  * Validate aggregator_form_feed form submissions.
466  */
467 function aggregator_form_feed_validate($form_id, $form_values) {
468   if ($_POST['op'] == t('Submit')) {
469     // Check for duplicate titles
470     if (isset($form_values['fid'])) {
471       $result = db_query("SELECT title, url FROM {aggregator_feed} WHERE (title = '%s' OR url='%s') AND fid != %d", $form_values['title'], $form_values['url'], $form_values['fid']);
472     }
473     else {
474       $result = db_query("SELECT title, url FROM {aggregator_feed} WHERE title = '%s' OR url='%s'", $form_values['title'], $form_values['url']);
475     }
476     while ($feed = db_fetch_object($result)) {
477       if (strcasecmp($feed->title, $form_values['title']) == 0) {
478         form_set_error('title', t('A feed named %feed already exists. Please enter a unique title.', array('%feed' => theme('placeholder', $form_values['title']))));
479       }
480     }
481   }
482 }
483
484 /**
485  * Process aggregator_form_feed form submissions.
486  * @todo Add delete confirmation dialog.
487  */
488 function aggregator_form_feed_submit($form_id, $form_values) {
489   if ($_POST['op'] == t('Delete')) {
490     $title = $form_values['title'];
491     // Unset the title:
492     unset($form_values['title']);
493   }
494   aggregator_save_feed($form_values);
495   menu_rebuild();
496   if (isset($form_values['fid'])) {
497     if (isset($form_values['title'])) {
498       drupal_set_message(t('The feed %feed has been updated.', array('%feed' => theme('placeholder', $form_values['title']))));
499       if (arg(0) == 'admin') {
500         return 'admin/aggregator/';
501       }
502       else {
503         return 'aggregator/sources/'. $form_values['fid'];
504       }
505     }
506     else {
507       watchdog('aggregator', t('Feed %feed deleted.', array('%feed' => theme('placeholder', $title))));
508       drupal_set_message(t('The feed %feed has been deleted.', array('%feed' => theme('placeholder', $title))));
509       if (arg(0) == 'admin') {
510         return 'admin/aggregator/';
511       }
512       else {
513         return 'aggregator/sources/';
514       }
515     }
516   }
517   else {
518     watchdog('aggregator', t('Feed %feed added.', array('%feed' => theme('placeholder', $form_values['title']))), WATCHDOG_NOTICE, l(t('view'), 'admin/aggregator'));
519     drupal_set_message(t('The feed %feed has been added.', array('%feed' => theme('placeholder', $form_values['title']))));
520   }
521 }
522
523 /**
524  * Add/edit/delete an aggregator feed.
525  */
526 function aggregator_save_feed($edit) {
527   if ($edit['fid']) {
528     // An existing feed is being modified, delete the category listings.
529     db_query('DELETE FROM {aggregator_category_feed} WHERE fid = %d', $edit['fid']);
530   }
531   if ($edit['fid'] && $edit['title']) {
532     db_query("UPDATE {aggregator_feed} SET title = '%s', url = '%s', refresh = %d WHERE fid = %d", $edit['title'], $edit['url'], $edit['refresh'], $edit['fid']);
533   }
534   else if ($edit['fid']) {
535     $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = %d', $edit['fid']);
536     while ($item = db_fetch_object($result)) {
537       $items[] = "iid = $item->iid";
538     }
539     if ($items) {
540       db_query('DELETE FROM {aggregator_category_item} WHERE '. implode(' OR ', $items));
541     }
542     db_query('DELETE FROM {aggregator_feed} WHERE fid = %d', $edit['fid']);
543     db_query('DELETE FROM {aggregator_item} WHERE fid = %d', $edit['fid']);
544   }
545   else if ($edit['title']) {
546     // A single unique id for bundles and feeds, to use in blocks.
547     $edit['fid'] = db_next_id('{aggregator_feed}_fid');
548     db_query("INSERT INTO {aggregator_feed} (fid, title, url, refresh, block) VALUES (%d, '%s', '%s', %d, 5)", $edit['fid'], $edit['title'], $edit['url'], $edit['refresh']);
549   }
550   if ($edit['title']) {
551     // The feed is being saved, save the categories as well.
552     if ($edit['category']) {
553       foreach ($edit['category'] as $cid => $value) {
554         if ($value) {
555           db_query('INSERT INTO {aggregator_category_feed} (fid, cid) VALUES (%d, %d)', $edit['fid'], $cid);
556         }
557       }
558     }
559   }
560 }
561
562 function aggregator_remove($feed) {
563   $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = %d', $feed['fid']);
564   while ($item = db_fetch_object($result)) {
565     $items[] = "iid = $item->iid";
566   }
567   if ($items) {
568     db_query('DELETE FROM {aggregator_category_item} WHERE '. implode(' OR ', $items));
569   }
570   db_query('DELETE FROM {aggregator_item} WHERE fid = %d', $feed['fid']);
571   db_query("UPDATE {aggregator_feed} SET checked = 0, etag = '', modified = 0 WHERE fid = %d", $feed['fid']);
572   drupal_set_message(t('The news items from %site have been removed.', array('%site' => theme('placeholder', $feed['title']))));
573 }
574
575 /**
576  * Call-back function used by the XML parser.
577  */
578 function aggregator_element_start($parser, $name, $attributes) {
579   global $item, $element, $tag, $items, $channel;
580
581   switch ($name) {
582     case 'IMAGE':
583     case 'TEXTINPUT':
584     case 'CONTENT':
585     case 'SUMMARY':
586     case 'TAGLINE':
587     case 'SUBTITLE':
588     case 'LOGO':
589     case 'INFO':
590       $element = $name;
591       break;
592     case 'ID':
593       if ($element != 'ITEM') {
594         $element = $name;
595       }
596     case 'LINK':
597       if ($attributes['REL'] == 'alternate') {
598         if ($element == 'ITEM') {
599           $items[$item]['LINK'] = $attributes['HREF'];
600         }
601         else {
602           $channel['LINK'] = $attributes['HREF'];
603         }
604       }
605       break;
606     case 'ITEM':
607       $element = $name;
608       $item += 1;
609       break;
610     case 'ENTRY':
611       $element = 'ITEM';
612       $item += 1;
613       break;
614   }
615
616   $tag = $name;
617 }
618
619 /**
620  * Call-back function used by the XML parser.
621  */
622 function aggregator_element_end($parser, $name) {
623   global $element;
624
625   switch ($name) {
626     case 'IMAGE':
627     case 'TEXTINPUT':
628     case 'ITEM':
629     case 'ENTRY':
630     case 'CONTENT':
631     case 'INFO':
632       $element = '';
633       break;
634     case 'ID':
635       if ($element == 'ID') {
636         $element = '';
637       }
638   }
639 }
640
641 /**
642  * Call-back function used by the XML parser.
643  */
644 function aggregator_element_data($parser, $data) {
645   global $channel, $element, $items, $item, $image, $tag;
646
647   switch ($element) {
648     case 'ITEM':
649       $items[$item][$tag] .= $data;
650       break;
651     case 'IMAGE':
652     case 'LOGO':
653       $image[$tag] .= $data;
654       break;
655     case 'LINK':
656       if ($data) {
657         $items[$item][$tag] .= $data;
658       }
659       break;
660     case 'CONTENT':
661       $items[$item]['CONTENT'] .= $data;
662       break;
663     case 'SUMMARY':
664       $items[$item]['SUMMARY'] .= $data;
665       break;
666     case 'TAGLINE':
667     case 'SUBTITLE':
668       $channel['DESCRIPTION'] .= $data;
669       break;
670     case 'INFO':
671     case 'ID':
672     case 'TEXTINPUT':
673       // The sub-element is not supported. However, we must recognize
674       // it or its contents will end up in the item array.
675       break;
676     default:
677       $channel[$tag] .= $data;
678   }
679 }
680
681 /**
682  * Checks a news feed for new items.
683  */
684 function aggregator_refresh($feed) {
685   global $channel, $image;
686
687   // Generate conditional GET headers.
688   $headers = array();
689   if ($feed['etag']) {
690     $headers['If-None-Match'] = $feed['etag'];
691   }
692   if ($feed['modified']) {
693     $headers['If-Modified-Since'] = gmdate('D, d M Y H:i:s', $feed['modified']) .' GMT';
694   }
695
696   // Request feed.
697   $result = drupal_http_request($feed['url'], $headers);
698
699   // Process HTTP response code.
700   switch ($result->code) {
701     case 304:
702       db_query('UPDATE {aggregator_feed} SET checked = %d WHERE fid = %d', time(), $feed['fid']);
703       drupal_set_message(t('There is no new syndicated content from %site.', array('%site' => theme('placeholder', $feed['title']))));
704       break;
705     case 301:
706       $feed['url'] = $result->redirect_url;
707       watchdog('aggregator', t('Updated URL for feed %title to %url.', array('%title' => theme('placeholder', $feed['title']), '%url' => theme('placeholder', $feed['url']))));
708
709     case 200:
710     case 302:
711     case 307:
712       // Filter the input data:
713      if (aggregator_parse_feed($result->data, $feed)) {
714
715         if ($result->headers['Last-Modified']) {
716           $modified = strtotime($result->headers['Last-Modified']);
717         }
718
719         /*
720         ** Prepare the channel data:
721         */
722
723         foreach ($channel as $key => $value) {
724           $channel[$key] = trim($value);
725         }
726
727         /*
728         ** Prepare the image data (if any):
729         */
730
731         foreach ($image as $key => $value) {
732           $image[$key] = trim($value);
733         }
734
735         if ($image['LINK'] && $image['URL'] && $image['TITLE']) {
736           // 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
737           $image = '<a href="'. check_url($image['LINK']) .'" class="feed-image"><img src="'. check_url($image['URL']) .'" alt="'. check_plain($image['TITLE']) .'" /></a>';
738         }
739         else {
740           $image = NULL;
741         }
742
743         /*
744         ** Update the feed data:
745         */
746
747         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']);
748
749         /*
750         ** Clear the cache:
751         */
752
753         cache_clear_all();
754
755         watchdog('aggregator', t('There is new syndicated content from %site.', array('%site' => theme('placeholder', $feed['title']))));
756         drupal_set_message(t('There is new syndicated content from %site.', array('%site' => theme('placeholder', $feed['title']))));
757       }
758       break;
759     default:
760       watchdog('aggregator', t('The RSS-feed from %site seems to be broken, due to "%error".', array('%site' => theme('placeholder', $feed['title']), '%error' => theme('placeholder', $result->code .' '. $result->error))), WATCHDOG_WARNING);
761       drupal_set_message(t('The RSS-feed from %site seems to be broken, because of error "%error".', array('%site' => theme('placeholder', $feed['title']), '%error' => theme('placeholder', $result->code .' '. $result->error))));
762   }
763 }
764
765 /**
766  * Parse the W3C date/time format, a subset of ISO 8601. PHP date parsing
767  * functions do not handle this format.
768  * See http://www.w3.org/TR/NOTE-datetime for more information.
769  * Originally from MagpieRSS (http://magpierss.sourceforge.net/).
770  *
771  * @param $date_str A string with a potentially W3C DTF date.
772  * @return A timestamp if parsed successfully or -1 if not.
773  */
774 function aggregator_parse_w3cdtf($date_str) {
775   if (preg_match('/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/', $date_str, $match)) {
776     list($year, $month, $day, $hours, $minutes, $seconds) = array($match[1], $match[2], $match[3], $match[4], $match[5], $match[6]);
777     // calc epoch for current date assuming GMT
778     $epoch = gmmktime($hours, $minutes, $seconds, $month, $day, $year);
779     if ($match[10] != 'Z') { // Z is zulu time, aka GMT
780       list($tz_mod, $tz_hour, $tz_min) = array($match[8], $match[9], $match[10]);
781       // zero out the variables
782       if (!$tz_hour) {
783         $tz_hour = 0;
784       }
785       if (!$tz_min) {
786         $tz_min = 0;
787       }
788       $offset_secs = (($tz_hour * 60) + $tz_min) * 60;
789       // is timezone ahead of GMT?  then subtract offset
790       if ($tz_mod == '+') {
791         $offset_secs *= -1;
792       }
793       $epoch += $offset_secs;
794     }
795     return $epoch;
796   }
797   else {
798     return FALSE;
799   }
800 }
801
802 function aggregator_parse_feed(&$data, $feed) {
803   global $items, $image, $channel;
804
805   // Unset the global variables before we use them:
806   unset($GLOBALS['element'], $GLOBALS['item'], $GLOBALS['tag']);
807   $items = array();
808   $image = array();
809   $channel = array();
810
811   // parse the data:
812   $xml_parser = drupal_xml_parser_create($data);
813   xml_set_element_handler($xml_parser, 'aggregator_element_start', 'aggregator_element_end');
814   xml_set_character_data_handler($xml_parser, 'aggregator_element_data');
815
816   if (!xml_parse($xml_parser, $data, 1)) {
817     watchdog('aggregator', t('The RSS-feed from %site seems to be broken, due to an error "%error" on line %line.', array('%site' => theme('placeholder', $feed['title']), '%error' => xml_error_string(xml_get_error_code($xml_parser)), '%line' => xml_get_current_line_number($xml_parser))), WATCHDOG_WARNING);
818     drupal_set_message(t('The RSS-feed from %site seems to be broken, because of error "%error" on line %line.', array('%site' => theme('placeholder', $feed['title']), '%error' => xml_error_string(xml_get_error_code($xml_parser)), '%line' => xml_get_current_line_number($xml_parser))), 'error');
819     return 0;
820   }
821   xml_parser_free($xml_parser);
822
823   /*
824   ** We reverse the array such that we store the first item last,
825   ** and the last item first.  In the database, the newest item
826   ** should be at the top.
827   */
828
829   $items = array_reverse($items);
830
831   foreach ($items as $item) {
832     unset($title, $link, $author, $description);
833
834     // Prepare the item:
835     foreach ($item as $key => $value) {
836       $item[$key] = trim($value);
837     }
838
839     /*
840     ** Resolve the item's title.  If no title is found, we use
841     ** up to 40 characters of the description ending at a word
842     ** boundary but not splitting potential entities.
843     */
844
845     if ($item['TITLE']) {
846       $title = $item['TITLE'];
847     }
848     else {
849       $title = preg_replace('/^(.*)[^\w;&].*?$/', "\\1", truncate_utf8($item['DESCRIPTION'], 40));
850     }
851
852     /*
853     ** Resolve the items link.
854     */
855
856     if ($item['LINK']) {
857       $link = $item['LINK'];
858     }
859     elseif ($item['GUID'] && (strncmp($item['GUID'], 'http://', 7) == 0)) {
860       $link = $item['GUID'];
861     }
862     else {
863       $link = $feed['link'];
864     }
865
866     /**
867      * Atom feeds have a CONTENT and/or SUMMARY tag instead of a DESCRIPTION tag
868      */
869     if ($item['CONTENT:ENCODED']) {
870       $item['DESCRIPTION'] = $item['CONTENT:ENCODED'];
871     }
872     else if ($item['SUMMARY']) {
873       $item['DESCRIPTION'] = $item['SUMMARY'];
874     }
875
876     /*
877     ** Try to resolve and parse the item's publication date.  If no
878     ** date is found, we use the current date instead.
879     */
880
881     if ($item['PUBDATE']) $date = $item['PUBDATE'];                        // RSS 2.0
882     else if ($item['DC:DATE']) $date = $item['DC:DATE'];                   // Dublin core
883     else if ($item['DCTERMS:ISSUED']) $date = $item['DCTERMS:ISSUED'];     // Dublin core
884     else if ($item['DCTERMS:CREATED']) $date = $item['DCTERMS:CREATED'];   // Dublin core
885     else if ($item['DCTERMS:MODIFIED']) $date = $item['DCTERMS:MODIFIED']; // Dublin core
886     else if ($item['ISSUED']) $date = $item['ISSUED'];                     // Atom XML
887     else if ($item['CREATED']) $date = $item['CREATED'];                   // Atom XML
888     else if ($item['MODIFIED']) $date = $item['MODIFIED'];                 // Atom XML
889     else $date = 'now';
890
891     $timestamp = strtotime($date); // As of PHP 5.1.0, strtotime returns FALSE on failure instead of -1.
892     if ($timestamp <= 0) {
893       $timestamp = aggregator_parse_w3cdtf($date); // Returns FALSE on failure
894       if (!$timestamp) {
895         $timestamp = time(); // better than nothing
896       }
897     }
898
899     /*
900     ** Save this item.  Try to avoid duplicate entries as much as
901     ** possible.  If we find a duplicate entry, we resolve it and
902     ** pass along it's ID such that we can update it if needed.
903     */
904
905     if ($link && $link != $feed['link'] && $link != $feed['url']) {
906       $entry = db_fetch_object(db_query("SELECT iid FROM {aggregator_item} WHERE fid = %d AND link = '%s'", $feed['fid'], $link));
907     }
908     else {
909       $entry = db_fetch_object(db_query("SELECT iid FROM {aggregator_item} WHERE fid = %d AND title = '%s'", $feed['fid'], $title));
910     }
911
912     aggregator_save_item(array('iid' => $entry->iid, 'fid' => $feed['fid'], 'timestamp' => $timestamp, 'title' => $title, 'link' => $link, 'author' => $item['AUTHOR'], 'description' => $item['DESCRIPTION']));
913   }
914
915   /*
916   ** Remove all items that are older than flush item timer:
917   */
918
919   $age = time() - variable_get('aggregator_clear', 9676800);
920   $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = %d AND timestamp < %d', $feed['fid'], $age);
921
922   if (db_num_rows($result)) {
923     $items = array();
924     while ($item = db_fetch_object($result)) {
925       $items[] = $item->iid;
926     }
927     db_query('DELETE FROM {aggregator_category_item} WHERE iid IN ('. implode(', ', $items) .')');
928     db_query('DELETE FROM {aggregator_item} WHERE fid = %d AND timestamp < %d', $feed['fid'], $age);
929   }
930
931   return 1;
932 }
933
934 function aggregator_save_item($edit) {
935   if ($edit['iid'] && $edit['title']) {
936     db_query("UPDATE {aggregator_item} SET title = '%s', link = '%s', author = '%s', description = '%s' WHERE iid = %d", $edit['title'], $edit['link'], $edit['author'], $edit['description'], $edit['iid']);
937   }
938   else if ($edit['iid']) {
939     db_query('DELETE FROM {aggregator_item} WHERE iid = %d', $edit['iid']);
940     db_query('DELETE FROM {aggregator_category_item} WHERE iid = %d', $edit['iid']);
941   }
942   else if ($edit['title'] && $edit['link']) {
943     $edit['iid'] = db_next_id('{aggregator_item}_iid');
944     db_query("INSERT INTO {aggregator_item} (iid, fid, title, link, author, description, timestamp) VALUES (%d, %d, '%s', '%s', '%s', '%s', %d)", $edit['iid'], $edit['fid'], $edit['title'], $edit['link'], $edit['author'], $edit['description'], $edit['timestamp']);
945     // file the items in the categories indicated by the feed
946     $categories = db_query('SELECT cid FROM {aggregator_category_feed} WHERE fid = %d', $edit['fid']);
947     while ($category = db_fetch_object($categories)) {
948       db_query('INSERT INTO {aggregator_category_item} (cid, iid) VALUES (%d, %d)', $category->cid, $edit['iid']);
949     }
950   }
951 }
952
953 function aggregator_get_feed($fid) {
954   return db_fetch_array(db_query('SELECT * FROM {aggregator_feed} WHERE fid = %d', $fid));
955 }
956
957 function aggregator_get_category($cid) {
958   return db_fetch_array(db_query('SELECT * FROM {aggregator_category} WHERE cid = %d', $cid));
959 }
960
961 function aggregator_view() {
962   $result = db_query('SELECT f.*, COUNT(i.iid) AS items FROM {aggregator_feed} f LEFT JOIN {aggregator_item} i ON f.fid = i.fid GROUP BY f.fid, f.title, f.url, f.refresh, f.checked, f.link, f.description, f.etag, f.modified, f.image, f.block ORDER BY f.title');
963
964   $output .= '<h3>'. t('Feed overview') .'</h3>';
965
966   $header = array(t('Title'), t('Items'), t('Last update'), t('Next update'), array('data' => t('Operations'), 'colspan' => '3'));
967   $rows = array();
968   while ($feed = db_fetch_object($result)) {
969     $rows[] = array(l($feed->title, "aggregator/sources/$feed->fid"), format_plural($feed->items, '1 item', '%count items'), ($feed->checked ? t('%time ago', array('%time' => format_interval(time() - $feed->checked))) : t('never')), ($feed->checked ? t('%time left', array('%time' => format_interval($feed->checked + $feed->refresh - time()))) : t('never')), l(t('edit'), "admin/aggregator/edit/feed/$feed->fid"), l(t('remove items'), "admin/aggregator/remove/$feed->fid"), l(t('update items'), "admin/aggregator/update/$feed->fid"));
970   }
971   $output .= theme('table', $header, $rows);
972
973   $result = db_query('SELECT c.cid, c.title, count(ci.iid) as items FROM {aggregator_category} c LEFT JOIN {aggregator_category_item} ci ON c.cid = ci.cid GROUP BY c.cid, c.title ORDER BY title');
974
975   $output .= '<h3>'. t('Category overview') .'</h3>';
976
977   $header = array(t('Title'), t('Items'), t('Operations'));
978   $rows = array();
979   while ($category = db_fetch_object($result)) {
980     $rows[] = array(l($category->title, "aggregator/categories/$category->cid"), format_plural($category->items, '1 item', '%count items'), l(t('edit'), "admin/aggregator/edit/category/$category->cid"));
981   }
982   $output .= theme('table', $header, $rows);
983
984   return $output;
985 }
986
987 /**
988  * Menu callback; removes all items from a feed, then redirects to the overview page.
989  */
990 function aggregator_admin_remove_feed($feed) {
991   aggregator_remove(aggregator_get_feed($feed));
992   drupal_goto('admin/aggregator');
993 }
994
995 /**
996  * Menu callback; refreshes a feed, then redirects to the overview page.
997  */
998 function aggregator_admin_refresh_feed($feed) {
999   aggregator_refresh(aggregator_get_feed($feed));
1000   drupal_goto('admin/aggregator');
1001 }
1002
1003 /**
1004  * Menu callback; displays the aggregator administration page.
1005  */
1006 function aggregator_admin_overview() {
1007   return aggregator_view();
1008 }
1009
1010 /**
1011  * Menu callback; displays the most recent items gathered from any feed.
1012  */
1013 function aggregator_page_last() {
1014   return _aggregator_page_list('SELECT i.*, f.title AS ftitle, f.link AS flink FROM {aggregator_item} i INNER JOIN {aggregator_feed} f ON i.fid = f.fid ORDER BY i.timestamp DESC, i.iid DESC', arg(1));
1015 }
1016
1017 /**
1018  * Menu callback; displays all the items captured from a particular feed.
1019  */
1020 function aggregator_page_source() {
1021   $feed = db_fetch_object(db_query('SELECT * FROM {aggregator_feed} WHERE fid = %d', arg(2)));
1022   $info = theme('aggregator_feed', $feed);
1023
1024   return _aggregator_page_list('SELECT * FROM {aggregator_item} WHERE fid = '. $feed->fid .' ORDER BY timestamp DESC, iid DESC', arg(3), $info);
1025 }
1026
1027 /**
1028  * Menu callback; displays all the items aggregated in a particular category.
1029  */
1030 function aggregator_page_category() {
1031   $category = db_fetch_object(db_query('SELECT cid, title FROM {aggregator_category} WHERE cid = %d', arg(2)));
1032
1033   return _aggregator_page_list('SELECT i.*, f.title AS ftitle, f.link AS flink FROM {aggregator_category_item} c LEFT JOIN {aggregator_item} i ON c.iid = i.iid LEFT JOIN {aggregator_feed} f ON i.fid = f.fid WHERE cid = '. $category->cid .' ORDER BY timestamp DESC, iid DESC', arg(3));
1034 }
1035
1036 /**
1037  * Prints an aggregator page listing a number of feed items. Various
1038  * menu callbacks use this function to print their feeds.
1039  */
1040 function _aggregator_page_list($sql, $op, $header = '') {
1041   $categorize = (user_access('administer news feeds') && ($op == 'categorize'));
1042
1043   $output = '<div id="aggregator">';
1044
1045   $form['header'] = array('#value' => $header);
1046   $output .= $form['header']['#value'];
1047
1048   $result = pager_query($sql, 20);
1049   $categories = array();
1050   while ($item = db_fetch_object($result)) {
1051     $form['items'][$item->iid] = array('#value' => theme('aggregator_page_item', $item));
1052     $output .= $form['items'][$item->iid]['#value'];
1053     $form['categories'][$item->iid] = array();
1054
1055     if ($categorize) {
1056
1057       $categories_result = db_query('SELECT c.cid, c.title, ci.iid FROM {aggregator_category} c LEFT JOIN {aggregator_category_item} ci ON c.cid = ci.cid AND ci.iid = %d', $item->iid);
1058       $selected = array();
1059       while ($category = db_fetch_object($categories_result)) {
1060         if (!$done) {
1061           $categories[$category->cid] = check_plain($category->title);
1062         }
1063         if ($category->iid) {
1064           $selected[] = $category->cid;
1065         }
1066       }
1067       $done = true;
1068       $form['categories'][$item->iid] = array(
1069         '#type' => variable_get('aggregator_category_selector', 'checkboxes'),
1070         '#default_value' => $selected, '#options' => $categories,
1071         '#size' => 10, '#multiple' => true
1072       );
1073     }
1074   }
1075   $output .= '</div>';
1076   $form['submit'] = array('#type' => 'submit', '#value' => t('Save categories'));
1077   $form['pager'] = array('#value' => theme('pager', NULL, 20, 0));
1078   $output .= $form['pager']['#value'];
1079
1080   // arg(1) is undefined if we are at the top aggregator URL
1081   // is there a better way to do this?
1082   if (!arg(1)) {
1083     $form['feed_icon'] = array('#value' => theme('feed_icon', url('aggregator/rss')));
1084   }
1085   elseif (arg(1) == 'categories' && arg(2) && !arg(3)) {
1086     $form['feed_icon'] = array('#value' => theme('feed_icon', url('aggregator/rss/' . arg(2))));
1087   }
1088   $output .= $form['feed_icon']['#value'];
1089
1090   return ($categorize) ? drupal_get_form('aggregator_page_list', $form) : $output;
1091 }
1092
1093 function theme_aggregator_page_list($form) {
1094   $output = '<div id="aggregator">';
1095   $output .= form_render($form['header']);
1096   $rows = array();
1097   if ($form['items']) {
1098     foreach (element_children($form['items']) as $key) {
1099       if (is_array($form['items'][$key])) {
1100         $rows[] = array(form_render($form['items'][$key]), array('data' => form_render($form['categories'][$key]), 'class' => 'categorize-item'));
1101       }
1102     }
1103   }
1104   $output .= theme('table', array('', t('Categorize')), $rows);
1105   $output .= form_render($form['submit']);
1106   $output .= '</div>';
1107   $output .= form_render($form);
1108   return $output;
1109 }
1110
1111 function aggregator_page_list_validate($form_id, &$form) {
1112   if (!user_access('administer news feeds')) {
1113     form_error($form, t('You are not allowed to categorize this feed item.'));
1114   }
1115 }
1116
1117 function aggregator_page_list_submit($form_id, $form_values) {
1118   foreach ($form_values as $iid => $selection) {
1119     db_query('DELETE FROM {aggregator_category_item} WHERE iid = %d', $iid);
1120     foreach ($selection as $cid) {
1121       if ($cid) {
1122         db_query('INSERT INTO {aggregator_category_item} (cid, iid) VALUES (%d, %d)', $cid, $iid);
1123       }
1124     }
1125   }
1126   drupal_set_message(t('The categories have been saved.'));
1127 }
1128
1129 /**
1130  * Menu callback; displays all the feeds used by the aggregator.
1131  */
1132 function aggregator_page_sources() {
1133   $result = db_query('SELECT f.fid, f.title, f.description, f.image, MAX(i.timestamp) AS last FROM {aggregator_feed} f LEFT JOIN {aggregator_item} i ON f.fid = i.fid GROUP BY f.fid, f.title, f.description, f.image ORDER BY last DESC, f.title');
1134   $output = "<div id=\"aggregator\">\n";
1135   while ($feed = db_fetch_object($result)) {
1136     $output .= '<h2>'. check_plain($feed->title) ."</h2>\n";
1137
1138     // Most recent items:
1139     $list = array();
1140     if (variable_get('aggregator_summary_items', 3)) {
1141       $items = db_query_range('SELECT i.title, i.timestamp, i.link FROM {aggregator_item} i WHERE i.fid = %d ORDER BY i.timestamp DESC', $feed->fid, 0, variable_get('aggregator_summary_items', 3));
1142       while ($item = db_fetch_object($items)) {
1143         $list[] = theme('aggregator_summary_item', $item);
1144       }
1145     }
1146     $output .= theme('item_list', $list);
1147     $output .= '<div class="links">'. theme('links', array(l(t('more'), 'aggregator/sources/'. $feed->fid))) ."</div>\n";
1148   }
1149   $output .= theme('xml_icon', url('aggregator/opml'));
1150   $output .= '</div>';
1151   return $output;
1152 }
1153
1154 /**
1155  * Menu callback; generate an RSS 0.92 feed of aggregator items or categories.
1156  */
1157 function aggregator_page_rss() {
1158   // arg(2) is the passed cid, only select for that category
1159   $result = NULL;
1160   if (arg(2)) {
1161     $category = db_fetch_object(db_query('SELECT cid, title FROM {aggregator_category} WHERE cid = %d', arg(2)));
1162     $url = '/categories/' . $category->cid;
1163     $title = ' ' . t('in category') . ' ' . $category->title;
1164     $sql = 'SELECT i.*, f.title AS ftitle, f.link AS flink FROM {aggregator_category_item} c LEFT JOIN {aggregator_item} i ON c.iid = i.iid LEFT JOIN {aggregator_feed} f ON i.fid = f.fid WHERE cid = %d ORDER BY timestamp DESC, iid DESC';
1165     $result = db_query_range($sql, $category->cid, 0, variable_get('feed_default_items', 10));
1166   }
1167   // or, get the default aggregator items
1168   else {
1169     $sql = 'SELECT i.*, f.title AS ftitle, f.link AS flink FROM {aggregator_item} i INNER JOIN {aggregator_feed} f ON i.fid = f.fid ORDER BY i.timestamp DESC, i.iid DESC';
1170     $result = db_query_range($sql, 0, variable_get('feed_default_items', 10));
1171   }
1172
1173   while ($item = db_fetch_object($result)) {
1174     switch (variable_get('feed_item_length', 'teaser')) {
1175       case 'teaser':
1176         $teaser = node_teaser($item->description);
1177         if ($teaser != $item->description) {
1178           $teaser .= '<p><a href="'. check_url($item->link) .'">'. t('read more') ."</a></p>\n";
1179         }
1180         $item->description = $teaser;
1181         break;
1182       case 'title':
1183         $item->description = '';
1184         break;
1185     }
1186     $items .= format_rss_item($item->ftitle . ': ' . $item->title, $item->link, $item->description, array('pubDate' => date('r', $item->timestamp)));
1187   }
1188
1189   $output .= "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
1190   $output .= "<rss version=\"2.0\">\n";
1191   $output .= format_rss_channel(variable_get('site_name', t('Drupal')) . ' ' . t('aggregator'), url('aggregator' . $url, NULL, NULL, TRUE), variable_get('site_name', t('Drupal')) . ' - ' . t('aggregated feeds') . $title, $items, 'en');
1192   $output .= "</rss>\n";
1193
1194   drupal_set_header('Content-Type: application/rss+xml; charset=utf-8');
1195   print $output;
1196 }
1197
1198 /**
1199  * Menu callback; generates an OPML representation of all feeds.
1200  */
1201 function aggregator_page_opml($cid = NULL) {
1202   if ($cid) {
1203     $result = db_query('SELECT f.title, f.url FROM {aggregator_feed} f LEFT JOIN {aggregator_category_feed} c on f.fid = c.fid WHERE c.cid = %d ORDER BY title', $cid);
1204   }
1205   else {
1206     $result = db_query('SELECT * FROM {aggregator_feed} ORDER BY title');
1207   }
1208
1209   $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
1210   $output .= "<opml version=\"1.1\">\n";
1211   $output .= "<head>\n";
1212   $output .= '<title>'. check_plain(variable_get('site_name', 'Drupal')) ."</title>\n";
1213   $output .= '<dateModified>'. gmdate('r') ."</dateModified>\n";
1214   $output .= "</head>\n";
1215   $output .= "<body>\n";
1216
1217   while ($feed = db_fetch_object($result)) {
1218     $output .= '<outline text="'. check_plain($feed->title) .'" xmlUrl="'. check_url($feed->url) ."\" />\n";
1219   }
1220
1221   $output .= "</body>\n";
1222   $output .= "</opml>\n";
1223
1224   drupal_set_header('Content-Type: text/xml; charset=utf-8');
1225   print $output;
1226 }
1227
1228 /**
1229  * Menu callback; displays all the categories used by the aggregator.
1230  */
1231 function aggregator_page_categories() {
1232   $result = db_query('SELECT c.cid, c.title, c.description FROM {aggregator_category} c LEFT JOIN {aggregator_category_item} ci ON c.cid = ci.cid LEFT JOIN {aggregator_item} i ON ci.iid = i.iid GROUP BY c.cid, c.title, c.description');
1233   $output = "<div id=\"aggregator\">\n";
1234
1235   while ($category = db_fetch_object($result)) {
1236     $output .= '<h2>'. check_plain($category->title) ."</h2>\n";
1237     if (variable_get('aggregator_summary_items', 3)) {
1238       $list = array();
1239       $items = db_query_range('SELECT i.title, i.timestamp, i.link, f.title as feed_title, f.link as feed_link FROM {aggregator_category_item} ci LEFT JOIN {aggregator_item} i ON i.iid = ci.iid LEFT JOIN {aggregator_feed} f ON i.fid = f.fid WHERE ci.cid = %d ORDER BY i.timestamp DESC', $category->cid, 0, variable_get('aggregator_summary_items', 3));
1240       while ($item = db_fetch_object($items)) {
1241         $list[] = theme('aggregator_summary_item', $item);
1242       }
1243       $output .= theme('item_list', $list);
1244     }
1245     $output .= '<div class="links">'. theme('links', array(l(t('more'), 'aggregator/categories/'. $category->cid))) ."</div>\n";
1246   }
1247   $output .= '</div>';
1248
1249   return $output;
1250 }
1251
1252 /**
1253  * Format a news feed.
1254  *
1255  * @ingroup themeable
1256  */
1257 function theme_aggregator_feed($feed) {
1258   $output  = '<div class="feed-source">';
1259   $output .= theme('feed_icon', $feed->url) ."\n";
1260   $output .= $feed->image;
1261   $output .= '<div class="feed-description">'. aggregator_filter_xss($feed->description) ."</div>\n";
1262   $output .= '<div class="feed-url"><em>'. t('URL:') .'</em> '. l($feed->link, $feed->link, array(), NULL, NULL, TRUE) ."</div>\n";
1263
1264   if ($feed->checked) {
1265     $updated = t('%time ago', array('%time' => format_interval(time() - $feed->checked)));
1266   }
1267   else {
1268     $updated = t('never');
1269   }
1270
1271   if (user_access('administer news feeds')) {
1272     $updated = l($updated, 'admin/aggregator');
1273   }
1274
1275   $output .= '<div class="feed-updated"><em>'. t('Updated:') . "</em> $updated</div>";
1276   $output .= "</div>\n";
1277
1278   return $output;
1279 }
1280
1281 /**
1282  * Format an individual feed item for display in the block.
1283  *
1284  * @ingroup themeable
1285  */
1286 function theme_aggregator_block_item($item, $feed = 0) {
1287   global $user;
1288
1289   if ($user->uid && module_exist('blog') && user_access('edit own blog')) {
1290     if ($image = theme('image', 'misc/blog.png', t('blog it'), t('blog it'))) {
1291       $output .= '<div class="icon">'. l($image, 'node/add/blog', array('title' => t('Comment on this news item in your personal blog.'), 'class' => 'blog-it'), "iid=$item->iid", NULL, FALSE, TRUE) .'</div>';
1292     }
1293   }
1294
1295   // Display the external link to the item.
1296   $output .= '<a href="'. check_url($item->link) .'">'. check_plain($item->title) ."</a>\n";
1297
1298   return $output;
1299 }
1300
1301 /**
1302  * Return a themed item heading for summary pages located at "aggregator/sources"
1303  * and "aggregator/categories".
1304  *
1305  * @param $item The item object from the aggregator module.
1306  * @return A string containing the output.
1307  *
1308  * @ingroup themeable
1309  */
1310 function theme_aggregator_summary_item($item) {
1311   $output = '<a href="'. check_url($item->link) .'">'. check_plain($item->title) .'</a> <span class="age">'. t('%age old', array('%age' => format_interval(time() - $item->timestamp))) .'</span>';
1312   if ($item->feed_link) {
1313     $output .= ', <span class="source"><a href="'. check_url($item->feed_link) .'">'. check_plain($item->feed_title) .'</a></span>';
1314   }
1315   return $output ."\n";
1316 }
1317
1318 /**
1319  * Format an individual feed item for display on the aggregator page.
1320  *
1321  * @ingroup themeable
1322  */
1323 function theme_aggregator_page_item($item) {
1324
1325   $source = '';
1326   if ($item->ftitle && $item->fid) {
1327     $source = l($item->ftitle, "aggregator/sources/$item->fid", array('class' => 'feed-item-source')) . ' -';
1328   }
1329
1330   if (date('Ymd', $item->timestamp) == date('Ymd')) {
1331     $source_date = t('%ago ago', array('%ago' => format_interval(time() - $item->timestamp)));
1332   }
1333   else {
1334     $source_date = format_date($item->timestamp, 'custom', variable_get('date_format_medium', 'D, Y-m-d H:i'));
1335   }
1336
1337   $output .= "<div class=\"feed-item\">\n";
1338   $output .= '<h3 class="feed-item-title"><a href="'. check_url($item->link) .'">'. check_plain($item->title) ."</a></h3>\n";
1339   $output .= "<div class=\"feed-item-meta\">$source <span class=\"feed-item-date\">$source_date</span></div>\n";
1340
1341   if ($item->description) {
1342     $output .= '<div class="feed-item-body">'. aggregator_filter_xss($item->description) ."</div>\n";
1343   }
1344
1345   $result = db_query('SELECT c.title, c.cid FROM {aggregator_category_item} ci LEFT JOIN {aggregator_category} c ON ci.cid = c.cid WHERE ci.iid = %d ORDER BY c.title', $item->iid);
1346   $categories = array();
1347   while ($category = db_fetch_object($result)) {
1348     $categories[] = l($category->title, 'aggregator/categories/'. $category->cid);
1349   }
1350   if ($categories) {
1351     $output .= '<div class="feed-item-categories">'. t('Categories') .': '. implode(', ', $categories) ."</div>\n";
1352   }
1353
1354   $output .= "</div>\n";
1355
1356   return $output;
1357 }
1358
1359 /**
1360  * Safely render HTML content, as allowed.
1361  */
1362 function aggregator_filter_xss($value) {
1363   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));
1364 }
1365
1366 /**
1367  * Helper function for drupal_map_assoc.
1368  */
1369 function _aggregator_items($count) {
1370   return format_plural($count, '1 item', '%count items');
1371 }