/[drupal]/contributions/modules/planet/planet.module
ViewVC logotype

Diff of /contributions/modules/planet/planet.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph | View Patch Patch

revision 1.6 by daryl, Fri Jun 15 17:28:29 2007 UTC revision 1.7 by swe3tdave, Wed Mar 11 23:15:34 2009 UTC
# Line 1  Line 1 
1  <?php  <?php
2    // $Id: planet.install Exp $
3    
4  define('PLANET_ADMIN', 'administer planet');  /**
5     * @file
6     * The planet module
7     *
8     */
9    
10  function planet_node_info() {  function planet_node_info() {
11    return array(    return array(
12      'planet' => array(      'planet' => array(
13        'name' => t('Planet Entry'),      'name' => t('Planet Entry'),
14        'module' => 'planet',      'module' => 'planet',
15        'description' => t('Node to contain posts aggregated from various blogs.'),      'description' => t('Node to contain posts aggregated from various blogs.'),
16      )      )
17    );    );
18  }  }
19    
20    /**
21     * Implementation of hook_perm.
22     */
23  function planet_perm() {  function planet_perm() {
24          return array(PLANET_ADMIN);    return array('administer planet', 'administer own planet feeds');
25  }  }
26    
27  function planet_help($section){  function planet_help($path, $arg) {
28          switch($section){    switch ($path) {
29                  case 'admin/help/planet':      case 'admin/help/planet':
30                          $output = '<p>Planet is an aggregator that allows you to aggregate the blogs for users in a given role (e.g. staff) and associate content with the users rather than as a detached feed. This provides the benefit of showing avatars with content, providing per-user aggregation of planet content in addition to blog content, etc.</p>';        $output = '<p>Planet is an aggregator that allows you to aggregate the blogs for users in a given role (e.g. staff) and associate content with the users rather than as a detached feed. This provides the benefit of showing avatars with content, providing per-user aggregation of planet content in addition to blog content, etc.</p>';
31                          $output .= '<p>To use planet, go to admin/settings/planet and note the following sections:</p>';        $output .= '<p>To use planet, go to admin/settings/planet and note the following sections:</p>';
32                          $output .= '<ul>';        $output .= '<ul>';
33                          $output .= '<li><strong>Recent Items</strong>. This is a queue of items that have recently been pulled into the site. The convert column allows you to turn them into bona fide blog posts. This is useful if you want to feature blog posts front and center and keep planet as a secondary content view. Conversion allows you to float site-relevant content to the mainstream while providing a view of more general content from your members.</li>';        $output .= '<li><strong>General Settings</strong>. The role to select bloggers from lets you narrow the user list for when you\'re adding a feed and associating it with a user. A common setting will be to create a staff role and use this for planet.</li>';
34                          $output .= '<li><strong>General Settings</strong>. The auto-publish value is a string that the module looks for in categories (if possible) or within a post itself. Posts that include the value will be auto-converted into blog entries. The role to select bloggers from lets you narrow the user list for when you\'re adding a feed and associating it with a user. A common setting will be to create a staff role and use this for planet.</li>';        $output .= '<li><strong>Feeds</strong>. This section lets you add a new feed. Give it a title, select an author, provide the feed url, and you\'re off. You\'ll have to manually refresh it or wait for a cron run for items to be imported.</li>';
35                          $output .= '<li><strong>Feeds</strong>. This section lets you add a new feed. Give it a title, select an author, provide the feed url, and you\'re off. You\'ll have to manually refresh it or wait for a cron run for items to be imported.</li>';        $output .= '<li><strong>Feeds</strong>. This section lists current feeds, when they were last updated, how many items they have, and it allows you to edit, refresh, or freeze them. Freezing is a quick way to temporarily suspend updates from the given feed.</li>';
36                          $output .= '<li><strong>Feeds</strong>. This section lists current feeds, when they were last updated, how many items they have, and it allows you to edit, refresh, or freeze them. Freezing is a quick way to temporarily suspend updates from the given feed.</li>';        return $output;
37                          return $output;      case 'admin/modules#description':
38                  case 'admin/modules#description':        return t('Aggregates RSS feeds and faciliates their association with site users who belong to a given role.');
39                          return t('Aggregates RSS feeds and faciliates their association with site users who belong to a given role.');    }
         }  
40  }  }
41    
42  function planet_view($node, $teaser = FALSE, $page = FALSE, $links = TRUE){  function planet_view($node, $teaser = FALSE, $page = FALSE, $links = TRUE) {
43          if($page === true && variable_get('planet_redirect_page', 0) == 1){    if ($page === true && variable_get('planet_redirect_page', 0) == 1) {
44                  $obj = db_fetch_object(db_query('SELECT * FROM {planet_items} WHERE nid = %d', $node->nid));      $obj = db_fetch_object(db_query('SELECT * FROM {planet_items} WHERE nid = %d', $node->nid));
45                  if($obj->nid == $node->nid && $obj->link != ''){      if ($obj->nid == $node->nid && $obj->link != '') {
46                          header('Location: ' . $obj->link);        header('Location: '. $obj->link);
47                          exit;        exit;
48                  }      }
49          }    }
50          else{    else {
51                  return node_prepare($node, $teaser);      return node_prepare($node, $teaser);
52          }    }
53  }  }
54    
55  function planet_access($op, $node){  function planet_access($op, $node, $account) {
         global $user;  
56    
         if ($op == 'create') {  
                 return user_access('edit own blog') && $user->uid;  
         }  
57    
58          if ($op == 'update' || $op == 'delete') {    if ($op == 'create') {
59                  if (user_access('edit own blog') && ($user->uid == $node->uid) || user_access('administer nodes')) {      return user_access('edit own blog', $account) && $account->uid;
60                          return TRUE;    }
61                  }  
62          }    if ($op == 'update' || $op == 'delete') {
63        if (user_access('edit own blog', $account) && ($account->uid == $node->uid) || user_access('administer nodes', $account)) {
64          return TRUE;
65        }
66      }
67  }  }
68    
69  function planet_menu($may_cache){  function planet_menu() {
70         global $user;  
71          $items = array();    $items['admin/settings/planet'] = array(
72          if($may_cache){      'title' => 'Planet Settings',
73        'description' => 'Configure settings for the planet module.',
74          }      'page callback' => '_planet_settings',
75        'access arguments' => array('administer nodes'),
76          $items[] = array('path' => 'admin/settings/planet', 'title' => t('planet settings'),      'type' => MENU_NORMAL_ITEM);
77        'callback' => '_planet_settings', 'access' => user_access('administer nodes'),  
78        'type' => MENU_NORMAL_ITEM);    $items['user/%user/planet'] = array(
79        'title' => 'Planet Feeds',
80        'page callback' => 'planet_user_feeds',
81        'page arguments' => array(1),
82        'access arguments' => array('administer own planet feeds'),
83        'type' => MENU_LOCAL_TASK,
84      );
85    
86      //  if (arg(0) == 'planet' && is_numeric(arg(1))) {
87      $items['planet/'. '%'] = array(
88        'title' => 'planet',
89        'page callback' => 'planet_page_user',
90        'page arguments' => array(arg(1))
91      );
92    //  }
93    
94    //   if (arg(3) == 'refresh' && is_numeric(arg(4))) {
95    
96      $items['admin/settings/planet/refresh/%'] = array(
97        'title' => 'planet refresh',
98        'page callback' => 'planet_call_refresh',
99        'access arguments' => array('administer nodes'),
100        'type' => MENU_CALLBACK
101      );
102    //   }
103    
104      if(arg(0) == 'planet' && is_numeric(arg(1))){  //  if (is_numeric(arg(4)) && (arg(3) == 'freeze' || arg(3) == 'unfreeze')) {
105        $items[] = array('path' => 'planet/' . arg(1), 'title' => 'planet', 'callback' => 'planet_page_user', 'callback arguments' => array(arg(1)));    $items['admin/settings/planet/'. arg(3) .'/%'] = array(
106        'title' => 'planet freeze',
107        'page callback' => 'planet_toggle_frozen',
108        'access arguments' => array('administer nodes'),
109        'type' => MENU_CALLBACK
110      );
111    //   }
112    
113      $items['planet'] = array(
114        'title' => 'Planet',
115        'description' => 'Planet Page',
116        'page callback' => 'planet_page_last',
117        'access arguments' => array('access content'),
118        'type' => MENU_NORMAL_ITEM
119      );
120    
121      $items['planet/feed'] = array(
122        'title' => 'Planet',
123        'page callback' => 'planet_feed',
124        'access arguments' => array('access content'),
125        'type' => MENU_CALLBACK
126      );
127    
128      return $items;
129    }
130    
131    function planet_call_refresh() {
132      $title = planet_refresh();
133      watchdog('planet', 'Feed "'. $title .'" refreshed.');
134      drupal_set_message('Feed "'. $title .'" refreshed.');
135      drupal_goto('admin/settings/planet');
136    }
137    
138    function planet_toggle_frozen() {
139    
140      $fid = intval(arg(4));
141      db_query('UPDATE {planet_feeds} SET frozen = %d WHERE fid = %d', arg(3) == 'unfreeze' ? 0 : 1, $fid);
142      drupal_set_message('Feed '. (arg(3) == 'unfreeze' ? 'un' : '') .'frozen.');
143      drupal_goto('admin/settings/planet');
144    }
145    
146    
147    function planet_user_feeds() {
148    global $user;
149    if ($_POST) {
150        $edit = $_POST;
151        if ($_POST['op'] == 'Delete' && intval($edit['fid']) > 0) {
152          $result = db_query('SELECT nid FROM {planet_items} WHERE fid = %d', intval($edit['fid']));
153          while ($node = db_fetch_object($result)) {
154            $nodes[$node->nid] = TRUE;
155          }
156          return drupal_get_form('planet_multiple_delete_confirm', $nodes, intval($edit['fid']), 'user/'. $user->uid .'/planet');
157        }
158        else if ($_POST['op'] == 'Delete all' && $_POST['confirm'] == 1) {
159          $edit['fid'] = intval(arg(3));
160          $edit['redirect'] = 'user/'. $user->uid .'/planet';
161          return drupal_get_form('planet_multiple_delete_confirm_submit', $edit);
162        }
163        else {
164          if (isset($edit['fid']) && intval($edit['fid']) == 0) {
165            db_query('INSERT INTO {planet_feeds} (uid, title, link, image, checked, frozen) VALUES(%d, "%s", "%s", "%s", 0, 0)', $user->uid, $edit['title'], $edit['link'], $edit['image']);
166            $edit_r = db_fetch_array(db_query('SELECT fid FROM {planet_feeds} WHERE uid = %d AND title = "%s" AND link = "%s"', $user->uid, $edit['title'], $edit['link']));
167            $title = planet_refresh(intval($edit_r['fid']));
168            drupal_set_message('Added new feed: ' . $title);
169          }
170          else if ($edit['fid'] && intval($edit['fid']) > 0) {
171            db_query('UPDATE {planet_feeds} SET uid = %d, title="%s", link = "%s", image="%s" WHERE fid=%d', $user->uid, $edit['title'], $edit['link'], $edit['image'], $edit['fid']);
172            drupal_set_message('Edited "'. $edit['title'] .'" feed.');
173          }
174          else {
175            if ($edit['planet_author_roles']) {
176              variable_set('planet_author_roles', $edit['planet_author_roles']);
177            }
178            if ($edit['planet_filter_formats']) {
179              variable_set('planet_filter_formats', $edit['planet_filter_formats']);
180            }
181            if ($edit['planet_redirect_page'] == 1) {
182              variable_set('planet_redirect_page', $edit['planet_redirect_page']);
183            }
184            else {
185              variable_del('planet_redirect_page');
186            }
187            drupal_set_message('Edited general planet settings.');
188          }
189        }
190        drupal_goto('user/'. $user->uid .'/planet');
191      }
192      else {
193        $fid = intval(arg(3));
194        if ($fid > 0) {
195          $edit = db_fetch_array(db_query('SELECT * FROM {planet_feeds} WHERE fid = %d', $fid));
196          $output .= drupal_get_form('planet_feed_form', $edit, true, $user);
197      }      }
198        else {
199    
200          $output .= drupal_get_form('planet_feed_form', $edit, false, $user);
201    
202      if(arg(3) == 'refresh' && is_numeric(arg(4))){       // $result = db_query('SELECT *, (UNIX_TIMESTAMP(NOW()) - checked) _checked FROM {planet_feeds}');
203          $items[] = array('path' => 'admin/settings/planet/refresh/' . arg(4), 'title' => t('planet refresh'),        $result = db_query('SELECT COUNT(f.fid) cnt, f.*, (UNIX_TIMESTAMP(NOW()) - checked) _checked FROM {planet_feeds} f LEFT OUTER JOIN {planet_items} i ON i.fid = f.fid WHERE f.uid = %d GROUP BY f.fid;', $user->uid);
204                  'callback' => 'planet_call_refresh', 'access' => user_access('administer nodes'),        $rows = array();
205                  'type' => MENU_CALLBACK);        $headers = array('Feed', 'Items', 'Edit', 'Last checked');
206          while ($feed = db_fetch_object($result)) {
207            $checked = intval($feed->_checked / 60) .' minutes';
208            if ($feed->_checked % 60 > 0) {
209              $checked .= ', '. $feed->_checked % 60 .' seconds';
210            }
211            $checked .= ' ago';
212            array_push($rows, array(
213              $feed->title,
214              $feed->cnt,
215              l('edit', 'user/'. $user->uid .'/planet/'. intval($feed->fid)),
216              $checked,
217              )
218            );
219          }
220          $output .= '<h2>Feeds</h2>';
221          $output .= theme('table', $headers, $rows);
222      }      }
223        print theme('page', $output);
224      }
225    }
226    
227    
228    function _planet_settings() {
229      if ($_POST) {
230        $edit = $_POST;
231    
232      if(is_numeric(arg(4)) && (arg(3) == 'freeze' || arg(3) == 'unfreeze')){      if ($_POST['op'] == 'Delete' && intval($edit['fid']) > 0) {
233          $items[] = array('path' => 'admin/settings/planet/' . arg(3). '/' . arg(4), 'title' => t('planet freeze'),        $result = db_query('SELECT nid FROM {planet_items} WHERE fid = %d', intval($edit['fid']));
234                  'callback' => 'planet_toggle_frozen', 'access' => user_access('administer nodes'),        while ($node = db_fetch_object($result)) {
235                  'type' => MENU_CALLBACK);          $nodes[$node->nid] = TRUE;
236          }
237          return drupal_get_form('planet_multiple_delete_confirm', $nodes, intval($edit['fid']), 'admin/settings/planet');
238        }
239        else if ($_POST['op'] == 'Delete all' && $_POST['confirm'] == 1) {
240          $edit['fid'] = intval(arg(3));
241          $edit['redirect'] = 'admin/settings/planet';
242          return drupal_get_form('planet_multiple_delete_confirm_submit', $edit);
243        }
244        else {
245          if (isset($edit['fid']) && intval($edit['fid']) == 0) {
246            db_query('INSERT INTO {planet_feeds} (uid, title, link, image, checked, frozen) VALUES(%d, "%s", "%s", "%s", 0, 0)', $edit['uid'], $edit['title'], $edit['link'], $edit['image']);
247            $edit_r = db_fetch_array(db_query('SELECT fid FROM {planet_feeds} WHERE uid = %d AND title = "%s" AND link = "%s"', $edit['uid'], $edit['title'], $edit['link']));
248            $title = planet_refresh(intval($edit_r['fid']));
249            drupal_set_message('Added new feed: ' . $title);
250          }
251          else if ($edit['fid'] && intval($edit['fid']) > 0) {
252            db_query('UPDATE {planet_feeds} SET uid = %d, title="%s", link = "%s", image="%s" WHERE fid=%d', $edit['uid'], $edit['title'], $edit['link'], $edit['image'], $edit['fid']);
253            drupal_set_message('Edited "'. $edit['title'] .'" feed.');
254          }
255          else {
256            if ($edit['planet_author_roles']) {
257              variable_set('planet_author_roles', $edit['planet_author_roles']);
258            }
259            if ($edit['planet_filter_formats']) {
260              variable_set('planet_filter_formats', $edit['planet_filter_formats']);
261            }
262            if ($edit['planet_redirect_page'] == 1) {
263              variable_set('planet_redirect_page', $edit['planet_redirect_page']);
264            }
265            else {
266              variable_del('planet_redirect_page');
267            }
268            drupal_set_message('Edited general planet settings.');
269          }
270        }
271        drupal_goto('admin/settings/planet');
272      }
273      else {
274        $fid = intval(arg(3));
275        if ($fid > 0) {
276          $edit = db_fetch_array(db_query('SELECT * FROM {planet_feeds} WHERE fid = %d', $fid));
277          $output .= drupal_get_form('planet_feed_form', $edit, true);
278      }      }
279        else {
280    
281      if(is_numeric(arg(4)) && arg(3) == 'convert'){        $output .= drupal_get_form('planet_settings_form');
282          $items[] = array('path' => 'admin/settings/planet/convert/' . arg(4), 'title' => t('planet convert'),        //$output .= drupal_get_form('settings', $form);
283                  'callback' => 'planet_convert_to_blog', 'access' => user_access('administer nodes'),        //$output .= $form;
284                  'type' => MENU_CALLBACK);  
285          $output .= drupal_get_form('planet_feed_form', $edit);
286    
287         // $result = db_query('SELECT *, (UNIX_TIMESTAMP(NOW()) - checked) _checked FROM {planet_feeds}');
288          $result = db_query('SELECT COUNT(f.fid) cnt, f.*, (UNIX_TIMESTAMP(NOW()) - checked) _checked FROM {planet_feeds} f LEFT OUTER JOIN {planet_items} i ON i.fid = f.fid GROUP BY f.fid;');
289          $rows = array();
290          $headers = array('Feed', 'Items', 'Edit', 'Last checked', 'Refresh', 'Freeze');
291          while ($feed = db_fetch_object($result)) {
292            $checked = intval($feed->_checked / 60) .' minutes';
293            if ($feed->_checked % 60 > 0) {
294              $checked .= ', '. $feed->_checked % 60 .' seconds';
295            }
296            $checked .= ' ago';
297            array_push($rows, array(
298              $feed->title,
299              $feed->cnt,
300              l('edit', 'admin/settings/planet/'. intval($feed->fid)),
301              $checked,
302              l('refresh', 'admin/settings/planet/refresh/'. intval($feed->fid)),
303              l($feed->frozen ? 'unfreeze' : 'freeze', 'admin/settings/planet/'. ($feed->frozen ? 'unfreeze/' : 'freeze/') . intval($feed->fid))
304              )
305            );
306          }
307          $output .= '<h2>Feeds</h2>';
308          $output .= theme('table', $headers, $rows);
309      }      }
310        print theme('page', $output);
311      }
312    }
313    
314      $items[] = array('path' => 'planet', 'title' => t('Planet'),  function planet_multiple_delete_confirm(&$form_state, $nodes, $fid, $redirect) {
315        'callback' => 'planet_page_last', 'access' => user_access('access content'),    $form_state['values']['fid'] = $fid;
316        'type' => MENU_CALLBACK);    $form_state['values']['redirect'] = $redirect;
317      $form['nodes'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
318      $items[] = array('path' => 'planet/feed', 'title' => t('Planet'),    // array_filter returns only elements with TRUE values
319        'callback' => 'planet_feed', 'access' => user_access('access content'),    foreach ($nodes as $nid => $value) {
320        'type' => MENU_CALLBACK);      $title = db_result(db_query('SELECT title FROM {node} WHERE nid = %d', $nid));
321        $form['nodes'][$nid] = array(
322          return $items;        '#type' => 'hidden',
323          '#value' => $nid,
324          '#prefix' => '<li>',
325          '#suffix' => check_plain($title) ."</li>\n",
326        );
327      }
328      $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
329      $form['#submit'][] = 'planet_multiple_delete_confirm_submit';
330      return confirm_form($form,
331                          t('Are you sure you want to delete these items?'),
332                          $redirect, t('This action cannot be undone.'),
333                          t('Delete all'), t('Cancel'));
334  }  }
335    
336  function planet_call_refresh(){  function planet_multiple_delete_confirm_submit(&$form_state, $edit) {
337          $title = planet_refresh();    $fid = $edit['fid'];
338          watchdog('planet', 'Feed "' . $title . '" refreshed.');    if ($edit['confirm']) {
339          drupal_set_message('Feed "' . $title . '" refreshed.');      foreach ($edit['nodes'] as $nid => $value) {
340          drupal_goto('admin/settings/planet');        node_delete($nid);
341  }      }
342        db_query('DELETE FROM {planet_feeds} WHERE fid = %d', $fid);
343  function planet_toggle_frozen(){      db_query('DELETE FROM {planet_items} WHERE fid = %d', $fid);
344          $fid = intval(arg(4));      drupal_set_message(t('The feed and items have been deleted.'));
345          db_query('UPDATE {planet_feeds} SET frozen = %d WHERE fid = %d', arg(3) == 'unfreeze' ? 0 : 1, $fid);    }
346          drupal_set_message('Feed ' . (arg(3) == 'unfreeze' ? 'un' : '') . 'frozen.');    drupal_goto($edit['redirect']);
         drupal_goto('admin/settings/planet');  
 }  
   
 function _planet_settings(){  
         if($_POST){  
                 $edit = $_POST;  
   
                 if($_POST['op'] == 'Delete' && intval($edit['fid']) > 0){  
                         db_query('DELETE FROM {planet_feeds} WHERE fid = %d', intval($edit['fid']));  
                         drupal_set_message('Deleted feed.');  
                 }  
                 else{  
                         if(isset($edit['fid']) && intval($edit['fid']) == 0){  
                                 db_query('INSERT INTO {planet_feeds} (uid, title, link, image, checked, frozen) VALUES(%d, "%s", "%s", "%s", 0, 0)', $edit['uid'], $edit['title'], $edit['link'], $edit['image']);  
                                 drupal_set_message('Added new feed.');  
                         }  
                         else if($edit['fid'] && intval($edit['fid']) > 0){  
                                 db_query('UPDATE {planet_feeds} SET uid = %d, title="%s", link = "%s", image="%s" WHERE fid=%d', $edit['uid'], $edit['title'], $edit['link'], $edit['image'], $edit['fid']);  
                                 drupal_set_message('Edited "' . $edit['title'] . '" feed.');  
                         }  
                         else{  
                                 if($edit['planet_author_roles']){  
                                         variable_set('planet_author_roles', $edit['planet_author_roles']);  
                                 }  
                                 if($edit['planet_auto_publish']){  
                                         variable_set('planet_auto_publish', $edit['planet_auto_publish']);  
                                 }  
                                 if($edit['planet_redirect_page'] == 1){  
                                         variable_set('planet_redirect_page', $edit['planet_redirect_page']);  
                                 }  
                                 else{  
                                         variable_del('planet_redirect_page');  
                                 }  
                                 drupal_set_message('Edited general planet settings.');  
                         }  
                 }  
                 drupal_goto('admin/settings/planet');  
         }  
         else{  
                 $fid = intval(arg(3));  
                 if($fid > 0){  
                         $edit = db_fetch_array(db_query('SELECT * FROM {planet_feeds} WHERE fid = %d', $fid));  
                         $output .= drupal_get_form('planet_feed_form', $edit, true);  
                 }  
                 else{  
   
                         $output .= '<h2>Recent Items</h2>';  
                         $output .= planet_queue();  
   
                         $output .= drupal_get_form('planet_settings_form');  
                         //$output .= drupal_get_form('settings', $form);  
                         //$output .= $form;  
   
                         $output .= drupal_get_form('planet_feed_form', $edit);  
   
                         $result = db_query('SELECT *, (UNIX_TIMESTAMP(NOW()) - checked) _checked FROM {planet_feeds}');  
                         $result = db_query('SELECT COUNT(f.fid) cnt, f.*, (UNIX_TIMESTAMP(NOW()) - checked) _checked FROM {planet_feeds} f LEFT OUTER JOIN {planet_items} i ON i.fid = f.fid GROUP BY f.fid;');  
                         $rows = array();  
                         $headers = array('Feed', 'Items', 'Edit', 'Last checked', 'Refresh', 'Freeze');  
                         while($feed = db_fetch_object($result)){  
                                 $checked = intval($feed->_checked / 60) . ' minutes';  
                                 if($feed->_checked % 60 > 0){  
                                         $checked .= ', ' . $feed->_checked % 60 . ' seconds';  
                                 }  
                                 $checked .= ' ago';  
                                 array_push($rows, array(  
                                         $feed->title,  
                                         $feed->cnt,  
                                         l('edit', 'admin/settings/planet/' . intval($feed->fid)),  
                                         $checked,  
                                         l('refresh', 'admin/settings/planet/refresh/' . intval($feed->fid)),  
                                         l($feed->frozen ? 'unfreeze' : 'freeze', 'admin/settings/planet/' . ($feed->frozen ? 'unfreeze/' : 'freeze/') . intval($feed->fid))  
                                         )  
                                 );  
                         }  
                         $output .= '<h2>Feeds</h2>';  
                         $output .= theme('table', $headers, $rows);  
                 }  
                 print theme('page', $output);  
         }  
347  }  }
348    
 function planet_settings_form(){  
         $roles = array();  
349    
         $result = db_query('SELECT rid, name FROM {role}');  
         while($role = db_fetch_object($result)){  
                 $roles[$role->rid] = $role->name;  
         }  
350    
351          $form = array();  function planet_settings_form(&$form_state) {
352          $form['general'] = array('#type' => 'fieldset', '#title' => t('General Settings'));    $roles = array();
         $form['general']['planet_auto_publish'] = array('#type' => 'textfield', '#title' => t('Auto-publish text'), '#value' => variable_get('planet_auto_publish', ''), '#size' => 30, '#maxlength' => 30, '#description' => t('If this snippet appears in the aggregated item, it will be auto-published.'));  
         $form['general']['planet_author_roles'] = array('#type' => 'select', '#title' => t('Role to select authors from'), '#options' => $roles, '#default_value' => variable_get('planet_author_roles', 2), '#description' =>t('Select the role from which blog authors should be selected on the feed creation screen.'));  
         $form['general']['planet_redirect_page'] = array('#type' => 'checkbox', '#title' => t('Redirect node?'), '#return_value' => 1, '#value' => (variable_get('planet_redirect_page', 0) == 1) ? 1 : null, '#description' => t('Check this if you want the node view to redirect to the original content link; this is useful if you want the feed to forward through instead of showing the planet node.'));  
         $form['general']['submit'] = array('#type' => 'submit', '#value' => 'Adjust Settings');  
         return $form;  
 }  
   
   
 function planet_feed_form($edit = array(), $individual = false){  
         $uids = array();  
         $result = db_query('SELECT u.uid, u.name FROM {users} u, {role} r, {users_roles} ur WHERE u.uid = ur.uid AND ur.rid = r.rid AND r.rid = %d ORDER BY u.name ASC', variable_get('planet_author_roles',2));  
         while($f_user = db_fetch_object($result)){  
                 $uids[$f_user->uid] = $f_user->name;  
         }  
   
         $form = array();  
         $form['feeds'] = array('#type' => 'fieldset', '#title' => 'Feeds');  
         $form['feeds']['fid'] = array('#type' => 'hidden', '#value' => $edit['fid']);  
         $form['feeds']['title'] = array('#type' => 'textfield', '#title' => t('Title'), '#value' => $edit['title'], '#size' => 40, '#maxlength' => 40);  
         $form['feeds']['uid'] = array('#type' => 'select', '#title' => t('Original author'), '#value' => $edit['uid'], '#options' => $uids, '#description' => t('Select a user to associate this feed with'));  
         $form['feeds']['link'] = array('#type' => 'textfield', '#title' => t('URL'), '#value' => $edit['link'], '#size' => 40, '#maxlength' => 80);  
         $form['feeds']['submit'] = array('#type' => 'submit', '#value' => $edit['fid'] > 0 ? 'Edit' : 'Add' . ' Feed');  
353    
354          if($individual){    $result = db_query('SELECT rid, name FROM {role}');
355                  $form['queue'] = array('#type' => 'item', '#value' => planet_queue(intval($edit['uid'])));    while ($role = db_fetch_object($result)) {
356          }      $roles[$role->rid] = $role->name;
357      }
358          return $form;  
359  }    unset($result);
360      $result = db_query('SELECT format, name FROM {filter_formats}');
361      while ($format = db_fetch_object($result)) {
362        $formats[$format->format] = $format->name;
363      }
364    
365  function planet_queue($uid = null){    $form = array();
366          $rows = array();  
367          $headers = array('Title', 'Created', 'Convert');    $form['general'] = array(
368        '#type' => 'fieldset',
369          if($uid > 0){      '#title' => t('General Settings')
370                  $result = pager_query(db_rewrite_sql('SELECT nid, title, created FROM {node} WHERE type = "planet" AND uid = ' . intval($uid) . ' ORDER BY created DESC'), variable_get('default_nodes_main', 10), 0, NULL);    );
371          }  
372          else{    $form['general']['planet_author_roles'] = array(
373                  $result = pager_query(db_rewrite_sql('SELECT nid, title, created FROM {node} WHERE type = "planet" ORDER BY created DESC'), variable_get('default_nodes_main', 10), 0, NULL);      '#type' => 'select',
374          }      '#title' => t('Role to select authors from'),
375        '#options' => $roles,
376          while($node = db_fetch_object($result)){      '#default_value' => variable_get('planet_author_roles', 2),
377                  array_push($rows,       array(      '#description' => t('Select the role from which blog authors should be selected on the feed creation screen.')
378                                                                  l($node->title, 'node/' . $node->nid),    );
379                                                                  format_date($node->created, 'custom', 'Y-m-d H:i'),  
380                                                                  l('convert', 'admin/settings/planet/convert/' . $node->nid)    $form['general']['planet_filter_formats'] = array(
381                                                          )      '#type' => 'select',
382                  );      '#title' => t('Filter format for planet entry nodes'),
383          }      '#options' => $formats,
384          $output .= theme('table',$headers, $rows);      '#default_value' => variable_get('planet_filter_formats', 1),
385          $output .= theme('pager', NULL, variable_get('default_nodes_main', 10));      '#description' => t('Select the filter format that will be used to show planet entry nodes.')
386          return $output;    );
387    
388      $form['general']['planet_redirect_page'] = array(
389        '#type' => 'checkbox',
390        '#title' => t('Redirect node?'),
391        '#return_value' => 1,
392        '#value' => (variable_get('planet_redirect_page', 0) == 1) ? 1 : null,
393        '#description' => t('Check this if you want the node view to redirect to the original content link; this is useful if you want the feed to forward through instead of showing the planet node.')
394      );
395    
396      $form['general']['submit'] = array(
397        '#type' => 'submit',
398        '#value' => 'Save Configuration'
399      );
400    
401      return $form;
402  }  }
403    
404    
405    function planet_feed_form(&$form_state, $edit = array(), $individual = false, $user = NULL) {
406      $uids = array();
407      $result = db_query('SELECT u.uid, u.name FROM {users} u, {role} r, {users_roles} ur WHERE u.uid = ur.uid AND ur.rid = r.rid AND r.rid = %d ORDER BY u.name ASC', variable_get('planet_author_roles', 2));
408      while ($f_user = db_fetch_object($result)) {
409        $uids[$f_user->uid] = $f_user->name;
410      }
411    
412      if ($individual) {
413        if (!isset($uids[$edit['uid']])) {
414          $g_user = db_fetch_array(db_query('SELECT uid, name FROM {users} WHERE uid = %d', $edit['uid']));
415          $uids[$edit['uid']] = $g_user['name'];
416        }
417      }
418    
419      $form = array();
420    
421  function planet_cron(){    $form['feeds'] = array(
422          $result = db_query('SELECT fid FROM {planet_feeds} WHERE frozen = 0');      '#type' => 'fieldset',
423          while($feed = db_fetch_object($result)){      '#title' => 'Feeds'
424                  $title = planet_refresh($feed->fid);    );
425                  watchdog('planet', 'Cron updated feed "' . $title . '".');  
426          }    $form['feeds']['fid'] = array(
427  }      '#type' => 'hidden',
428        '#value' => $edit['fid']
429      );
430    
431  function planet_refresh($fid = null){    $form['feeds']['title'] = array(
432          if(!$fid){      '#type' => 'textfield',
433                  $fid = intval(arg(4));      '#title' => t('Title'),
434          }      '#value' => $edit['title'],
435        '#size' => 40,
436          $feed = db_fetch_object(db_query('SELECT * FROM {planet_feeds} WHERE fid = %d', $fid));      '#maxlength' => 40
437      );
438          $headers = array();  
439          $result = planet_http_request($feed->link, $headers, 15);    if ($user == NULL) {
440        $form['feeds']['uid'] = array(
441          switch ($result->code) {        '#type' => 'select',
442                  case 304:        '#title' => t('Original author'),
443                          drupal_set_message(t('No new content syndicated from %site.', array('%site' => '<em>'. $feed->title .'</em>')));        '#value' => $edit['uid'],
444                          break;        '#options' => $uids,
445          '#description' => t('Select a user to associate this feed with')
446                  case 301:      );
447                          if ($result->redirect_url) {    }
448                                  $feed->link = $result->redirect_url;    else {
449                                  watchdog('planet', t('Updated URL for feed %title to %url.', array('%title' => '<em>'. $feed->title .'</em>', '%url' => '<em>'. $feed->url .'</em>')), WATCHDOG_NOTICE, l(t('view'), 'planet/'.$feed->fid));      $form['feeds']['uid'] = array(
450                                  db_query("UPDATE {planet_feeds} SET link = '%s' WHERE fid = %d", $feed->link, $feed->fid);        '#type' => 'hidden',
451                          }        '#value' => $user->uid,
452                          break;      );
453      }
454                  case 200:    $form['feeds']['link'] = array(
455                  case 302:      '#type' => 'textfield',
456                  case 307:      '#title' => t('URL'),
457                          $xml_tree = planet_parse_xml($result->data);      '#value' => $edit['link'],
458        '#size' => 40,
459                          if ($xml_tree['parser_error']) {      '#maxlength' => 80
460                                  watchdog('planet', t('Failed to parse RSS feed %site: %error at line %line.', array('%site' => '<em>'. $feed->title .'</em>', '%error' => $xml_tree['parser_error'], '%line' => $xml_tree['parser_line'])), WATCHDOG_ERROR);    );
461                                  drupal_set_message(t('Failed to parse RSS feed %site: %error at line %line.', array('%site' => '<em>'. $feed->title .'</em>', '%error' => $xml_tree['parser_error'], '%line' => $xml_tree['parser_line'])), 'error');  
462                                  break;    $form['feeds']['submit'] = array(
463                          }      '#type' => 'submit',
464                          else {      '#value' => $edit['fid'] > 0 ? 'Save' : 'Add'.' Feed'
465                                  drupal_set_message('Parsing feed '. $feed->title .' took '. $xml_tree['parser_time'] .' seconds.');    );
466                          }  
467      if ($individual) {
468                          if (planet_parse_items($xml_tree, $feed) !== false){      $form['feeds']['delete'] = array(
469                                  if ($result->headers['Last-Modified']) {        '#type' => 'submit',
470                                          $modified = strtotime($result->headers['Last-Modified']);        '#value' => 'Delete',
471                                  }      );
472      }
473                                  /*  
474                                  ** Prepare data:    return $form;
                                 */  
                                 if ($xml_tree['RSS']) { // RSS 0.91, 0.92, 2.0  
                                         $root = &$xml_tree['RSS'][0];  
                                         $channel = &$root['CHANNEL'][0];  
                                         $image = &$channel['IMAGE'][0];  
                                         $description = &$channel['DESCRIPTION'][0]['VALUE'];  
                                         $link = &$channel['LINK'][0]['VALUE'];  
                                 }  
                                 else if ($xml_tree['RDF:RDF']) {  
                                         $root = &$xml_tree['RDF:RDF'][0];  
                                         $channel = &$root['CHANNEL'][0];  
                                         $image = &$root['IMAGE'][0];  
                                         $description = &$channel['DESCRIPTION'][0]['VALUE'];  
                                         $link = &$channel['LINK'][0]['VALUE'];  
                                 }  
                                 else if ($xml_tree['FEED']) { // Atom 0.3, 1.0  
                                         $root = &$xml_tree['FEED'][0];  
                                         $channel = &$root;  
                                         $image = &$channel['LOGO'][0]['VALUE'];  
                                         $description = ($channel['TAGLINE'][0]['VALUE'] ? $channel['TAGLINE'][0]['VALUE'] : '');  
                                         // TODO: remove this Atom hack when we have field mapping or at least specialized parsers in place  
                                         if (count($channel['LINK']) > 1) {  
                                                 $link = $feed->link;  
                                                 foreach ($channel['LINK'] as $l) {  
                                                         if ($l['REL'] == 'alternate') {  
                                                                 $link = $l['HREF'];  
                                                         }  
                                                 }  
                                         }  
                                         else {  
                                                 $link = $channel['LINK'][0]['HREF'];  
                                         }  
                                 }  
                                 else if ($xml_tree['CHANNEL']) { // RSS 1.1  
                                         $root = &$xml_tree['CHANNEL'][0];  
                                         $channel = &$root;  
                                         $image = &$channel['IMAGE'][0];  
                                         $description = &$channel['DESCRIPTION'][0]['VALUE'];  
                                         $link = &$channel['LINK'][0]['VALUE'];  
                                 }  
                                 else if ($xml_tree['OPML']) {  
                                         $root = &$xml_tree['OPML'][0];  
                                         $channel = &$root;  
                                         $image = NULL;  
                                         $description = NULL;  
                                         $link = NULL;  
                                 }  
                                 else {  
                                         // unsupported format  
                                         break;  
                                 }  
   
                                 if (!$feed->uid) {  
                                         if ($channel['AUTHOR'][0]['VALUE']) {  
                                                 $feed->uid = $channel['AUTHOR'][0]['VALUE'];  
                                         }  
                                         if ($channel['AUTHOR'][0]['NAME'][0]['VALUE']) {  
                                                 $feed->uid = $channel['AUTHOR'][0]['NAME'][0]['VALUE'];  
                                         }  
                                         else if ($channel['DC:CREATOR']) {  
                                                 $feed->uid = $channel['DC:CREATOR'][0]['VALUE'];  
                                         }  
                                         else {  
                                                 $feed->uid = '';  
                                         }  
                                 }  
   
                                 /*  
                                 ** Generate image link  
                                 */  
                                 if (!$feed->image && $image['LINK'] && $image['URL'] && $image['TITLE']) {  
                                         if (strlen($image['TITLE'][0]['VALUE']) > 250) {  
                                                 $image['TITLE'][0]['VALUE'] = trim(substr($image['TITLE'][0]['VALUE'], 0, 250)).'...';  
                                         }  
                                         $feed->image = '<a href="'. $image['LINK'][0]['VALUE'] .'" class="planet_logo_link"><img src="'. $image['URL'][0]['VALUE'] .'" class="planet_logo" alt="'. $image['TITLE'][0]['VALUE'] .'" /></a>';  
                                 }  
   
                                 /*  
                                 ** Update the feed data:  
                                 */  
                                 $feed->checked = time();  
                                 $feed->link = $link;  
                                 $feed->etag = $result->headers['ETag'];  
                                 $feed->modified = $modified;  
                                 if ($feed->body == '' && $description/* && valid_input_data($description)*/) {  
                                         $feed->body = $feed->teaser = $description;  
                                 }  
                                 $feed->rss_data = &$xml_tree;  
   
                                 /*  
                                 ** Taxonomy module doesn't add taxonomy terms at load time... so we have to do it by hand :((  
                                 */  
                                 $terms = module_invoke('taxonomy', 'node_get_terms', $feed->nid, 'tid');  
                                 $feed->taxonomy = array();  
                                 foreach ($terms as $tid => $term) {  
                                         if ($term->tid) {  
                                                 $feed->taxonomy[] = $term->tid;  
                                         }  
                                 }  
                         }  
                 default:  
         }  
   
   
         db_query('UPDATE {planet_feeds} SET checked = %d WHERE fid = %d', time(), $fid);  
         return $feed->title;  
         //print theme('page', 'refreshing ' . $fid . '.');// and got ' . print_r($feed, 1));  
475  }  }
476    
477  /**  function planet_cron() {
478   * Let admin users convert nodes to blog posts.    $result = db_query('SELECT fid FROM {planet_feeds} WHERE frozen = 0');
479   */    while ($feed = db_fetch_object($result)) {
480  function planet_convert_to_blog($nid = NULL){      $title = planet_refresh($feed->fid);
481          if(user_access('administer nodes')){      watchdog('planet', 'Cron updated feed "'. $title .'".');
482                  if ($nid == NULL && is_numeric(arg(4))) {    }
                         $nid = intval(arg(4));  
                 }  
                 $node = node_load($nid);  
                 if($node->type == 'planet'){  
                         //Unpublish planet item  
                         $node->status = 0;  
                         node_save($node);  
   
                         //Now reset some fields and resave as a blog node.  
                         $node->type = 'blog';  
                         $node->nid = null;  
                         $node->comment = 2;  
                         $node->status = 1;  
                         $nid = node_save($node);  
   
                         //And redirect to the new node.  
                         $url = $node->path ? $node->path : 'node/' . $nid;  
                         drupal_set_message(t('The feed item has been converted.'));  
                         drupal_goto($url);  
                         //drupal_goto('admin/feeds/queue');  
                 }  
         }  
483  }  }
484    
485    function planet_refresh($fid = null) {
486      if (!$fid) {
487        $fid = intval(arg(4));
488      }
489    
490      $feed = db_fetch_object(db_query('SELECT * FROM {planet_feeds} WHERE fid = %d', $fid));
491    
492      $headers = array();
493      $result = planet_http_request($feed->link, $headers, 15);
494    
495      switch ($result->code) {
496        case 304:
497          drupal_set_message(t('No new content syndicated from %site.', array('%site' => '<em>'. $feed->title .'</em>')));
498          break;
499    
500        case 301:
501          if ($result->redirect_url) {
502            $feed->link = $result->redirect_url;
503            watchdog('planet', 'Updated URL for feed %title to %url.', array('%title' => '<em>'. $feed->title .'</em>', '%url' => '<em>'. $feed->url .'</em>'), WATCHDOG_NOTICE, l(t('view'), 'planet/'.$feed->fid));
504            db_query("UPDATE {planet_feeds} SET link = '%s' WHERE fid = %d", $feed->link, $feed->fid);
505          }
506          break;
507    
508        case 200:
509        case 302:
510        case 307:
511          $xml_tree = planet_parse_xml($result->data);
512    
513          if ($xml_tree['parser_error']) {
514            watchdog('planet', 'Failed to parse RSS feed %site: %error at line %line.', array('%site' => '<em>'. $feed->title .'</em>', '%error' => $xml_tree['parser_error'], '%line' => $xml_tree['parser_line']), WATCHDOG_ERROR);
515            drupal_set_message(t('Failed to parse RSS feed %site: %error at line %line.', array('%site' => '<em>'. $feed->title .'</em>', '%error' => $xml_tree['parser_error'], '%line' => $xml_tree['parser_line'])), 'error');
516            break;
517          }
518          else {
519            drupal_set_message('Parsing feed '. $feed->title .' took '. $xml_tree['parser_time'] .' seconds.');
520          }
521    
522          if (planet_parse_items($xml_tree, $feed) !== false) {
523            if ($result->headers['Last-Modified']) {
524              $modified = strtotime($result->headers['Last-Modified']);
525            }
526    
527            /*
528            ** Prepare data:
529            */
530            if ($xml_tree['RSS']) { // RSS 0.91, 0.92, 2.0
531              $root = &$xml_tree['RSS'][0];
532              $channel = &$root['CHANNEL'][0];
533              $image = &$channel['IMAGE'][0];
534              $description = &$channel['DESCRIPTION'][0]['VALUE'];
535              $link = &$channel['LINK'][0]['VALUE'];
536            }
537            else if ($xml_tree['RDF:RDF']) {
538              $root = &$xml_tree['RDF:RDF'][0];
539              $channel = &$root['CHANNEL'][0];
540              $image = &$root['IMAGE'][0];
541              $description = &$channel['DESCRIPTION'][0]['VALUE'];
542              $link = &$channel['LINK'][0]['VALUE'];
543            }
544            else if ($xml_tree['FEED']) { // Atom 0.3, 1.0
545              $root = &$xml_tree['FEED'][0];
546              $channel = &$root;
547              $image = &$channel['LOGO'][0]['VALUE'];
548              $description = ($channel['TAGLINE'][0]['VALUE'] ? $channel['TAGLINE'][0]['VALUE'] : '');
549              // TODO: remove this Atom hack when we have field mapping or at least specialized parsers in place
550              if (count($channel['LINK']) > 1) {
551                $link = $feed->link;
552                foreach ($channel['LINK'] as $l) {
553                  if ($l['REL'] == 'alternate') {
554                    $link = $l['HREF'];
555                  }
556                }
557              }
558              else {
559                $link = $channel['LINK'][0]['HREF'];
560              }
561            }
562            else if ($xml_tree['CHANNEL']) { // RSS 1.1
563              $root = &$xml_tree['CHANNEL'][0];
564              $channel = &$root;
565              $image = &$channel['IMAGE'][0];
566              $description = &$channel['DESCRIPTION'][0]['VALUE'];
567              $link = &$channel['LINK'][0]['VALUE'];
568            }
569            else if ($xml_tree['OPML']) {
570              $root = &$xml_tree['OPML'][0];
571              $channel = &$root;
572              $image = NULL;
573              $description = NULL;
574              $link = NULL;
575            }
576            else {
577              // unsupported format
578              break;
579            }
580    
581            if (!$feed->uid) {
582              if ($channel['AUTHOR'][0]['VALUE']) {
583                $feed->uid = $channel['AUTHOR'][0]['VALUE'];
584              }
585              if ($channel['AUTHOR'][0]['NAME'][0]['VALUE']) {
586                $feed->uid = $channel['AUTHOR'][0]['NAME'][0]['VALUE'];
587              }
588              else if ($channel['DC:CREATOR']) {
589                $feed->uid = $channel['DC:CREATOR'][0]['VALUE'];
590              }
591              else {
592                $feed->uid = '';
593              }
594            }
595    
596            /*
597            ** Generate image link
598            */
599            if (!$feed->image && $image['LINK'] && $image['URL'] && $image['TITLE']) {
600              if (strlen($image['TITLE'][0]['VALUE']) > 250) {
601                $image['TITLE'][0]['VALUE'] = trim(substr($image['TITLE'][0]['VALUE'], 0, 250)).'...';
602              }
603              $feed->image = '<a href="'. $image['LINK'][0]['VALUE'] .'" class="planet_logo_link"><img src="'. $image['URL'][0]['VALUE'] .'" class="planet_logo" alt="'. $image['TITLE'][0]['VALUE'] .'" /></a>';
604            }
605    
606            /*
607            ** Update the feed data:
608            */
609            $feed->checked = time();
610            $feed->link = $link;
611            $feed->etag = $result->headers['ETag'];
612            $feed->modified = $modified;
613            if ($feed->body == '' && $description/* && valid_input_data($description)*/) {
614              $feed->body = $feed->teaser = $description;
615            }
616            $feed->rss_data = &$xml_tree;
617    
618            /*
619            ** Taxonomy module doesn't add taxonomy terms at load time... so we have to do it by hand :((
620            */
621            $terms = module_invoke('taxonomy', 'node_get_terms', $feed->nid, 'tid');
622            $feed->taxonomy = array();
623            foreach ($terms as $tid => $term) {
624              if ($term->tid) {
625                $feed->taxonomy[] = $term->tid;
626              }
627            }
628          }
629        default:
630      }
631    
632    
633      db_query('UPDATE {planet_feeds} SET checked = %d WHERE fid = %d', time(), $fid);
634      return $feed->title;
635      //print theme('page', 'refreshing '. $fid .'.');// and got '. print_r($feed, 1));
636    }
637    
638  /**  /**
639   * Private function; Parse HTTP headers from data retreived with cURL   * Private function; Parse HTTP headers from data retreived with cURL
640   * from: http://pl2.php.net/manual/en/function.curl-setopt.php#42009   * from: http://pl2.php.net/manual/en/function.curl-setopt.php#42009
641   */   */
642  function planet_parse_response($response){  function planet_parse_response($response) {
643          /*    /*
644           ***original code extracted from examples at     ***original code extracted from examples at
645           ***http://www.webreference.com/programming     ***http://www.webreference.com/programming
646                                                                                                           /php/cookbook/chap11/1/3.html                             /php/cookbook/chap11/1/3.html
647    
648           ***returns an array in the following format which varies depending on headers returned     ***returns an array in the following format which varies depending on headers returned
649    
650                           [0] => the HTTP error or response code such as 404         [0] => the HTTP error or response code such as 404
651                           [1] => Array         [1] => Array
652                           (         (
653                                           [Server] => Microsoft-IIS/5.0             [Server] => Microsoft-IIS/5.0
654                                           [Date] => Wed, 28 Apr 2004 23:29:20 GMT             [Date] => Wed, 28 Apr 2004 23:29:20 GMT
655                                           [X-Powered-By] => ASP.NET             [X-Powered-By] => ASP.NET
656                                           [Connection] => close             [Connection] => close
657                                           [Set-Cookie] => COOKIESTUFF             [Set-Cookie] => COOKIESTUFF
658                                           [Expires] => Thu, 01 Dec 1994 16:00:00 GMT             [Expires] => Thu, 01 Dec 1994 16:00:00 GMT
659                                           [Content-Type] => text/html             [Content-Type] => text/html
660                                           [Content-Length] => 4040             [Content-Length] => 4040
661                           )         )
662                           [2] => Response body (string)         [2] => Response body (string)
663          */    */
664    
665          do {    do {
666                  list($response_headers, $response) = explode("\r\n\r\n", $response, 2);      list($response_headers, $response) = explode("\r\n\r\n", $response, 2);
667                  $response_header_lines = explode("\r\n", $response_headers);      $response_header_lines = explode("\r\n", $response_headers);
668    
669                  // first line of headers is the HTTP response code      // first line of headers is the HTTP response code
670                  $http_response_line = array_shift($response_header_lines);      $http_response_line = array_shift($response_header_lines);
671                  if (preg_match('@^HTTP/[0-9]\.[0-9] ([0-9]{3})@', $http_response_line, $matches)) {      if (preg_match('@^HTTP/[0-9]\.[0-9] ([0-9]{3})@', $http_response_line, $matches)) {
672                          $response_code = $matches[1];        $response_code = $matches[1];
673                  }      }
674                  else {      else {
675                          $response_code = "Error";        $response_code = "Error";
676                  }      }
677          }    }
678          while (substr($response_code, 0, 1) == "1");    while (substr($response_code, 0, 1) == "1");
679    
680          $response_body = $response;    $response_body = $response;
681    
682          // put the rest of the headers in an array    // put the rest of the headers in an array
683          $response_header_array = array();    $response_header_array = array();
684          foreach ($response_header_lines as $header_line) {    foreach ($response_header_lines as $header_line) {
685                  list($header, $value) = explode(':', $header_line, 2);      list($header, $value) = explode(':', $header_line, 2);
686                  $response_header_array[$header] = trim($value);      $response_header_array[$header] = trim($value);
687          }    }
688    
689          return array($response_code, $response_header_array, $response_body, $http_response_line);    return array($response_code, $response_header_array, $response_body, $http_response_line);
690  }  }
691    
692  /**  /**
693   * Private function; Gets data from given URL :)   * Private function; Gets data from given URL :)
694   */   */
695  function planet_http_request($url, $headers = array(), $timeout = 15, $method = 'GET', $data = NULL, $follow = 3) {  function planet_http_request($url, $headers = array(), $timeout = 15, $method = 'GET', $data = NULL, $follow = 3) {
696          if (!function_exists('curl_init')) {    if (!function_exists('curl_init')) {
697                  return drupal_http_request($url, $headers, $method, $data, $follow);      return drupal_http_request($url, $headers, $method, $data, $follow);
698          }    }
699    
700          // convert headers array to format used by cURL    // convert headers array to format used by cURL
701          $temp = array();    $temp = array();
702          foreach ($headers as $header => $value) {    foreach ($headers as $header => $value) {
703                  $temp[] = $header .': '. $value;      $temp[] = $header .': '. $value;
704          }    }
705          $headers = $temp;    $headers = $temp;
706    
707          $result = new StdClass();    $result = new StdClass();
708    
709          $ch = curl_init();    $ch = curl_init();
710          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
711          curl_setopt($ch, CURLOPT_URL, $url);    curl_setopt($ch, CURLOPT_URL, $url);
712          curl_setopt($ch, CURLOPT_HEADER, 1);    curl_setopt($ch, CURLOPT_HEADER, 1);
713          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
714          curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
715          curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
716    
717          $data = curl_exec($ch);    $data = curl_exec($ch);
718          $info = curl_getinfo($ch);    $info = curl_getinfo($ch);
719    
720          curl_close($ch);    curl_close($ch);
721          unset($ch);    unset($ch);
722    
723          $response = planet_parse_response($data);    $response = planet_parse_response($data);
724          $result->code = $response[0];    $result->code = $response[0];
725          $result->headers = $response[1];    $result->headers = $response[1];
726          $result->data = $response[2];    $result->data = $response[2];
727          $error = $response[3];    $error = $response[3];
728          switch ($code) {    switch ($code) {
729                  case 200: // OK      case 200: // OK
730                  case 304: // Not modified      case 304: // Not modified
731                          break;        break;
732                  case 301: // Moved permanently      case 301: // Moved permanently
733                  case 302: // Moved temporarily      case 302: // Moved temporarily
734                  case 307: // Moved temporarily      case 307: // Moved temporarily
735                          $location = $result->headers['Location'];        $location = $result->headers['Location'];
736    
737                          if ($follow) {        if ($follow) {
738                                  $result = planet_http_request($result->headers['Location'], $headers, $timeout, $method, $data, --$follow);          $result = planet_http_request($result->headers['Location'], $headers, $timeout, $method, $data, --$follow);
739                                  $result->redirect_code = $result->code;          $result->redirect_code = $result->code;
740                          }        }
741                          $result->redirect_url = $location;        $result->redirect_url = $location;
742                          break;        break;
743                  default:      default:
744                          $result->error = $error;        $result->error = $error;
745                          break;        break;
746          }    }
747    
748          $result->code = $response[0];    $result->code = $response[0];
749          return $result;    return $result;
750  }  }
751    
752  /**  /**
# Line 585  function planet_http_request($url, $head Line 765  function planet_http_request($url, $head
765   * @return A timestamp if parsed successfully or -1 if not.   * @return A timestamp if parsed successfully or -1 if not.
766   */   */
767  function planet_parse_w3cdtf($date_str) {  function planet_parse_w3cdtf($date_str) {
768          if (preg_match('/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/', $date_str, $match)) {    if (preg_match('/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/', $date_str, $match)) {
769                  list($year, $month, $day, $hours, $minutes, $seconds) = array($match[1], $match[2], $match[3], $match[4], $match[5], $match[6]);      list($year, $month, $day, $hours, $minutes, $seconds) = array($match[1], $match[2], $match[3], $match[4], $match[5], $match[6]);
770                  // calc epoch for current date assuming GMT      // calc epoch for current date assuming GMT
771                  $epoch = gmmktime($hours, $minutes, $seconds, $month, $day, $year);      $epoch = gmmktime($hours, $minutes, $seconds, $month, $day, $year);
772                  if ($match[10] != 'Z') { // Z is zulu time, aka GMT      if ($match[10] != 'Z') { // Z is zulu time, aka GMT
773                          list($tz_mod, $tz_hour, $tz_min) = array($match[8], $match[9], $match[10]);        list($tz_mod, $tz_hour, $tz_min) = array($match[8], $match[9], $match[10]);
774                          // zero out the variables        // zero out the variables
775                          if (!$tz_hour) {        if (!$tz_hour) {
776                                  $tz_hour = 0;          $tz_hour = 0;
777                          }        }
778                          if (!$tz_min) {        if (!$tz_min) {
779                                  $tz_min = 0;          $tz_min = 0;
780                          }        }
781                          $offset_secs = (($tz_hour * 60) + $tz_min) * 60;        $offset_secs = (($tz_hour * 60) + $tz_min) * 60;
782                          // is timezone ahead of GMT?    then subtract offset        // is timezone ahead of GMT?  then subtract offset
783                          if ($tz_mod == '+') {        if ($tz_mod == '+') {
784                                  $offset_secs *= -1;          $offset_secs *= -1;
785                          }        }
786                          $epoch += $offset_secs;        $epoch += $offset_secs;
787                  }      }
788                  return $epoch;      return $epoch;
789          }    }
790          else {    else {
791                  return -1;      return -1;
792          }    }
793  }  }
794    
795  /**  /**
# Line 621  function planet_parse_w3cdtf($date_str) Line 801  function planet_parse_w3cdtf($date_str)
801   * @return UTF-8 string   * @return UTF-8 string
802   */   */
803  function planet_replace_num_entity($ord) {  function planet_replace_num_entity($ord) {
804          $ord = $ord[1];    $ord = $ord[1];
805          if (preg_match('/^x([0-9a-f]+)$/i', $ord, $match)) {    if (preg_match('/^x([0-9a-f]+)$/i', $ord, $match)) {
806                  $ord = hexdec($match[1]);      $ord = hexdec($match[1]);
807          }    }
808          else {    else {
809                  $ord = intval($ord);      $ord = intval($ord);
810          }    }
811    
812          $no_bytes = 0;    $no_bytes = 0;
813          $byte = array();    $byte = array();
814    
815          if ($ord == 128) {    if ($ord == 128) {
816                  return chr(226).chr(130).chr(172);      return chr(226) . chr(130) . chr(172);
817          }    }
818          else if($ord == 129) {    else if ($ord == 129) {
819                  return chr(239).chr(191).chr(189);      return chr(239) . chr(191) . chr(189);
820          }    }
821          else if($ord == 130) {    else if ($ord == 130) {
822                  return chr(226).chr(128).chr(154);      return chr(226) . chr(128) . chr(154);
823          }    }
824          else if($ord == 131) {    else if ($ord == 131) {
825                  return chr(198).chr(146);      return chr(198) . chr(146);
826          }    }
827          else if($ord == 132) {    else if ($ord == 132) {
828                  return chr(226).chr(128).chr(158);      return chr(226) . chr(128) . chr(158);
829          }    }
830          else if($ord == 133) {    else if ($ord == 133) {
831                  return chr(226).chr(128).chr(166);      return chr(226) . chr(128) . chr(166);
832          }    }
833          else if($ord == 134) {    else if ($ord == 134) {
834                  return chr(226).chr(128).chr(160);      return chr(226) . chr(128) . chr(160);
835          }    }
836          else if($ord == 135) {    else if ($ord == 135) {
837                  return chr(226).chr(128).chr(161);      return chr(226) . chr(128) . chr(161);
838          }    }
839          else if($ord == 136) {    else if ($ord == 136) {
840                  return chr(203).chr(134);      return chr(203) . chr(134);
841          }    }
842          else if($ord == 137) {    else if ($ord == 137) {
843                  return chr(226).chr(128).chr(176);      return chr(226) . chr(128) . chr(176);
844          }    }
845          else if($ord == 138) {    else if ($ord == 138) {
846                  return chr(197).chr(160);      return chr(197) . chr(160);
847          }    }
848          else if($ord == 139) {    else if ($ord == 139) {
849                  return chr(226).chr(128).chr(185);      return chr(226) . chr(128) . chr(185);
850          }    }
851          else if($ord == 140) {    else if ($ord == 140) {
852                  return chr(197).chr(146);      return chr(197) . chr(146);
853          }    }
854          else if($ord == 141) {    else if ($ord == 141) {
855                  return chr(239).chr(191).chr(189);      return chr(239) . chr(191) . chr(189);
856          }    }
857          else if($ord == 142) {    else if ($ord == 142) {
858                  return chr(197).chr(189);      return chr(197) . chr(189);
859          }    }
860          else if($ord == 143) {    else if ($ord == 143) {
861                  return chr(239).chr(191).chr(189);      return chr(239) . chr(191) . chr(189);
862          }    }
863          else if($ord == 144) {    else if ($ord == 144) {
864                  return chr(239).chr(191).chr(189);      return chr(239) . chr(191) . chr(189);
865          }    }
866          else if($ord == 145) {    else if ($ord == 145) {
867                  return chr(226).chr(128).chr(152);      return chr(226) . chr(128) . chr(152);
868          }    }
869          else if($ord == 146) {    else if ($ord == 146) {
870                  return chr(226).chr(128).chr(153);      return chr(226) . chr(128) . chr(153);
871          }    }
872          else if($ord == 147) {    else if ($ord == 147) {
873                  return chr(226).chr(128).chr(156);      return chr(226) . chr(128) . chr(156);
874          }    }
875          else if($ord == 148) {    else if ($ord == 148) {
876                  return chr(226).chr(128).chr(157);      return chr(226) . chr(128) . chr(157);
877          }    }
878          else if($ord == 149) {    else if ($ord == 149) {
879                  return chr(226).chr(128).chr(162);      return chr(226) . chr(128) . chr(162);
880          }    }
881          else if($ord == 150) {    else if ($ord == 150) {
882                  return chr(226).chr(128).chr(147);      return chr(226) . chr(128) . chr(147);
883          }    }
884          else if($ord == 151) {    else if ($ord == 151) {
885                  return chr(226).chr(128).chr(148);      return chr(226) . chr(128) . chr(148);
886          }    }
887          else if($ord == 152) {    else if ($ord == 152) {
888                  return chr(203).chr(156);      return chr(203) . chr(156);
889          }    }
890          else if($ord == 153) {    else if ($ord == 153) {
891                  return chr(226).chr(132).chr(162);      return chr(226) . chr(132) . chr(162);
892          }    }
893          else if($ord == 154) {    else if ($ord == 154) {
894                  return chr(197).chr(161);      return chr(197) . chr(161);
895          }    }
896          else if($ord == 155) {    else if ($ord == 155) {
897                  return chr(226).chr(128).chr(186);      return chr(226) . chr(128) . chr(186);
898          }    }
899          else if($ord == 156) {    else if ($ord == 156) {
900                  return chr(197).chr(147);      return chr(197) . chr(147);
901          }    }
902          else if($ord == 157) {    else if ($ord == 157) {
903                  return chr(239).chr(191).chr(189);      return chr(239) . chr(191) . chr(189);
904          }    }
905          else if($ord == 158) {    else if ($ord == 158) {
906                  return chr(197).chr(190);      return chr(197) . chr(190);
907          }    }
908          else if($ord == 159) {    else if ($ord == 159) {
909                  return chr(197).chr(184);      return chr(197) . chr(184);
910          }    }
911          else if($ord == 160) {    else if ($ord == 160) {
912                  return chr(194).chr(160);      return chr(194) . chr(160);
913          }    }
914    
915          if ($ord < 128) {    if ($ord < 128) {
916                  return chr($ord);      return chr($ord);
917          }    }
918          else if ($ord < 2048) {    else if ($ord < 2048) {
919                  $no_bytes = 2;      $no_bytes = 2;
920          }    }
921          else if ($ord < 65536) {    else if ($ord < 65536) {
922                  $no_bytes = 3;      $no_bytes = 3;
923          }    }
924          else if ($ord < 1114112) {    else if ($ord < 1114112) {
925                  $no_bytes = 4;      $no_bytes = 4;
926          }    }
927          else {    else {
928                  return;      return;
929          }    }
930    
931          switch ($no_bytes) {    switch ($no_bytes) {
932                  case 2:      case 2:
933                          $prefix = array(31, 192);        $prefix = array(31, 192);
934                          break;        break;
935    
936                  case 3:      case 3:
937                          $prefix = array(15, 224);        $prefix = array(15, 224);
938                          break;        break;
939    
940                  case 4:      case 4:
941                          $prefix = array(7, 240);        $prefix = array(7, 240);
942                          break;        break;
943          }    }
944    
945          for ($i = 0; $i < $no_bytes; $i++) {    for ($i = 0; $i < $no_bytes; $i++) {
946                  $byte[$no_bytes - $i - 1] = (($ord & (63 * pow(2, 6 * $i))) / pow(2, 6 * $i)) & 63 | 128;      $byte[$no_bytes - $i - 1] = (($ord & (63 * pow(2, 6 * $i))) / pow(2, 6 * $i)) & 63 | 128;
947          }    }
948    
949          $byte[0] = ($byte[0] & $prefix[0]) | $prefix[1];    $byte[0] = ($byte[0] & $prefix[0]) | $prefix[1];
950    
951          $ret = '';    $ret = '';
952          for ($i = 0; $i < $no_bytes; $i++) {    for ($i = 0; $i < $no_bytes; $i++) {
953                  $ret .= chr($byte[$i]);      $ret .= chr($byte[$i]);
954          }    }
955    
956          return $ret;    return $ret;
957  }  }
958    
959  /**  /**
# Line 781  function planet_replace_num_entity($ord) Line 961  function planet_replace_num_entity($ord)
961   * from: http://pl2.php.net/manual/en/function.html-entity-decode.php#51722   * from: http://pl2.php.net/manual/en/function.html-entity-decode.php#51722
962   */   */
963  function planet_replace_name_entities(&$text) {  function planet_replace_name_entities(&$text) {
964          static $ttr;    static $ttr;
965          if (!$ttr) {    if (!$ttr) {
966                  $trans_tbl = get_html_translation_table(HTML_ENTITIES);      $trans_tbl = get_html_translation_table(HTML_ENTITIES);
967                  foreach ($trans_tbl as $k => $v) {      foreach ($trans_tbl as $k => $v) {
968                          $ttr[$v] = utf8_encode($k);        $ttr[$v] = utf8_encode($k);
969                  }      }
970                  $ttr['&apos;'] = "'";      $ttr['&apos;'] = "'";
971          }    }
972          return strtr($text, $ttr);    return strtr($text, $ttr);
973  }  }