~m-baert/planet-drupal/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
<?php

define('PLANET_ADMIN', 'administer planet');

function planet_node_info() {
        return array('planet' => array('name' => t('planet'), 'base' => 'planet'));
} 

function planet_perm() {
	return array(PLANET_ADMIN);
}

function planet_help($section){
	switch($section){
		case 'admin/help/planet':
			$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>To use planet, go to admin/settings/planet and note the following sections:</p>';
			$output .= '<ul>';
			$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 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>';
			$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>';
			$output .= '</ul>';
			return $output;
		case 'admin/modules#description':
			return t('Aggregates RSS feeds and faciliates their association with site users who belong to a given role.');
	}
}

function planet_node_name(){
	return 'planet';
}

function planet_access($op, $node){
	global $user;

	if ($op == 'create') {
		return user_access('edit own blog') && $user->uid;
	}

	if ($op == 'update' || $op == 'delete') {
		if (user_access('edit own blog') && ($user->uid == $node->uid)) {
			return TRUE;
		}
	}
}

function planet_menu($may_cache){
       global $user;
	$items = array();
	if($may_cache){
	
	}
	
	$items[] = array('path' => 'admin/settings/planet', 'title' => t('planet settings'),
      'callback' => '_planet_settings', 'access' => user_access('administer nodes'),
      'type' => MENU_NORMAL_ITEM);


    if(arg(0) == 'planet' && is_numeric(arg(1))){
      $items[] = array('path' => 'planet/' . arg(1), 'title' => 'planet', 'callback' => 'planet_page_user', 'callback arguments' => array(arg(1)));
    }
    
    if(arg(3) == 'refresh' && is_numeric(arg(4))){
    	$items[] = array('path' => 'admin/settings/planet/refresh/' . arg(4), 'title' => t('planet refresh'),
      		'callback' => 'planet_call_refresh', 'access' => user_access('administer nodes'),
      		'type' => MENU_CALLBACK);
    }
    
    if(is_numeric(arg(4)) && (arg(3) == 'freeze' || arg(3) == 'unfreeze')){
    	$items[] = array('path' => 'admin/settings/planet/' . arg(3). '/' . arg(4), 'title' => t('planet freeze'),
      		'callback' => 'planet_toggle_frozen', 'access' => user_access('administer nodes'),
      		'type' => MENU_CALLBACK);
    }
    
    if(is_numeric(arg(4)) && arg(3) == 'convert'){
    	$items[] = array('path' => 'admin/settings/planet/convert/' . arg(4), 'title' => t('planet convert'),
      		'callback' => 'planet_convert_to_blog', 'access' => user_access('administer nodes'),
      		'type' => MENU_CALLBACK);
    }

    $items[] = array('path' => 'planet', 'title' => t('Planet'),
      'callback' => 'planet_page_last', 'access' => user_access('access content'),
      'type' => MENU_CALLBACK);
      
    $items[] = array('path' => 'planet/feed', 'title' => t('Planet'),
      'callback' => 'planet_feed', 'access' => user_access('access content'),
      'type' => MENU_CALLBACK);
      
	return $items;
}

function planet_call_refresh(){
	$title = planet_refresh();
	watchdog('planet', 'Feed "' . $title . '" refreshed.');
	drupal_set_message('Feed "' . $title . '" refreshed.');
	drupal_goto('admin/settings/planet');
}

function planet_toggle_frozen(){
	$fid = intval(arg(4));
	db_query('UPDATE {planet_feeds} SET frozen = %d WHERE fid = %d', arg(3) == 'unfreeze' ? 0 : 1, $fid);
	drupal_set_message('Feed ' . (arg(3) == 'unfreeze' ? 'un' : '') . 'frozen.');
	drupal_goto('admin/settings/planet');
}

function _planet_settings(){
	if($_POST['edit']){	
		$edit = $_POST['edit'];
		
		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']);
				}
				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 .= planet_feed_form($edit, true);
		}
		else{
		
			$roles = array();

			$result = db_query('SELECT rid, name FROM {role}');
			while($role = db_fetch_object($result)){
				$roles[$role->rid] = $role->name;
			}

			$output .= '<h2>Recent Items</h2>';
			$output .= planet_queue();
			
			$form = array();

			$form['general'] = array('#type' => 'fieldset', '#title' => t('General Settings'));
		
			$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' => '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']['submit'] = array('#type' => 'submit', '#value' => 'Adjust Settings');
			
			$output .= drupal_get_form('settings', $form);
			//$output .= $form;

			$output .= planet_feed_form($edit);
		
			$result = db_query('SELECT *, (UNIX_TIMESTAMP(NOW()) - checked) _checked FROM {planet_feeds}');
			$result = db_query('SELECT COUNT(f.uid) 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.uid;');
			$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);		
	}
}

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['title']);
	$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');
	$output .= drupal_get_form('settings',$form);
	
	if($individual){
		$output .= planet_queue(intval($edit['uid']));
	}
	
	return $output;
}

function planet_queue($uid = null){
	$rows = array();
	$headers = array('Title', 'Created', 'Convert');
	
	if($uid > 0){
		$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);
	}
	else{
		$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);	
	}
	
	while($node = db_fetch_object($result)){
		array_push($rows, 	array(
								l($node->title, 'node/' . $node->nid),
								format_date($node->created, 'custom', 'Y-m-d H:i'),
								l('convert', 'admin/settings/planet/convert/' . $node->nid)
							)
		);
	}
	$output .= theme('table',$headers, $rows);
	$output .= theme('pager', NULL, variable_get('default_nodes_main', 10));
	return $output;
}


function planet_cron(){
	$result = db_query('SELECT fid FROM {planet_feeds} WHERE frozen = 0');
	while($feed = db_fetch_object($result)){
		$title = planet_refresh($feed->fid);
		watchdog('planet', 'Cron updated feed "' . $title . '".');
	}
}

function planet_refresh($fid = null){
	if(!$fid){
		$fid = intval(arg(4));
	}
	
	$feed = db_fetch_object(db_query('SELECT * FROM {planet_feeds} WHERE fid = %d', $fid));
	
	$headers = array();
	$result = planet_http_request($feed->link, $headers, 15);	
	
	switch ($result->code) {
		case 304:
			drupal_set_message(t('No new content syndicated from %site.', array('%site' => '<em>'. $feed->title .'</em>')));
			break;

		case 301:
			if ($result->redirect_url) {
				$feed->link = $result->redirect_url;
				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));
				db_query("UPDATE {planet_feeds} SET link = '%s' WHERE fid = %d", $feed->link, $feed->fid);
			}
			break;

		case 200:
		case 302:
		case 307:
			$xml_tree = planet_parse_xml($result->data);

			if ($xml_tree['parser_error']) {
				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);
				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');
				break;
			}
			else {
				drupal_set_message('Parsing feed '. $feed->title .' took '. $xml_tree['parser_time'] .' seconds.');
			}

			if (planet_parse_items($xml_tree, $feed) !== false){
				if ($result->headers['Last-Modified']) {
					$modified = strtotime($result->headers['Last-Modified']);
				}

				/*
				** Prepare data:
				*/
				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));
}

/**
 * Let admin users convert nodes to blog posts.
 */
function planet_convert_to_blog($nid = NULL){
	if(user_access('administer nodes')){
		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');
		}
	}
}


/**
 * Private function; Parse HTTP headers from data retreived with cURL
 * from: http://pl2.php.net/manual/en/function.curl-setopt.php#42009
 */
function planet_parse_response($response){
	/*
	 ***original code extracted from examples at
	 ***http://www.webreference.com/programming
													 /php/cookbook/chap11/1/3.html

	 ***returns an array in the following format which varies depending on headers returned

			 [0] => the HTTP error or response code such as 404
			 [1] => Array
			 (
					 [Server] => Microsoft-IIS/5.0
					 [Date] => Wed, 28 Apr 2004 23:29:20 GMT
					 [X-Powered-By] => ASP.NET
					 [Connection] => close
					 [Set-Cookie] => COOKIESTUFF
					 [Expires] => Thu, 01 Dec 1994 16:00:00 GMT
					 [Content-Type] => text/html
					 [Content-Length] => 4040
			 )
			 [2] => Response body (string)
	*/

	do {
		list($response_headers, $response) = explode("\r\n\r\n", $response, 2);
		$response_header_lines = explode("\r\n", $response_headers);

		// first line of headers is the HTTP response code
		$http_response_line = array_shift($response_header_lines);
		if (preg_match('@^HTTP/[0-9]\.[0-9] ([0-9]{3})@', $http_response_line, $matches)) {
			$response_code = $matches[1];
		}
		else {
			$response_code = "Error";
		}
	}
	while (substr($response_code, 0, 1) == "1");

	$response_body = $response;
				
	// put the rest of the headers in an array
	$response_header_array = array();
	foreach ($response_header_lines as $header_line) {
		list($header, $value) = explode(':', $header_line, 2);
		$response_header_array[$header] = trim($value);
	}

	return array($response_code, $response_header_array, $response_body, $http_response_line);
}

/**
 * Private function; Gets data from given URL :)
 */
function planet_http_request($url, $headers = array(), $timeout = 15, $method = 'GET', $data = NULL, $follow = 3) {
	if (!function_exists('curl_init')) {
		return drupal_http_request($url, $headers, $method, $data, $follow);
	}

	// convert headers array to format used by cURL
	$temp = array();
	foreach ($headers as $header => $value) {
		$temp[] = $header .': '. $value;
	}
	$headers = $temp;

	$result = new StdClass();

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

	$data = curl_exec($ch);
	$info = curl_getinfo($ch);

	curl_close($ch);
	unset($ch);

	$response = planet_parse_response($data);
	$result->code = $response[0];
	$result->headers = $response[1];
	$result->data = $response[2];
	$error = $response[3];
	switch ($code) {
		case 200: // OK
		case 304: // Not modified
			break;
		case 301: // Moved permanently
		case 302: // Moved temporarily
		case 307: // Moved temporarily
			$location = $result->headers['Location'];

			if ($follow) {
				$result = planet_http_request($result->headers['Location'], $headers, $timeout, $method, $data, --$follow);
				$result->redirect_code = $result->code;
			}
			$result->redirect_url = $location;
			break;
		default:
			$result->error = $error;
			break;
	}

	$result->code = $response[0];
	return $result;
}

/**
 * Private function; Checks a news feed for new items.
 */


/**
 * Private function;
 * Parse the W3C date/time format, a subset of ISO 8601. PHP date parsing
 * functions do not handle this format.
 * See http://www.w3.org/TR/NOTE-datetime for more information.
 * Origionally from MagpieRSS (http://magpierss.sourceforge.net/).
 *
 * @param $date_str A string with a potentially W3C DTF date.
 * @return A timestamp if parsed successfully or -1 if not.
 */
function planet_parse_w3cdtf($date_str) {
	if (preg_match('/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/', $date_str, $match)) {
		list($year, $month, $day, $hours, $minutes, $seconds) = array($match[1], $match[2], $match[3], $match[4], $match[5], $match[6]);
		// calc epoch for current date assuming GMT
		$epoch = gmmktime($hours, $minutes, $seconds, $month, $day, $year);
		if ($match[10] != 'Z') { // Z is zulu time, aka GMT
			list($tz_mod, $tz_hour, $tz_min) = array($match[8], $match[9], $match[10]);
			// zero out the variables
			if (!$tz_hour) {
				$tz_hour = 0;
			}
			if (!$tz_min) {
				$tz_min = 0;
			}
			$offset_secs = (($tz_hour * 60) + $tz_min) * 60;
			// is timezone ahead of GMT?	then subtract offset
			if ($tz_mod == '+') {
				$offset_secs *= -1;
			}
			$epoch += $offset_secs;
		}
		return $epoch;
	}
	else {
		return -1;
	}
}

/**
 * Private function;
 * from: http://pl2.php.net/manual/en/function.html-entity-decode.php#51055
 * Used as callback function for preg_replace_all() to decode numeric entities to UTF-8 chars
 *
 * @param $ord Number
 * @return UTF-8 string
 */
function planet_replace_num_entity($ord) {
	$ord = $ord[1];
	if (preg_match('/^x([0-9a-f]+)$/i', $ord, $match)) {
		$ord = hexdec($match[1]);
	}
	else {
		$ord = intval($ord);
	}

	$no_bytes = 0;
	$byte = array();

	if ($ord == 128) {
		return chr(226).chr(130).chr(172);
	}
	else if($ord == 129) {
		return chr(239).chr(191).chr(189);
	}
	else if($ord == 130) {
		return chr(226).chr(128).chr(154);
	}
	else if($ord == 131) {
		return chr(198).chr(146);
	}
	else if($ord == 132) {
		return chr(226).chr(128).chr(158);
	}
	else if($ord == 133) {
		return chr(226).chr(128).chr(166);
	}
	else if($ord == 134) {
		return chr(226).chr(128).chr(160);
	}
	else if($ord == 135) {
		return chr(226).chr(128).chr(161);
	}
	else if($ord == 136) {
		return chr(203).chr(134);
	}
	else if($ord == 137) {
		return chr(226).chr(128).chr(176);
	}
	else if($ord == 138) {
		return chr(197).chr(160);
	}
	else if($ord == 139) {
		return chr(226).chr(128).chr(185);
	}
	else if($ord == 140) {
		return chr(197).chr(146);
	}
	else if($ord == 141) {
		return chr(239).chr(191).chr(189);
	}
	else if($ord == 142) {
		return chr(197).chr(189);
	}
	else if($ord == 143) {
		return chr(239).chr(191).chr(189);
	}
	else if($ord == 144) {
		return chr(239).chr(191).chr(189);
	}
	else if($ord == 145) {
		return chr(226).chr(128).chr(152);
	}
	else if($ord == 146) {
		return chr(226).chr(128).chr(153);
	}
	else if($ord == 147) {
		return chr(226).chr(128).chr(156);
	}
	else if($ord == 148) {
		return chr(226).chr(128).chr(157);
	}
	else if($ord == 149) {
		return chr(226).chr(128).chr(162);
	}
	else if($ord == 150) {
		return chr(226).chr(128).chr(147);
	}
	else if($ord == 151) {
		return chr(226).chr(128).chr(148);
	}
	else if($ord == 152) {
		return chr(203).chr(156);
	}
	else if($ord == 153) {
		return chr(226).chr(132).chr(162);
	}
	else if($ord == 154) {
		return chr(197).chr(161);
	}
	else if($ord == 155) {
		return chr(226).chr(128).chr(186);
	}
	else if($ord == 156) {
		return chr(197).chr(147);
	}
	else if($ord == 157) {
		return chr(239).chr(191).chr(189);
	}
	else if($ord == 158) {
		return chr(197).chr(190);
	}
	else if($ord == 159) {
		return chr(197).chr(184);
	}
	else if($ord == 160) {
		return chr(194).chr(160);
	}

	if ($ord < 128) {
		return chr($ord);
	}
	else if ($ord < 2048) {
		$no_bytes = 2;
	}
	else if ($ord < 65536) {
		$no_bytes = 3;
	}
	else if ($ord < 1114112) {
		$no_bytes = 4;
	}
	else {
		return;
	}

	switch ($no_bytes) {
		case 2:
			$prefix = array(31, 192);
			break;

		case 3:
			$prefix = array(15, 224);
			break;

		case 4:
			$prefix = array(7, 240);
			break;
	}

	for ($i = 0; $i < $no_bytes; $i++) {
		$byte[$no_bytes - $i - 1] = (($ord & (63 * pow(2, 6 * $i))) / pow(2, 6 * $i)) & 63 | 128;
	}

	$byte[0] = ($byte[0] & $prefix[0]) | $prefix[1];

	$ret = '';
	for ($i = 0; $i < $no_bytes; $i++) {
		$ret .= chr($byte[$i]);
	}

	return $ret;
}

/**
 * Private function; Convert named entities to UTF-8 characters
 * from: http://pl2.php.net/manual/en/function.html-entity-decode.php#51722
 */
function planet_replace_name_entities(&$text) {
	static $ttr;
	if (!$ttr) {
		$trans_tbl = get_html_translation_table(HTML_ENTITIES);
		foreach ($trans_tbl as $k => $v) {
			$ttr[$v] = utf8_encode($k);
		}
		$ttr['&apos;'] = "'";
	}
	return strtr($text, $ttr);
}

/**
 * Private function; Convert all entities to UTF-8 characters
 */
function planet_replace_entities(&$text) {
	$result = planet_replace_name_entities($text);
	return preg_replace_callback('/&#([0-9a-fx]+);/mi', 'planet_replace_num_entity', $result);
}

/**
 * Private function; Clone object function to stay compatible with both php4 and php5
 * from: Drupal 4.7CVS
 * TODO: remove after moving to Drupal 4.7
 */
function planet_clone($object) {
	return version_compare(phpversion(), '5.0') < 0 ? $object : clone($object);
}

/**
 * Private function; Convert relative URLs
 */
function planet_convert_relative_urls(&$data, $base_url) {
	$src = '%( href| src)="(?!\w+://)/?([^"]*)"%';
	$dst = '$1="'. trim($base_url, '/') .'/$2"';
	return preg_replace($src, $dst, $data);
}

/**
 * Private function; Creates nodes from data found in given xml_tree
 */
function planet_parse_items(&$xml_tree, &$feed) {

	if ($xml_tree['RSS']) { // RSS 0.91, 0.92, 2.0
		$items = &$xml_tree['RSS'][0]['CHANNEL'][0]['ITEM'];
		$link_field = 'VALUE';
	}
	else if ($xml_tree['RDF:RDF']) {
		$items = &$xml_tree['RDF:RDF'][0]['ITEM'];
		$link_field = 'VALUE';
	}
	else if ($xml_tree['FEED']) { // Atom 0.3, 1.0
		$items = &$xml_tree['FEED'][0]['ENTRY'];
		$link_field = 'HREF';
	}
	else if ($xml_tree['CHANNEL']) { // RSS 1.1
		$items = &$xml_tree['CHANNEL'][0]['ITEMS'][0]['ITEM'];
		$link_field = 'VALUE';
	}
	else {
		// unsupported format
		$items = array();
		return false;
	}

	/*
	** We reverse the array such that we store the first item last,
	** and the last item first. In the database, the newest item
	** should be at the top.
	*/
	$items_added = 0;
	$auto_publish = variable_get('planet_auto_publish', '');				


	for ($index = count($items) - 1; $index >= 0; $index--) {
		$item = &$items[$index];
	//print '<pre>' . print_r($item, 1) . '</pre>';
		$teaser = NULL;
		$body = NULL;

		// Description field is needed early for case when no title is specified
		if ($item['DESCRIPTION']) { // RSS 0.91, 0.92, 1.0, 1.1, 2.0
			$body = &$item['DESCRIPTION'][0]['VALUE'];
		}
		else if ($item['SUMMARY']) { // Atom 0.3, 1.0
			$body = &$item['SUMMARY'][0]['VALUE'];
		}
		
		if ($item['CONTENT']) { // Atom 0.3, 1.0
			if (strlen($body) < strlen($item['CONTENT'][0]['VALUE'])) {
				if ($body) {
					$teaser = $body;
				}
				$body = &$item['CONTENT'][0]['VALUE'];
			}
		}
		else if ($item['CONTENT:ENCODED']) { // Don't know where it came from but it can be found in RSS 2.0 feeds
			if (strlen($body) < strlen($item['CONTENT:ENCODED'][0]['VALUE'])) {
				if ($body) {
					$teaser = $body;
				}
				$body = &$item['CONTENT:ENCODED'][0]['VALUE'];
			}
		}
		
		/*
		** Resolve the item's title. If no title is found, we use
		** up to 40 characters of the description ending at a word
		** boundary but not splitting potential entities.
		*/
		if (!($title = $item['TITLE'][0]['VALUE'])) {
			$title = preg_replace('/^(.*)[^\w;&].*?$/', "\\1", truncate_utf8($body, 40));
		}

		// If title was "escaped" then it may still contain entities, becuase each & from entity was also escabet to &amp; before
		// TODO: the same for content?
		if ($item['TITLE'][0]['MODE'] == 'escaped') {
			$title = feeds_replace_entities($title);
		}
		$title = strip_tags($title);

		/*
		** Resolve the items link.
		*/
		if ($item['LINK']) {
			// TODO: remove this Atom hack when we have field mapping or at least specialized parsers in place
			if (count($item['LINK']) > 1) {
				$link = $feed->link;
				foreach ($item['LINK'] as $temp) {
					if ($temp['REL'] == 'alternate') {
						$link = $temp[$link_field];
					}
				}
			}
			else {
				$link = $item['LINK'][0][$link_field];
			}
		}
		elseif ($item['GUID'] && (strncmp($item['GUID'][0][$link_field], 'http://', 7) == 0) && $item['GUID'][0]['ISPERMALINK'] != 'false') {
			$link = $item['GUID'][0][$link_field];
		}
		else {
			$link = $feed->link;
		}

		/*
		** Resolve the items source.
		*/
		if ($item['SOURCE'][0]['VALUE'] && $item['SOURCE'][0]['URL']) { // RSS 2.0
			$source_title = &$item['SOURCE'][0]['VALUE'];
			$source_link = &$item['SOURCE'][0]['URL'];
		}
		else if ($item['SOURCE'] || $item['ATOM:SOURCE']) { // ATOM 1.0
			if ($item['SOURCE'][0]['TITLE']) $source_title = &$item['SOURCE'][0]['TITLE'][0]['VALUE'];
			else if ($item['SOURCE'][0]['ATOM:TITLE']) $source_title = &$item['SOURCE'][0]['ATOM:TITLE'][0]['VALUE'];
			if ($item['SOURCE'][0]['LINK']) $source_link = &$item['SOURCE'][0]['LINK'][0]['VALUE'];
			else if ($item['SOURCE'][0]['ATOM:LINK']) $source_link = &$item['SOURCE'][0]['ATOM:LINK'][0]['VALUE'];
		}
		else {
			$source_title = '';
			$source_link = '';
		}

		/*
		** Try to resolve and parse the item's publication date.	If no
		** date is found, we use the current date instead.
		*/
		// TODO: find nicer way for handling namespaces ;)
		if ($item['PUBDATE']) $date = $item['PUBDATE'][0]['VALUE'];												// RSS 2.0
		else if ($item['DC:DATE']) $date = $item['DC:DATE'][0]['VALUE'];									 // Dublin core
		else if ($item['DATE']) $date = $item['DATE'][0]['VALUE'];												 // Dublin core
		else if ($item['DCTERMS:ISSUED']) $date = $item['DCTERMS:ISSUED'][0]['VALUE'];		 // Dublin core
		else if ($item['ISSUED']) $date = $item['ISSUED'][0]['VALUE'];										 // Dublin core
		else if ($item['DCTERMS:CREATED']) $date = $item['DCTERMS:CREATED'][0]['VALUE'];	 // Dublin core
		else if ($item['CREATED']) $date = $item['CREATED'][0]['VALUE'];									 // Dublin core
		else if ($item['DCTERMS:MODIFIED']) $date = $item['DCTERMS:MODIFIED'][0]['VALUE']; // Dublin core
		else if ($item['MODIFIED']) $date = $item['MODIFIED'][0]['VALUE'];								 // Dublin core
		else if ($item['ATOM:UPDATED']) $date = $item['ATOM:UPDATED'][0]['VALUE'];				 // Atom
		else if ($item['UPDATED']) $date = $item['UPDATED'][0]['VALUE'];									 // Atom
		else $date = 'now';

		if ($feed->item_date_source == FEEDS_ITEM_DATE_SNIFFED && $date) {
			$timestamp = strtotime($date); // strtotime() returns -1 on failure
			if ($timestamp < 0) {
				$timestamp = planet_parse_w3cdtf($date); // also returns -1 on failure
				if ($timestamp < 0) {
					$timestamp = time(); // better than nothing
				}
			}
		}
		else {
			$timestamp = time();
		}

		// Ignore items older than allowed for feed
		if ($timestamp < $time_horizont) {
			continue;
		}

		/*
		** Save this item. Try to avoid duplicate entries as much as
		** possible. If we find a duplicate entry, we resolve it and
		** pass along it's ID such that we can update it if needed.
		*/
		// Try to use RSS:GUID/ATOM:ID as unique identifier
		$guid = '';
		if ($item['GUID'][0]['VALUE']) { // RSS 2.0
			$guid = $item['GUID'][0]['VALUE'];
		}
		else if ($item['ATOM:ID'][0]['VALUE']) { // ATOM 0.3, 1.0
			$guid = $item['ATOM:ID'][0]['VALUE'];
		}
		else if ($item['ID'][0]['VALUE']) { // ATOM 0.3, 1.0
			$guid = $item['ID'][0]['VALUE'];
		}
		else{
			// feed may contain duplicated links for different items, so we try to generate unique ID for each item
			$guid = md5("$title - . " . $feed->fid);
		}
		// TODO: is there anyway to check if DC:IDENTIFIER is unique?
		//			 http://dublincore.org/documents/usageguide/elements.shtml says it can be non-unique so useles for us :(			

		$entry = NULL;
		if ($guid && strlen($guid) > 0) {
			$entry = db_fetch_object(db_query("SELECT nid FROM {planet_items} WHERE guid = '%s' AND fid = %d", $guid, $feed->fid));
		}
		else if ($link && $link != $feed->link && $link != $feed->url) {
			$entry = db_fetch_object(db_query("SELECT nid FROM {planet_items} WHERE guid = '%s' AND fid = %d", $link, $feed->fid));
		}
		else {
			$entry = db_fetch_object(db_query("SELECT ai.nid AS nid FROM {node} n, {planet_items} ai WHERE ai.fid = %d AND ai.nid = n.nid AND n.title = '%s'", $feed->fid, $title));
		}
		
		//print $guid . '<br />';
		//print $entry->nid . '<br />';
		// Ignore items already existing in database and not allowed to be updated

		//Fields to update in either case
		$entry->changed = strtotime($date);
		$entry->title = $title;
		$entry->body = $body;
		$entry->body = planet_convert_relative_urls($body, $link);
		$entry->teaser = node_teaser($entry->body);		

		// Check for an auto-publish string in the post and publish if applicable.
		$has_category = false;
		if($auto_publish != ''){
			$has_category = false;
			if($item['CATEGORY']){
				foreach($item['CATEGORY'] as $cat){
					if($cat['VALUE'] == $auto_publish){
						$has_category = true;
					}	
				}	
			}
		}
		//end auto-publish

		//Fields to set if it's a new item.		
		if(!isset($entry->nid)){						
			$entry->type = 'planet';
			if($has_category == true || preg_match('/' . $auto_publish . '/',$entry->body)){							
				$entry->type = 'blog';
			}			

			$options = variable_get('node_options_planet', array());

			$entry->uid = $feed->uid;
			$entry->status = 1;
			$entry->moderate = 0;
			$entry->promote = in_array('promote', $options) ? 1 : 0;
			$entry->sticky = in_array('sticky', $options) ? 1 : 0;
			$entry->comment = in_array('comment', $options) ? 2 : 0;
			$entry->format = 3;
			$entry->created = strtotime($date);
			
			$terms = module_invoke('taxonomy', 'node_get_terms', $edit->nid, 'tid');
			foreach ($terms as $tid => $term) {
				if ($term->tid) {
					$edit->taxonomy[] = $term->tid;
				}
			}
			node_save($entry);
			db_query('INSERT INTO {planet_items} (fid, nid, guid, created) VALUES(%d, %d, "%s", UNIX_TIMESTAMP(NOW()))', $feed->fid, $entry->nid, $guid);							
			watchdog('planet', 'Adding ' . $title);
			drupal_set_message('Adding ' . $title);
		}	
		else{
			if($entry->status == 1){
				if($has_category == true || preg_match('/' . $auto_publish . '/',$entry->body)){							
					$entry->type = 'blog';
				}
				node_save($entry);
				watchdog('planet', 'Updating ' . $title);
				drupal_set_message('Updating ' . $title);
			}
		}
	}

	return $items_added;
}


/**
 * Private function; parses given XML data and returns array
 */
function planet_parse_xml(&$data) {
	global $xml_tree, $xml_paths, $xml_path_cur;
	$xml_tree = array();
	$xml_paths[] = &$xml_tree;
	$xml_path_cur = 0;

	$_start = microtime();

	// Some feeds already use CDATA but in "wrong way": http://www.rocketboom.com/vlog/quicktime_daily_enclosures.xml (ie. <description> something <CDATA soemthing else></description>
	$data = trim(str_replace(array('<![CDATA[', ']]>'), '', $data));
	
	// Add CDATA around content which may contain (x)html data, and is not contained in CDATA yet
	$src = array(
		'%(<(link|content|content:encoded|description|title|summary|info|tagline|copyright|source|itunes:summary|media:text|text)(?>[^<]*(?<!/)>)(?!<!\[CDATA\[))(.*)(</\2>)%sUS',
		'%24:(\d\d:\d\d)%' // workaround buggy hour format in feeds
		/*'%(<(\w+)(?>[^<]*type=")(?:text/html|application/xhtml\+xml|html|xhtml")(?>[^<]*(?<!/)>)(?!<!\[CDATA\[))(.*)(</\2>)%sUS'*/
		);
	$dst = array(
		'$1<![CDATA[$3]]>$4',
		'00:$1'
		);
	$data = preg_replace($src, $dst, $data);

	// parse the data:
	$xml_parser = drupal_xml_parser_create($data);
	if ($xml_parser == NULL) {
		return $xml_tree;
	}

	xml_set_element_handler($xml_parser, 'planet_element_start', 'planet_element_end');
	xml_set_character_data_handler($xml_parser, 'planet_element_data');
	xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1);
	xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 1);
	if (!xml_parse($xml_parser, $data, 1)) {
		$xml_tree['parser_error'] = xml_error_string(xml_get_error_code($xml_parser));
		$xml_tree['parser_line'] = xml_get_current_line_number($xml_parser);
	}
	else {
			 unset($xml_tree['parser_error']);
			 unset($xml_tree['parser_line']);
	}
	xml_parser_free($xml_parser);

	$_end = microtime();

	list($sec, $usec) = explode(' ', $_start);
	$_start = $sec + $usec;
	list($sec, $usec) = explode(' ', $_end);
	$xml_tree['parser_time'] = ($sec + $usec) - $_start;

	return $xml_tree;
}

/**
 * Private call-back function used by the XML parser.
 */
function planet_element_start($parser, $name, $attributes) {
	global $xml_tree, $xml_paths, $xml_path_cur;

	$temp = &$xml_paths[$xml_path_cur++];
	$temp[$name][] = $attributes;
	$xml_paths[$xml_path_cur] = &$temp[$name][count($temp[$name])-1];
}

/**
 * Private call-back function used by the XML parser.
 */
function planet_element_end($parser, $name) {
	global $xml_tree, $xml_paths, $xml_path_cur;

	$temp = &$xml_paths[$xml_path_cur];
	array_pop($xml_paths);
	$xml_path_cur--;
	if (isset($temp['VALUE'])) {
		$temp['VALUE'] = trim(planet_replace_entities($temp['VALUE']));
	}
}

/**
 * Private call-back function used by the XML parser.
 */
function planet_element_data($parser, $data) {
	global $xml_tree, $xml_paths, $xml_path_cur;

	$temp = trim($data);
	if (strlen($temp) > 0) {
		$temp = &$xml_paths[$xml_path_cur];
		$temp['VALUE'] .= $data;
	}
}

function planet_page_last() {
  global $user;

  $output = '';

  $result = pager_query(db_rewrite_sql("SELECT n.nid, n.created FROM {node} n WHERE n.type = 'planet' AND n.status = 1 ORDER BY n.created DESC"), variable_get('default_nodes_main', 10));

  while ($node = db_fetch_object($result)) {
	$node = node_load($node->nid);
	$node->type = 'blog';
	$output .= node_view($node);
  }
  $output .= theme('pager', NULL, variable_get('default_nodes_main', 10));
  $output .= theme('xml_icon', url('blog/feed'));

  drupal_add_link(array('rel' => 'alternate',
                        'type' => 'application/rss+xml',
                        'title' => t('RSS - blogs'),
                        'href' => url("blog/feed")));
  print theme('page', $output);
}

function planet_feed() {
  $result = db_query_range(db_rewrite_sql("SELECT n.nid, n.title, n.body teaser, n.created, u.name, u.uid FROM {node} n INNER JOIN {users} u ON n.uid = u.uid WHERE n.type = 'planet' AND n.status = 1 ORDER BY n.created DESC"), 0, 15);
  //$channel['title'] = variable_get('site_name', 'drupal') .' blogs';
  $channel['title'] = 'Planet Blog';
  $channel['link'] = url('planet', NULL, NULL, TRUE);
  $channel['description'] = 'Planet feed';
  node_feed($result, $channel);
}

/**
 * Implementation of hook_user().
 */
function planet_user($type, &$edit, &$user) {
  if ($type == 'view' && user_access('edit own blog', $user)) {
    $items[] = array('title' => t('Planet'),
      'value' => l(t('view recent planet entries'), "planet/$user->uid", array('title' => t("Read %username's latest planet entries.", array('%username' => $user->name)))),
      'class' => 'planet',
    );
    return array(t('History') => $items);
  }
}

/**
 * Menu callback; displays a Drupal page containing recent planet entries.
 */
function planet_page($a = NULL, $b = NULL) {

  if (is_numeric($a)) { // $a is a user ID
    if ($b == 'feed') {
      return planet_feed_user($a);
    }
    else {
      return planet_page_user($a);
    }
  }
  else if ($a == 'feed') {
    return planet_feed_last();
  }
  else {
    return planet_page_last();
  }
}

function planet_page_user($uid) {
  global $user;

  $account = user_load(array((is_numeric($uid) ? 'uid' : 'name') => $uid, 'status' => 1));

  if ($account->uid) {
    drupal_set_title($title = t("%name's planet", array('%name' => $account->name)));

    if ($output) {
      $output = '<ul>'. $output .'</ul>';
    }
    else {
      $output = '';
    }
     $result = pager_query(db_rewrite_sql("SELECT n.nid, n.sticky, n.created FROM {node} n WHERE type = 'planet' AND n.uid = %d AND n.status = 1 ORDER BY n.sticky DESC, n.created DESC"), variable_get('default_nodes_main', 10), 0, NULL, $account->uid);
    while ($node = db_fetch_object($result)) {
      $output .= node_view(node_load($node->nid), 1);
    }
    $output .= theme('pager', NULL, variable_get('default_nodes_main', 10));
    $output .= theme('feed_icon', url("planet/$account->uid/feed"));

    drupal_add_link(array('rel' => 'alternate',
                          'type' => 'application/rss+xml',
                          'title' => t('RSS - %title', array('%title' => $title)),
                          'href' => url("planet/$account->uid/feed")));
    return $output;
  }
  else{
    drupal_not_found();
  }
}

function planet_load($node){
	$additions = db_fetch_object(db_query('SELECT guid FROM {planet_items} WHERE nid = %d', $node->nid));
	return $additions;
}

function planet_form(&$node, &$param){
	$form = array();
	$form['title'] = array('#type' => 'textfield', '#title' => 'Title', '#value' => $node->title, '#size' => 30, '#maxlength' => 80);
	$form['body'] = array('#type' => 'textarea', '#title' => 'Body', '#value' => $node->body);
	return $form;
}


?>