aboutsummaryrefslogtreecommitdiffstats
path: root/include/feedutils.php
blob: fac2a272cc01cf07c67beff65879f7acbc218834 (plain) (blame)
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
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
<?php


/**
 * @brief Return an Atom feed for channel.
 *
 * @see get_feed_for()
 *
 * @param array $channel
 * @param array $params associative array which configures the feed
 * @return string with an atom feed
 */
function get_public_feed($channel, $params) {

/*	$type      = 'xml';
	$begin     = NULL_DATE;
	$end       = '';
	$start     = 0;
	$records   = 40;
	$direction = 'desc';
	$pages     = 0;
*/

	if(! $params)
		$params = [];

	$params['type']        = ((x($params,'type'))     ? $params['type']           : 'xml');
	$params['begin']       = ((x($params,'begin'))    ? $params['begin']          : NULL_DATE);
	$params['end']         = ((x($params,'end'))      ? $params['end']            : datetime_convert('UTC','UTC','now'));
	$params['start']       = ((x($params,'start'))    ? $params['start']          : 0);
	$params['records']     = ((x($params,'records'))  ? $params['records']        : 40);
	$params['direction']   = ((x($params,'direction'))? $params['direction']      : 'desc');
	$params['pages']       = ((x($params,'pages'))    ? intval($params['pages'])  : 0);
	$params['top']         = ((x($params,'top'))      ? intval($params['top'])    : 0);
	$params['cat']         = ((x($params,'cat'))      ? $params['cat']            : '');
	$params['compat']      = ((x($params,'compat'))   ? intval($params['compat']) : 0);


	switch($params['type']) {
		case 'json':
			header("Content-type: application/atom+json");
			break;
		case 'xml':
		default:
			header("Content-type: application/atom+xml");
			break;
	}

	return get_feed_for($channel, get_observer_hash(), $params);
}

/**
 * @brief Create an atom feed for $channel from template.
 *
 * @param array $channel
 * @param string $observer_hash xchan_hash from observer
 * @param array $params
 * @return string with an atom feed
 */

function get_feed_for($channel, $observer_hash, $params) {

	if(! $channel)
		http_status_exit(401);

	if($params['pages']) {
		if(! perm_is_allowed($channel['channel_id'],$observer_hash,'view_pages'))
			http_status_exit(403);
	} else {
		if(! perm_is_allowed($channel['channel_id'],$observer_hash,'view_stream'))
			http_status_exit(403);
	}

	// logger('params: ' . print_r($params,true));

	$feed_template = get_markup_template('atom_feed.tpl');

	$atom = '';

	$feed_author = '';
	if(intval($params['compat']) === 1) {
		$feed_author = atom_render_author('author',$channel);
	}

	$owner = atom_render_author('zot:owner',$channel);

	$atom .= replace_macros($feed_template, array(
		'$version'      => xmlify(Zotlabs\Lib\System::get_project_version()),
		'$red'          => xmlify(Zotlabs\Lib\System::get_platform_name()),
		'$feed_id'      => xmlify($channel['xchan_url']),
		'$feed_title'   => xmlify($channel['channel_name']),
		'$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now', ATOM_TIME)),
		'$author'       => $feed_author,
		'$owner'        => $owner,
		'$name'         => xmlify($channel['channel_name']),
		'$profile_page' => xmlify($channel['xchan_url']),
		'$mimephoto'    => xmlify($channel['xchan_photo_mimetype']),
		'$photo'        => xmlify($channel['xchan_photo_l']),
		'$thumb'        => xmlify($channel['xchan_photo_m']),
		'$picdate'      => '',
		'$uridate'      => '',
		'$namdate'      => '',
		'$birthday'     => '',
		'$community'    => '',
	));


	$x = [ 'xml' => $atom, 'channel' => $channel, 'observer_hash' => $observer_hash, 'params' => $params ];
	call_hooks('atom_feed_top',$x);

	$atom = $x['xml'];

	// a much simpler interface
	call_hooks('atom_feed', $atom);

	$items = items_fetch(
		[
			'wall' => '1',
			'datequery'  => $params['end'],
			'datequery2' => $params['begin'],
			'start'      => intval($params['start']),
			'records'    => intval($params['records']),
			'direction'  => dbesc($params['direction']),
			'pages'      => $params['pages'],
			'order'      => dbesc('post'),
			'top'        => $params['top'],
			'cat'        => $params['cat'],
			'compat'     => $params['compat']
		], $channel, $observer_hash, CLIENT_MODE_NORMAL, App::$module
	);

	if($items) {
		$type = 'html';
		foreach($items as $item) {
			if($item['item_private'])
				continue;

			/** @BUG $owner is undefined in this call */
			$atom .= atom_entry($item, $type, null, $owner, true, '', $params['compat']);
		}
	}

	call_hooks('atom_feed_end', $atom);

	$atom .= '</feed>' . "\r\n";

	return $atom;
}

/**
 * @brief Return the verb for an item, or fall back to ACTIVITY_POST.
 *
 * @param array $item an associative array with
 *   * \e string \b verb
 * @return string item's verb if set, default ACTIVITY_POST see boot.php
 */
function construct_verb($item) {
	if ($item['verb'])
		return $item['verb'];

	return ACTIVITY_POST;
}

function construct_activity_object($item) {

	if($item['obj']) {
		$o = '<as:object>' . "\r\n";
		$r = json_decode($item['obj'],false);

		if(! $r)
			return '';
		if($r->type)
			$o .= '<as:obj_type>' . xmlify($r->type) . '</as:obj_type>' . "\r\n";
		if($r->id)
			$o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
		if($r->title)
			$o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
		if($r->links) {
			/** @FIXME!! */
			if(substr($r->link,0,1) === '<') {
				$r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
				$o .= $r->link;
			}
			else
				$o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
		}
		if($r->content) {
			$o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
		}
		$o .= '</as:object>' . "\r\n";

		return $o;
	}

	return '';
}

function construct_activity_target($item) {

	if($item['target']) {
		$o = '<as:target>' . "\r\n";
		$r = json_decode($item['target'],false);
		if(! $r)
			return '';
		if($r->type)
			$o .= '<as:obj_type>' . xmlify($r->type) . '</as:obj_type>' . "\r\n";
		if($r->id)
			$o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
		if($r->title)
			$o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
		if($r->links) {
			/** @FIXME !!! */
			if(substr($r->link,0,1) === '<') {
				if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
					$r->link = str_replace('&','&amp;', $r->link);
				$r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
				$o .= $r->link;
			}
			else
				$o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
		}
		if($r->content)
			$o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";

		$o .= '</as:target>' . "\r\n";

		return $o;
	}

	return '';
}

/**
 * @brief Return an array with a parsed atom item.
 *
 * @param SimplePie $feed
 * @param array $item
 * @param[out] array $author
 * @return array Associative array with the parsed item data
 */
function get_atom_elements($feed, $item, &$author) {

	require_once('include/html2bbcode.php');

	$res = array();

	$found_author = $item->get_author();
	if($found_author) {
		if($rawauthor) {
			if($rawauthor[0]['child'][NAMESPACE_POCO]['displayName'][0]['data'])
				$author['full_name'] = unxmlify($rawauthor[0]['child'][NAMESPACE_POCO]['displayName'][0]['data']);
		}
		$author['author_name'] = unxmlify($found_author->get_name());
		$author['author_link'] = unxmlify($found_author->get_link());
		$author['author_is_feed'] = false;

		$rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
		logger('rawauthor: ' . print_r($rawauthor, true));

	}
	else {
		$author['author_name'] = unxmlify($feed->get_title());
		$author['author_link'] = unxmlify($feed->get_permalink());
		$author['author_is_feed'] = true;
	}

	if(substr($author['author_link'],-1,1) == '/')
		$author['author_link'] = substr($author['author_link'],0,-1);

	$res['mid'] = normalise_id(unxmlify($item->get_id()));
	$res['title'] = unxmlify($item->get_title());
	$res['body'] = unxmlify($item->get_content());
	$res['plink'] = unxmlify($item->get_link(0));
	$res['item_rss'] = 1;


	$summary = unxmlify($item->get_description(true));

	// removing the content of the title if its identically to the body
	// This helps with auto generated titles e.g. from tumblr

	if (title_is_body($res['title'], $res['body']))
		$res['title'] = "";

	if($res['plink'])
		$base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
	else
		$base_url = '';


	$rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'published');
	if($rawcreated)
		$res['created'] = unxmlify($rawcreated[0]['data']);

	$rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'updated');
	if($rawedited)
		$res['edited'] = unxmlify($rawedited[0]['data']);

	if((x($res,'edited')) && (! (x($res,'created'))))
		$res['created'] = $res['edited'];

	if(! $res['created'])
		$res['created'] = $item->get_date('c');

	if(! $res['edited'])
		$res['edited'] = $item->get_date('c');

	$rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');

	// select between supported verbs

	if($rawverb) {
		$res['verb'] = unxmlify($rawverb[0]['data']);
	}


	// look for a photo. We should check media size and find the best one,
	// but for now let's just find any author photo

	$rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');

	if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
		$base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
		foreach($base as $link) {
			if(!x($author, 'author_photo') || ! $author['author_photo']) {
				if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
					$author['author_photo'] = unxmlify($link['attribs']['']['href']);
			}
		}
	}
	$rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');

	if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['obj_type'][0]['data'], ACTIVITY_OBJ_PERSON)) {
		$base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
		if($base && count($base)) {
			foreach($base as $link) {
				if($link['attribs']['']['rel'] === 'alternate' && (! $res['author_link']))
					$author['author_link'] = unxmlify($link['attribs']['']['href']);
				if(!x($author, 'author_photo') || ! $author['author_photo']) {
					if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
						$author['author_photo'] = unxmlify($link['attribs']['']['href']);
				}
			}
		}
	}

	// check for a yahoo media element (github etc.)

	if(! $author['author_photo']) {
		$rawmedia = $item->get_item_tags(NAMESPACE_YMEDIA,'thumbnail');
		if($rawmedia && $rawmedia[0]['attribs']['']['url']) {
			$author['author_photo'] = strip_tags(unxmlify($rawmedia[0]['attribs']['']['url']));
		}
	}


	// No photo/profile-link on the item - look at the feed level


	if((! (x($author,'author_link'))) || (! (x($author,'author_photo')))) {
		$rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
		if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
			$base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
			foreach($base as $link) {
				if($link['attribs']['']['rel'] === 'alternate' && (! $author['author_link'])) {
					$author['author_link'] = unxmlify($link['attribs']['']['href']);
					$author['author_is_feed'] = true;
				}
				if(! $author['author_photo']) {
					if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
						$author['author_photo'] = unxmlify($link['attribs']['']['href']);
				}
			}
		}

		$rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');

		if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['obj_type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
			$base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];

			if($base && count($base)) {
				foreach($base as $link) {
					if($link['attribs']['']['rel'] === 'alternate' && (! $res['author_link']))
						$author['author_link'] = unxmlify($link['attribs']['']['href']);
					if(! (x($author,'author_photo'))) {
						if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
							$author['author_photo'] = unxmlify($link['attribs']['']['href']);
					}
				}
			}
		}
	}

	$rawcnv = $item->get_item_tags(NAMESPACE_OSTATUS, 'conversation');
	if($rawcnv) {
		// new style
		$ostatus_conversation = normalise_id(unxmlify($rawcnv[0]['attribs']['']['ref']));
		if(! $ostatus_conversation) {
			// old style 
			$ostatus_conversation = normalise_id(unxmlify($rawcnv[0]['data']));
		}
		if($ostatus_conversation) {
			set_iconfig($res,'ostatus','conversation',$ostatus_conversation,true);
			logger('ostatus_conversation: ' . $ostatus_conversation, LOGGER_DATA, LOG_INFO);
		}
	}

	$ostatus_protocol = (($ostatus_conversation) ? true : false);
	
	$mastodon = (($item->get_item_tags('http://mastodon.social/schema/1.0','scope')) ? true : false);
	if($mastodon)
		$ostatus_protocol = true;

	$apps = $item->get_item_tags(NAMESPACE_STATUSNET, 'notice_info');
	if($apps && $apps[0]['attribs']['']['source']) {
		$res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
	}

	if($ostatus_protocol) {

		// translate OStatus unfollow to activity streams if it happened to get selected

		if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow')) {
			$res['verb'] = ACTIVITY_UNFOLLOW;
		}

		// And OStatus 'favorite' is pretty much what we call 'like' on other networks

		if((x($res,'verb')) && ($res['verb'] === ACTIVITY_FAVORITE)) {
			$res['verb'] = ACTIVITY_LIKE;
		}
	}

	/*
	 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
	 */

	$have_real_body = false;

	$rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
	if(! $rawenv)
		$rawenv = $item->get_item_tags(NAMESPACE_ZOT, 'source');
	if($rawenv) {
		$have_real_body = true;
		$res['body'] = $rawenv[0]['data'];
		$res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
		// make sure nobody is trying to sneak some html tags by us
		$res['body'] = notags(base64url_decode($res['body']));

		// We could probably turn these old Friendica bbcode bookmarks into bookmark tags but we'd have to
		// create a term table item for them. For now just make sure they stay as links.

		$res['body'] = preg_replace('/\[bookmark(.*?)\](.*?)\[\/bookmark\]/','[url$1]$2[/url]',$res['body']);
	}

	$res['body'] = limit_body_size($res['body']);

	// It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
	// the content type. Our own network only emits text normally, though it might have been converted to
	// html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
	// have to assume it is all html and needs to be purified.

	// It doesn't matter all that much security wise - because before this content is used anywhere, we are
	// going to escape any tags we find regardless, but this lets us import a limited subset of html from
	// the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
	// html.

	if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {

		$res['body'] = reltoabs($res['body'],$base_url);

		$res['body'] = html2bb_video($res['body']);

		$res['body'] = oembed_html2bbcode($res['body']);

		$res['body'] = purify_html($res['body']);

		$res['body'] = @html2bbcode($res['body']);
	}
	elseif(! $have_real_body) {

		// it's not one of our messages and it has no tags
		// so it's probably just text. We'll escape it just to be safe.

		$res['body'] = escape_tags($res['body']);
	}


	// strip title and don't apply "title-in-body" if the feed involved
	// uses the OStatus stack. We need a more generalised way for the calling
	// function to specify this behaviour or for plugins to alter it.

	if($ostatus_protocol) {
		$res['title'] = '';
	}
	elseif($res['plink'] && $res['title']) {
		$res['body'] = '#^[url=' . $res['plink'] . ']' . $res['title'] . '[/url]' . "\n\n" . $res['body'];
		$terms = array();
		$terms[] = array(
			'otype' => TERM_OBJ_POST,
			'ttype' => TERM_BOOKMARK,
			'url'   => $res['plink'],
			'term'  => $res['title'],
		);
	}
	elseif($res['plink']) {
		$res['body'] = '#^[url]' . $res['plink'] . '[/url]' . "\n\n" . $res['body'];
		$terms = array();
		$terms[] = array(
			'otype' => TERM_OBJ_POST,
			'ttype' => TERM_BOOKMARK,
			'url'   => $res['plink'],
			'term'  => $res['plink'],
		);
	}

	// turn Mastodon content warning into a #nsfw hashtag
	if($mastodon && $summary) {
		$res['body'] .= "\n\n#ContentWarning\n";
	}


	$private = $item->get_item_tags(NAMESPACE_DFRN, 'private');
	if($private && intval($private[0]['data']) > 0)
		$res['item_private'] = ((intval($private[0]['data'])) ? 1 : 0);
	else
		$res['item_private'] = 0;

	$rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
	if($rawlocation)
		$res['location'] = unxmlify($rawlocation[0]['data']);


	// Disallow time travelling posts

	$d1 = strtotime($res['created']);
	$d2 = strtotime($res['edited']);
	$d3 = strtotime('now');

	if($d1 > $d3)
		$res['created'] = datetime_convert();
	if($d2 > $d3)
		$res['edited'] = datetime_convert();

	$res['created'] = datetime_convert('UTC','UTC',$res['created']);
	$res['edited'] = datetime_convert('UTC','UTC',$res['edited']);

	$rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
	if(! $rawowner)
		$rawowner = $item->get_item_tags(NAMESPACE_ZOT, 'owner');

	if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
		$author['owner_name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
	elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
		$author['owner_name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
	if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
		$author['owner_link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
	elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
		$author['owner_link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);

	if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
		$base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];

		foreach($base as $link) {
			if(!x($author, 'owner_photo') || ! $author['owner_photo']) {
				if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
					$author['owner_photo'] = unxmlify($link['attribs']['']['href']);
			}
		}
	}

	$rawgeo = $item->get_item_tags(NAMESPACE_GEORSS, 'point');
	if($rawgeo)
		$res['coord'] = unxmlify($rawgeo[0]['data']);


	$cats = $item->get_categories();
	if($cats) {
		if(is_null($terms))
			$terms = array();

		foreach($cats as $cat) {
			$term = $cat->get_term();
			if(! $term)
				$term = $cat->get_label();

			$scheme = $cat->get_scheme();
			$termurl = '';
			if($scheme && $term && stristr($scheme,'X-DFRN:')) {
				$termtype = ((substr($scheme,7,1) === '#') ? TERM_HASHTAG : TERM_MENTION);
				$termurl = unxmlify(substr($scheme,9));
			}
			else {
				$termtype = TERM_CATEGORY;
			}
			$termterm = notags(trim(unxmlify($term)));

			if($termterm) {
				$terms[] = array(
					'otype' => TERM_OBJ_POST,
					'ttype' => $termtype,
					'url'   => $termurl,
					'term'  => $termterm,
				);
			}
		}
	}

	if(! is_null($terms))
		$res['term'] =  $terms;

	$attach = $item->get_enclosures();
	if($attach) {

		$res['attach'] = array();
		foreach($attach as $att) {
			$len   = intval($att->get_length());
			$link  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
			$title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
			$type  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
			if(strpos($type,';'))
				$type = substr($type,0,strpos($type,';'));
			if((! $link) || (strpos($link,'http') !== 0))
				continue;

			if(! $title)
				$title = ' ';
			if(! $type)
				$type = 'application/octet-stream';

			if($ostatus_protocol)  {
				if((strpos($type,'image') === 0) && (strpos($res['body'], ']' . $link . '[/img]') === false) && (strpos($link,'http') === 0)) {
					$res['body'] .= "\n\n" . '[img]' . $link . '[/img]';
				}
				if((strpos($type,'video') === 0) && (strpos($res['body'], ']' . $link . '[/video]') === false) && (strpos($link,'http') === 0)) {
					$res['body'] .= "\n\n" . '[video]' . $link . '[/video]';
				}
				if((strpos($type,'audio') === 0) && (strpos($res['body'], ']' . $link . '[/audio]') === false) && (strpos($link,'http') === 0)) {
					$res['body'] .= "\n\n" . '[audio]' . $link . '[/audio]';
				}
			}
			$res['attach'][] = array('href' => $link, 'length' => $len, 'type' => $type, 'title' => $title );
		}
	}
	

	$rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');

	if($rawobj) {
		$obj = array();

		$child = $rawobj[0]['child'];
		if($child[NAMESPACE_ACTIVITY]['obj_type'][0]['data']) {
			$res['obj_type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data'];
			$obj['type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data'];
		}
		if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
			$res['obj_type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
			$obj['type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
		}
		if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
			$obj['id'] = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'];
		if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
			$obj['link'] = encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']);
		if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
			$obj['title'] =  $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'];
		if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
			$body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
			if(! $body)
				$body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];

			// preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
			$obj['orig'] = xmlify($body);
			if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
				$body = purify_html($body);
				$body = html2bbcode($body);
			}

			$obj['content'] = $body;
		}

		$res['obj'] = $obj;
	}

	$rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');

	if($rawobj) {
		$obj = array();

		$child = $rawobj[0]['child'];
		if($child[NAMESPACE_ACTIVITY]['obj_type'][0]['data']) {
			$res['tgt_type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data'];
			$obj['type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data'];
		}
		if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
			$res['tgt_type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
			$obj['type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
		}
		if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
			$obj['id'] = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'];
		if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
			$obj['link'] = encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']);
		if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
			$obj['title'] =  $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'];
		if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
			$body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
			if(! $body)
				$body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];

			// preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
			$obj['orig'] = xmlify($body);
			if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
				$body = purify_html($body);
				$body = html2bbcode($body);
			}

			$obj['content'] = $body;
		}

		$res['target'] = $obj;
	}

	

	if(array_key_exists('verb',$res) && $res['verb'] === ACTIVITY_SHARE
		&& array_key_exists('obj_type',$res) && in_array($res['obj_type'], [ ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT, ACTIVITY_OBJ_ACTIVITY ] )) {
		feed_get_reshare($res,$item);
	}

	// build array to pass to hook
	$arr = [
			'feed'   => $feed,
			'item'   => $item,
			'author' => $author,
			'result' => $res
	];

	call_hooks('parse_atom', $arr);

	logger('author: ' .print_r($arr['author'], true), LOGGER_DATA);
	logger('result: ' .print_r($arr['result'], true), LOGGER_DATA);

	return $arr['result'];
}

function feed_get_reshare(&$res,$item) {

	$share = [];

	// For Mastodon shares ("boosts"), we need to parse the original author information
	// from the activity:object -> author structure
	$rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');

	if($rawobj) {

		$rawauthor = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['author'];

		if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name']) {
			$share['author'] = unxmlify($rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
		}

		if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri']) {
			$share['profile'] = unxmlify($rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
		}

		if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
			$base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
			foreach($base as $link) {
				if(! (array_key_exists('avatar',$share) && $share['avatar'])) {
					if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
						$share['avatar'] = unxmlify($link['attribs']['']['href']);
				}
			}
		}

		if(! $share['author'])
			$share['author'] = t('unknown');
		if(! $share['avatar'])
			$share['avatar'] = z_root() . '/' . get_default_profile_photo(80);
		if(! $share['profile'])
			$share['profile'] = z_root();
	
		$child = $rawobj[0]['child'];


		if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
			$share['links'] = encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']);

		$rawcreated = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['published'];

		if($rawcreated)
			$share['created'] = unxmlify($rawcreated[0]['data']);
		else
			$share['created'] = $res['created'];

		if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
			$share['message_id'] = unxmlify($child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data']);

		if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
			$body = unxmlify($child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']);
			if(! $body)
				$body = unxmlify($child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data']);

			if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
				$body = purify_html($body);
				$body = html2bbcode($body);
			}
		}
	
		$attach = $share['links'];
		if($attach) {
			foreach($attach as $att) {
				if($att['rel'] === 'alternate') {
					$share['alternate'] = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att['href']))));
					continue;
				}
				if($att['rel'] !== 'enclosure')
					continue;
				$len   = intval($att['length']);
				$link  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att['href']))));
				$title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att['title']))));
				$type  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att['type']))));
				if(strpos($type,';'))
					$type = substr($type,0,strpos($type,';'));
				if((! $link) || (strpos($link,'http') !== 0))
					continue;

				if(! $title)
					$title = ' ';
				if(! $type)
					$type = 'application/octet-stream';

				if((strpos($type,'image') === 0) && (strpos($body, ']' . $link . '[/img]') === false) && (strpos($link,'http') === 0)) {
					$body .= "\n\n" . '[img]' . $link . '[/img]';
				}
				if((strpos($type,'video') === 0) && (strpos($body, ']' . $link . '[/video]') === false) && (strpos($link,'http') === 0)) {
					$body .= "\n\n" . '[video]' . $link . '[/video]';
				}
				if((strpos($type,'audio') === 0) && (strpos($body, ']' . $link . '[/audio]') === false) && (strpos($link,'http') === 0)) {
					$body .= "\n\n" . '[audio]' . $link . '[/audio]';
				}
			}
		}
	
		$res['body'] = "[share author='" . urlencode($share['author']) . 
			"' profile='"    . $share['profile'] .
			"' avatar='"     . $share['avatar']  .
			"' link='"       . $share['alternate']    .
			"' posted='"     . $share['created'] . 
			"' message_id='" . $share['message_id'] . "']";

		$res['body'] .= $body;
		$res['body'] .= "[/share]";
	}

}



/**
 * @brief Encodes SimplePie_Item link arrays.
 *
 * @param array $links Array with SimplePie_Item link tags
 * @return array
 */
function encode_rel_links($links) {
	$o = array();
	if(! ((is_array($links)) && (count($links))))
		return $o;

	foreach($links as $link) {
		$l = array();
		if($link['attribs']['']['rel'])
			$l['rel'] =  $link['attribs']['']['rel'];
		if($link['attribs']['']['length'])
			$l['length'] =  $link['attribs']['']['length'];
		if($link['attribs']['']['title'])
			$l['title'] =  $link['attribs']['']['title'];
		if($link['attribs']['']['type'])
			$l['type'] =  $link['attribs']['']['type'];
		if($link['attribs']['']['href'])
			$l['href'] = $link['attribs']['']['href'];
		if( (x($link['attribs'], NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
			$l['width'] = $link['attribs'][NAMESPACE_MEDIA]['width'];
		if( (x($link['attribs'], NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
			$l['height'] = $link['attribs'][NAMESPACE_MEDIA]['height'];

		if($l)
			$o[] = $l;
	}

	return $o;
}

/**
 * @brief Process atom feed and update anything/everything we might need to update.
 *
 * @param string $xml
 *   The (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
 * @param $importer
 *   The contact_record (joined to user_record) of the local user who owns this
 *   relationship. It is this person's stuff that is going to be updated.
 * @param[in,out] array $contact
 *   The person who is sending us stuff. If not set, we MAY be processing a "follow" activity
 *   from an external network and MAY create an appropriate contact record. Otherwise, we MUST
 *   have a contact record.
 * @param int $pass by default ($pass = 0) we cannot guarantee that a parent item has been
 *   imported prior to its children being seen in the stream unless we are certain
 *   of how the feed is arranged/ordered.
 *  * With $pass = 1, we only pull parent items out of the stream.
 *  * With $pass = 2, we only pull children (comments/likes).
 *
 * So running this twice, first with pass 1 and then with pass 2 will do the right
 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
 * model where comments can have sub-threads. That would require some massive sorting
 * to get all the feed items into a mostly linear ordering, and might still require
 * recursion.
 */
function consume_feed($xml, $importer, &$contact, $pass = 0) {

	if(! strlen($xml)) {
		logger('Empty input');
		return;
	}

	$sys_expire = intval(get_config('system', 'default_expire_days'));
	$chn_expire = intval($importer['channel_expire_days']);

	$expire_days = $sys_expire;

	if(($chn_expire != 0) && ($chn_expire < $sys_expire))
		$expire_days = $chn_expire;

	$feed = new SimplePie();
	$feed->set_raw_data($xml);

	// We can preserve iframes because we will strip them in the purifier after
	// checking for supported video sources.
	$strip_htmltags = $feed->strip_htmltags;
	array_splice($strip_htmltags, array_search('iframe', $strip_htmltags), 1);
	$feed->strip_htmltags($strip_htmltags);

	$feed->init();

	if($feed->error())
		logger('Error parsing XML: ' . $feed->error());

	$permalink = $feed->get_permalink();

	// Check at the feed level for updated contact name and/or photo

	// process any deleted entries

	$del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
	if(is_array($del_entries) && count($del_entries) && $pass != 2) {
		foreach($del_entries as $dentry) {
			$deleted = false;
			if(isset($dentry['attribs']['']['ref'])) {
				$mid = normalise_id($dentry['attribs']['']['ref']);
				$deleted = true;
				if(isset($dentry['attribs']['']['when'])) {
					$when = $dentry['attribs']['']['when'];
					$when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
				}
				else
					$when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
			}

			if($deleted && is_array($contact)) {
				$r = q("SELECT * from item where mid = '%s' and author_xchan = '%s' and uid = %d limit 1",
					dbesc($mid),
					dbesc($contact['xchan_hash']),
					intval($importer['channel_id'])
				);

				if($r) {
					$item = $r[0];

					if(! intval($item['item_deleted'])) {
						logger('deleting item ' . $item['id'] . ' mid=' . $item['mid'], LOGGER_DEBUG);
						drop_item($item['id'],false);
					}
				}
			}
		}
	}

	// Now process the feed

	if($feed->get_item_quantity()) {

		logger('feed item count = ' . $feed->get_item_quantity(), LOGGER_DEBUG);

		$items = $feed->get_items();

		foreach($items as $item) {

			$is_reply = false;
			$parent_link = '';

			logger('processing ' . $item->get_id(), LOGGER_DEBUG);

			$rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
			if(isset($rawthread[0]['attribs']['']['ref'])) {
				$is_reply = true;
				$parent_mid = normalise_id($rawthread[0]['attribs']['']['ref']);
			}
			if(isset($rawthread[0]['attribs']['']['href'])) {
				$parent_link = $rawthread[0]['attribs']['']['href'];
			}

			logger('in-reply-to: ' . $parent_mid, LOGGER_DEBUG);

			if($is_reply) {

				if($pass == 1)
					continue;

				// Have we seen it? If not, import it.

				$author = array();
				$datarray = get_atom_elements($feed,$item,$author);

				if(! $datarray['mid'])
					continue;

				if($contact['xchan_network'] === 'rss') {
					$datarray['public_policy'] = 'specific';
					$datarray['comment_policy'] = 'none';
				}

				if((! x($author,'author_name')) || ($author['author_is_feed']))
					$author['author_name'] = $contact['xchan_name'];
				if((! x($author,'author_link')) || ($author['author_is_feed']))
					$author['author_link'] = $contact['xchan_url'];
				if((! x($author,'author_photo'))|| ($author['author_is_feed']))
					$author['author_photo'] = $contact['xchan_photo_m'];

				$datarray['author_xchan'] = '';

				if($author['author_link'] != $contact['xchan_url']) {
					$name = '';
					if($author['full_name']) {
						$name = $author['full_name'];
						if($author['author_name'])
							$name .= ' (' . $author['author_name'] . ')';
					}
					else {
						$name = $author['author_name'];
					}
					$x = import_author_unknown(array('name' => $name,'url' => $author['author_link'],'photo' => array('src' => $author['author_photo'])));
					if($x)
						$datarray['author_xchan'] = $x;
				}
				if(! $datarray['author_xchan'])
					$datarray['author_xchan'] = $contact['xchan_hash'];

				$datarray['owner_xchan'] = $contact['xchan_hash'];

				$r = q("SELECT edited FROM item WHERE mid = '%s' AND uid = %d LIMIT 1",
					dbesc($datarray['mid']),
					intval($importer['channel_id'])
				);


				// Update content if 'updated' changes

				if($r) {
					if((x($datarray,'edited') !== false)
						&& (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {

						// do not accept (ignore) an earlier edit than one we currently have.
						if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
							continue;

						update_feed_item($importer['channel_id'],$datarray);
					}
					continue;
				}

				$pmid = '';
				$conv_id = get_iconfig($datarray,'ostatus','conversation');

				// match conversations - first try ostatus:conversation
				// next try thr:in_reply_to

				if($conv_id) {
					logger('find_parent: conversation_id: ' . $conv_id, LOGGER_DEBUG);
					$c = q("select parent_mid from item left join iconfig on item.id = iconfig.iid where iconfig.cat = 'ostatus' and iconfig.k = 'conversation' and iconfig.v = '%s' and item.uid = %d order by item.id limit 1",
						dbesc($conv_id),
						intval($importer['channel_id'])
					);
					if($c) {
						logger('find_parent: matched conversation: ' . $conv_id, LOGGER_DEBUG);
						$pmid = $c[0]['parent_mid'];
						$datarray['parent_mid'] = $pmid;
					}
				}
				if(! $pmid) {
					$x = q("select parent_mid from item where mid = '%s' and uid = %d limit 1",
						dbesc($parent_mid),
						intval($importer['channel_id'])
					);
				
					if($x) {
						logger('find_parent: matched in-reply-to: ' . $parent_mid, LOGGER_DEBUG);
						$pmid = $x[0]['parent_mid'];
						$datarray['parent_mid'] = $pmid;
					}
				}
				if((! $pmid) && $parent_link !== '') {
					$f = feed_conversation_fetch($importer,$contact,$parent_link);
					if($f) {
						// check both potential conversation parents again
						if($conv_id) {
							$c = q("select parent_mid from item left join iconfig on item.id = iconfig.iid where iconfig.cat = 'ostatus' and iconfig.k = 'conversation' and iconfig.v = '%s' and item.uid = %d order by item.id limit 1",
								dbesc($conv_id),
								intval($importer['channel_id'])
							);
							if($c) {
								$pmid = $c[0]['parent_mid'];
								$datarray['parent_mid'] = $pmid;
							}
						}
						if(! $pmid) {
							$x = q("select parent_mid from item where mid = '%s' and uid = %d limit 1",
								dbesc($parent_mid),
								intval($importer['channel_id'])
							);
				
							if($x) {
								$pmid = $x[0]['parent_mid'];
								$datarray['parent_mid'] = $pmid;
							}
						}
					}

					// the conversation parent might just be the post we are trying to import.
					// check existence again in case it was just delivered.

					$r = q("SELECT id FROM item WHERE mid = '%s' AND uid = %d LIMIT 1",
						dbesc($datarray['mid']),
						intval($importer['channel_id'])
					);
					if($r) {
						continue;
					}
				}

				if($pmid) {

					// check comment permissions on the parent

					$r = q("select * from item where parent_mid = '%s' and parent_mid = mid and uid = %d limit 1"
						dbesc($pmid),
						intval($importer['channel_id'])
					);
					if($r) {
						$parent_item = $r[0];

					if(intval($parent_item['item_nocomment']) || $parent_item['comment_policy'] === 'none' 
						|| ($parent_item['comments_closed'] > NULL_DATE && $parent_item['comments_closed'] < datetime_convert())) {
						logger('comments disabled for post ' . $parent_item['mid']);
						continue;
					}

					$allowed = false;

					if($parent_item) {
						if($parent_item['owner_xchan'] == $importer['channel_hash']) 
							$allowed = perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'post_comments');
						else
							$allowed = true;

						if(! $allowed) {
							logger('Ignoring this comment author.');
							$status = 202;
							continue;
						}
					}
					else {
						if((! perm_is_allowed($importer['channel_id'],$contact['xchan_hash'],'send_stream')) && (! $importer['system'])) {
							// @fixme check for and process ostatus autofriend
							// otherwise 

							logger('Ignoring this author.');
							continue;
						}
					}
				}
				else {

					// immediate parent wasn't found. Turn into a top-level post if permissions allow
					// but save the thread_parent in case we need to refer to it later.
  
					if(! post_is_importable($datarray, $contact))
						continue;
					$datarray['parent_mid'] = $datarray['mid'];
					set_iconfig($datarray,'system','parent_mid',$parent_mid,true);
				}
				
				$datarray['aid'] = $importer['channel_account_id'];
				$datarray['uid'] = $importer['channel_id'];

				logger('data: ' . print_r($datarray, true), LOGGER_DATA);

				$xx = item_store($datarray);
				$r = $xx['item_id'];
				continue;
			}
			else {

				// Head post of a conversation. Have we seen it? If not, import it.

				$author = array();
				$datarray = get_atom_elements($feed,$item,$author);

				if(! $datarray['mid'])
					continue;

				if($contact['xchan_network'] === 'rss') {
					$datarray['public_policy'] = 'specific';
					$datarray['comment_policy'] = 'none';
				}

				if(is_array($contact)) {
					if((! x($author,'author_name')) || ($author['author_is_feed']))
						$author['author_name'] = $contact['xchan_name'];
					if((! x($author,'author_link')) || ($author['author_is_feed']))
						$author['author_link'] = $contact['xchan_url'];
					if((! x($author,'author_photo'))|| ($author['author_is_feed']))
						$author['author_photo'] = $contact['xchan_photo_m'];
				}

				if((! x($author,'author_name')) || (! x($author,'author_link'))) {
					logger('No author information! ' . print_r($author,true));
					continue;
				}

				$datarray['author_xchan'] = '';

				if($author['author_link'] != $contact['xchan_url']) {
					$name = '';
					if($author['full_name']) {
						$name = $author['full_name'];
						if($author['author_name'])
							$name .= ' (' . $author['author_name'] . ')';
					}
					else {
						$name = $author['author_name'];
					}
					$x = import_author_unknown(array('name' => $name,'url' => $author['author_link'],'photo' => array('src' => $author['author_photo'])));
					if($x)
						$datarray['author_xchan'] = $x;
				}
				if(! $datarray['author_xchan'])
					$datarray['author_xchan'] = $contact['xchan_hash'];

				$datarray['owner_xchan'] = $contact['xchan_hash'];

				if(array_key_exists('created',$datarray) && $datarray['created'] > NULL_DATE && $expire_days) {
					$t1 = $datarray['created'];
					$t2 = datetime_convert('UTC','UTC','now - ' . $expire_days . 'days');
					if($t1 < $t2) {
						logger('feed content older than expiration. Ignoring.', LOGGER_DEBUG, LOG_INFO);
						continue;
					}
				}


				$r = q("SELECT edited FROM item WHERE mid = '%s' AND uid = %d LIMIT 1",
					dbesc($datarray['mid']),
					intval($importer['channel_id'])
				);

				// Update content if 'updated' changes

				if($r) {
					if((x($datarray,'edited') !== false)
						&& (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {

						// do not accept (ignore) an earlier edit than one we currently have.
						if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
							continue;

						update_feed_item($importer['channel_id'],$datarray);
					}

					continue;
				}

				$datarray['parent_mid'] = $datarray['mid'];
				$datarray['uid'] = $importer['channel_id'];
				$datarray['aid'] = $importer['channel_account_id'];

				if(! link_compare($author['owner_link'], $contact['xchan_url'])) {
					logger('Correcting item owner.', LOGGER_DEBUG);
					$author['owner_name']   = $contact['name'];
					$author['owner_link']   = $contact['url'];
					$author['owner_avatar'] = $contact['thumb'];
				}

				if(! post_is_importable($datarray, $contact))
					continue;

				logger('author: ' . print_r($author, true), LOGGER_DEBUG);
				logger('data: ' . print_r($datarray, true), LOGGER_DATA);

				$xx = item_store($datarray);
				$r = $xx['item_id'];

				continue;
			}
		}
	}
}


function feed_conversation_fetch($importer,$contact,$parent_link) {

	logger('parent_link: ' . $parent_link, LOGGER_DEBUG, LOG_INFO);

	$link = '';

	// GNU-Social flavoured feeds
	if(strpos($parent_link,'/notice/')) {
		$link = str_replace('/notice/','/api/statuses/show/',$parent_link) . '.atom';
	} 

	// Mastodon flavoured feeds
	if(strpos($parent_link,'/users/') && strpos($parent_link,'/updates/')) {
		$link = $parent_link . '.atom';
	} 

	if(! $link)
		return false;

	logger('fetching: ' . $link, LOGGER_DEBUG, LOG_INFO);

	$fetch = z_fetch_url($link);

	if(! $fetch['success'])
		return false;

	$data = $fetch['body'];

	// We will probably receive an atom 'entry' and not an atom 'feed'. Unfortunately
	// our parser is a bit strict about compliance so we'll insert just enough of a feed 
	// tag to trick it into believing it's a compliant feed. 

	if(! strstr($data,'<feed')) {
		$data = str_replace('<entry ','<feed xmlns="http://www.w3.org/2005/Atom"><entry ',$data); 
		$data .= '</feed>';
	} 
 
	consume_feed($data,$importer,$contact,1);
	consume_feed($data,$importer,$contact,2);

	return true;
	
}

/**
 * @brief Normalise an id.
 *
 * Strip "X-ZOT:" from $id.
 *
 * @param string $id
 * @return string
 */
function normalise_id($id) {
	return str_replace('X-ZOT:', '', $id);
}


/**
 * @brief Process atom feed and return the first post and structure.
 *
 * @param string $xml
 *   The (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
 * @param $importer
 *   The contact_record (joined to user_record) of the local user who owns this
 *   relationship. It is this person's stuff that is going to be updated.
 */
function process_salmon_feed($xml, $importer) {

	$ret = array();

	if(! strlen($xml)) {
		logger('process_feed: empty input');
		return;
	}

	$feed = new SimplePie();
	$feed->set_raw_data($xml);

	// We can preserve iframes because we will strip them in the purifier after
	// checking for supported video sources.
	$strip_htmltags = $feed->strip_htmltags;
	array_splice($strip_htmltags, array_search('iframe', $strip_htmltags), 1);
	$feed->strip_htmltags($strip_htmltags);

	$feed->init();

	if($feed->error())
		logger('Error parsing XML: ' . $feed->error());

	$permalink = $feed->get_permalink();

	if($feed->get_item_quantity()) {

		// this should be exactly one

		logger('feed item count = ' . $feed->get_item_quantity(), LOGGER_DEBUG);

		$items = $feed->get_items();

		foreach($items as $item) {

			$item_id = normalise_id($item->get_id());

			logger('processing ' . $item_id, LOGGER_DEBUG);

			$rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
			if(isset($rawthread[0]['attribs']['']['ref'])) {
				$is_reply = true;
				$parent_mid = normalise_id($rawthread[0]['attribs']['']['ref']);
			}

			if($is_reply)
				$ret['parent_mid'] = $parent_mid;

			$ret['author'] = array();

			$datarray = get_atom_elements($feed, $item, $ret['author']);

			// reset policies which are restricted by default for RSS connections
			// This item is likely coming from GNU-social via salmon and allows public interaction
			$datarray['public_policy'] = '';
			$datarray['comment_policy'] = '';

			$ret['item'] = $datarray;
		}
	}

	return $ret;
}


/**
 * @brief Given an xml (atom) feed, find author and hub links.
 *
 * @param string $xml
 * @return array
 */
function feed_meta($xml) {

	$ret = array();

	if(! strlen($xml)) {
		logger('empty input');
		return $ret;
	}

	$feed = new SimplePie();
	$feed->set_raw_data($xml);
	$feed->init();

	if($feed->error()) {
		logger('Error parsing XML: ' . $feed->error());
		return $ret;
	}

	$ret['hubs'] = $feed->get_links('hub');

	//logger('hubs: ' . print_r($hubs,true), LOGGER_DATA);

	$author = array();

	$found_author = $feed->get_author();
	if($found_author) {
		$author['author_name'] = unxmlify($found_author->get_name());
		$author['author_link'] = unxmlify($found_author->get_link());

		$rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
		logger('rawauthor: ' . print_r($rawauthor, true));

		if($rawauthor) {
			if($rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
				$base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
				foreach($base as $link) {
					if(!x($author, 'author_photo') || ! $author['author_photo']) {
						if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar') {
							$author['author_photo'] = unxmlify($link['attribs']['']['href']);
							break;
						}
					}
				}
			}
			if($rawauthor[0]['child'][NAMESPACE_POCO]['displayName'][0]['data'])
				$author['full_name'] = unxmlify($rawauthor[0]['child'][NAMESPACE_POCO]['displayName'][0]['data']);
			if($rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
				$author['author_uri'] = unxmlify($rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
		}
	}

	if(! $author['author_photo'])
		$author['author_photo'] = $feed->get_image_url();


	if(substr($author['author_link'],-1,1) == '/')
		$author['author_link'] = substr($author['author_link'],0,-1);

	$ret['author'] = $author;

	return $ret;
}

/**
 * @brief Not yet implemented function to update feed item.
 *
 * @param int $uid
 * @param array $datarray
 */
function update_feed_item($uid, $datarray) {
	logger('Not implemented! ' . $uid . ' ' . print_r($datarray, true), LOGGER_DATA);
}

/**
 * @brief Fetch the content of a feed and further consume it.
 *
 * It will first process parent items and in a second run child items.
 * @see consume_feed()
 *
 * @param int $uid
 * @param int $abook_id
 * @param string $url URL of the feed
 */
function handle_feed($uid, $abook_id, $url) {

	$channel = channelx_by_n($uid);
	if(! $channel)
		return;

	$x = q("select * from abook left join xchan on abook_xchan = xchan_hash where abook_id = %d and abook_channel = %d limit 1",
		dbesc($abook_id),
		intval($uid)
	);

	$recurse = 0;
	$z = z_fetch_url($url, false, $recurse, array('novalidate' => true));

	//logger('data:' . print_r($z, true), LOGGER_DATA);

	if($z['success']) {
		consume_feed($z['body'], $channel, $x[0], 1);
		consume_feed($z['body'], $channel, $x[0], 2);
	}
}

/**
 * @brief Return a XML tag with author information.
 *
 * @hooks \b atom_author Possibility to add further tags to returned XML string
 *   * \e string The created XML tag as a string without closing tag
 * @param string $tag The XML tag to create
 * @param string $nick preferred username
 * @param string $name displayed name of the author
 * @param string $uri
 * @param int $h image height
 * @param int $w image width
 * @param string $type profile photo mime type
 * @param string $photo Fully qualified URL to a profile/avator photo
 * @return string
 */
function atom_author($tag, $nick, $name, $uri, $h, $w, $type, $photo) {
	$o = '';
	if(! $tag)
		return $o;

	$nick = xmlify($nick);
	$name = xmlify($name);
	$uri = xmlify($uri);
	$h = intval($h);
	$w = intval($w);
	$photo = xmlify($photo);

	$o .= "<$tag>\r\n";
	$o .= "  <id>$uri</id>\r\n";
	$o .= "  <name>$nick</name>\r\n";
	$o .= "  <uri>$uri</uri>\r\n";
	$o .= '  <link rel="photo"  type="' . $type . '" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
	$o .= '  <link rel="avatar" type="' . $type . '" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
	$o .= '  <poco:preferredUsername>' . $nick . '</poco:preferredUsername>' . "\r\n";
	$o .= '  <poco:displayName>' . $name . '</poco:displayName>' . "\r\n";

	call_hooks('atom_author', $o);

	$o .= "</$tag>\r\n";

	return $o;
}


function atom_render_author($tag,$xchan) {

	
	$nick = xmlify(substr($xchan['xchan_addr'],0,strpos($xchan['xchan_addr'],'@')));
	$id   = xmlify($xchan['xchan_url']);
	$name = xmlify($xchan['xchan_name']);
	$photo = xmlify($xchan['xchan_photo_l']);
	$type = xmlify($xchan['xchan_photo_mimetype']);
	$w = $h = 300;

	$o .= "<$tag>\r\n";
	$o .= "  <as:object-type>http://activitystrea.ms/schema/1.0/person</as:object-type>\r\n";
	$o .= "  <id>$id</id>\r\n";
	$o .= "  <name>$nick</name>\r\n";
	$o .= "  <uri>$id</uri>\r\n";
	$o .= '  <link rel="alternate" type="text/html" href="' . $id . '" />' . "\r\n";
	$o .= '  <link rel="photo"  type="' . $type . '" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
	$o .= '  <link rel="avatar" type="' . $type . '" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
	$o .= '  <poco:preferredUsername>' . $nick . '</poco:preferredUsername>' . "\r\n";
	$o .= '  <poco:displayName>' . $name . '</poco:displayName>' . "\r\n";

	call_hooks('atom_render_author', $o);

	$o .= "</$tag>\r\n";

	return $o;


}

function compat_photos_list($s) {

	$ret = [];

	$found = preg_match_all('/\[[zi]mg(.*?)\](.*?)\[/ism',$s,$matches,PREG_SET_ORDER);

	if($found) {
		foreach($matches as $match) {
			$ret[] = [
				'href' => $match[2],
				'length' => 0,
				'type' => guess_image_type($match[2])
			];

		}
	}

	return $ret;
}



/**
 * @brief Create an item for the Atom feed.
 *
 * @see get_feed_for()
 *
 * @param array $item
 * @param string $type
 * @param array $author
 * @param array $owner
 * @param string $comment default false
 * @param number $cid default 0
 * @return void|string
 */
function atom_entry($item, $type, $author, $owner, $comment = false, $cid = 0, $compat = false) {


	if(! $item['parent'])
		return;

	if($item['deleted'])
		return '<at:deleted-entry ref="' . xmlify($item['mid']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";

	create_export_photo_body($item);

	if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
		$body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
	else
		$body = $item['body'];

	if($compat) {
		$compat_photos = compat_photos_list($body);
	}
	else {
		$compat_photos = null;
	}

	$o = "\r\n\r\n<entry>\r\n";

	if(is_array($author)) {
		$o .= atom_render_author('author',$author);
	}
	else {
		$o .= atom_render_author('author',$item['author']);
	}

	$o .= atom_render_author('zot:owner',$item['owner']);

	if(($item['parent'] != $item['id']) || ($item['parent_mid'] !== $item['mid']) || (($item['thr_parent'] !== '') && ($item['thr_parent'] !== $item['mid']))) {
		$parent_item = (($item['thr_parent']) ? $item['thr_parent'] : $item['parent_mid']);
		// ensure it's a legal uri and not just a message-id
		if(! strpos($parent_item,':'))
			$parent_item = 'X-ZOT:' . $parent_item;

		$o .= '<thr:in-reply-to ref="' . xmlify($parent_item) . '" type="text/html" href="' .  xmlify($item['plink']) . '" />' . "\r\n";
	}

	if(activity_match($item['obj_type'],ACTIVITY_OBJ_EVENT) && activity_match($item['verb'],ACTIVITY_POST)) {
		$obj = ((is_array($item['obj'])) ? $item['obj'] : json_decode($item['obj'],true));

		$o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
		$o .= '<summary xmlns="urn:ietf:params:xml:ns:xcal">' . xmlify(bbcode($obj['title'])) . '</summary>' . "\r\n";
		$o .= '<dtstart xmlns="urn:ietf:params:xml:ns:xcal">' . datetime_convert('UTC','UTC', $obj['dtstart'],'Ymd\\THis' . (($obj['adjust']) ? '\\Z' : '')) .  '</dtstart>' . "\r\n";
		$o .= '<dtend xmlns="urn:ietf:params:xml:ns:xcal">' . datetime_convert('UTC','UTC', $obj['dtend'],'Ymd\\THis' . (($obj['adjust']) ? '\\Z' : '')) .  '</dtend>' . "\r\n";
		$o .= '<location xmlns="urn:ietf:params:xml:ns:xcal">' . xmlify(bbcode($obj['location'])) . '</location>' . "\r\n";
		$o .= '<content type="' . $type . '" >' . xmlify(bbcode($obj['description'])) . '</content>' . "\r\n";
	}
	else {
		$o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
		$o .= '<content type="' . $type . '" >' . xmlify(prepare_text($body,$item['mimetype'])) . '</content>' . "\r\n";
	}

	$o .= '<id>' . 'X-ZOT:' . xmlify($item['mid']) . '</id>' . "\r\n";
	$o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
	$o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";

	$o .= '<link rel="alternate" type="text/html" href="' . xmlify($item['plink']) . '" />' . "\r\n";

	if($item['location']) {
		$o .= '<zot:location>' . xmlify($item['location']) . '</zot:location>' . "\r\n";
		$o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
	}

	if($item['coord'])
		$o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";

	if(($item['item_private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
		$o .= '<zot:private>' . (($item['item_private']) ? $item['item_private'] : 1) . '</zot:private>' . "\r\n";

	if($item['app'])
		$o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";

	$verb = construct_verb($item);
	$o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
	$actobj = construct_activity_object($item);
	if(strlen($actobj))
		$o .= $actobj;

	$actarg = construct_activity_target($item);
	if(strlen($actarg))
		$o .= $actarg;

	if($item['attach']) {
		$enclosures = json_decode($item['attach'], true);
		if($enclosures) {
			foreach($enclosures as $enc) {
				$o .= '<link rel="enclosure" '
				. (($enc['href']) ? 'href="' . $enc['href'] . '" ' : '')
				. (($enc['length']) ? 'length="' . $enc['length'] . '" ' : '')
				. (($enc['type']) ? 'type="' . $enc['type'] . '" ' : '')
				. ' />' . "\r\n";
			}
		}
	}
	if($compat_photos) {
		foreach($compat_photos as $enc) {
			$o .= '<link rel="enclosure" '
			. (($enc['href']) ? 'href="' . $enc['href'] . '" ' : '')
			. ((array_key_exists('length',$enc)) ? 'length="' . $enc['length'] . '" ' : '')
			. (($enc['type']) ? 'type="' . $enc['type'] . '" ' : '')
			. ' />' . "\r\n";
		}
	}

	if($item['term']) {
		foreach($item['term'] as $term) {
			$scheme = '';
			$label = '';
			switch($term['ttype']) {
				case TERM_UNKNOWN:
					$scheme = NAMESPACE_ZOT . '/term/unknown';
					$label = $term['term'];
					break;
				case TERM_HASHTAG:
				case TERM_COMMUNITYTAG:
					$scheme = NAMESPACE_ZOT . '/term/hashtag';
					$label = '#' . $term['term'];
					break;
				case TERM_MENTION:
					$scheme = NAMESPACE_ZOT . '/term/mention';
					$label = '@' . $term['term'];
					break;
				case TERM_CATEGORY:
					$scheme = NAMESPACE_ZOT . '/term/category';
					$label = $term['term'];
					break;
				default:
					break;
			}
			if(! $scheme)
				continue;

			$o .= '<category scheme="' . $scheme . '" term="' . $term['term'] . '" label="' . $label . '" />' . "\r\n";
		}
	}

	$o .= '</entry>' . "\r\n";

	// build array to pass to hook
	$x = [
		'item'     => $item,
		'type'     => $type,
		'author'   => $author,
		'owner'    => $owner,
		'comment'  => $comment,
		'abook_id' => $cid,
		'entry'    => $o
	];

	call_hooks('atom_entry', $x);

	return $x['entry'];
}

/**
 * @brief
 *
 * @param array $items
 * @return array
 */
function gen_asld($items) {
	$ret = array();
	if(! $items)
		return $ret;

	foreach($items as $item) {
		$ret[] = i2asld($item);
	}

	return $ret;
}

/**
 * @brief
 *
 * @param array $i
 * @return array
 */
function i2asld($i) {

	if(! $i)
		return array();

	$ret = array();

	$ret['@context'] = array( 'http://www.w3.org/ns/activitystreams', 'zot' => 'http://purl.org/zot/protocol');

	if($i['verb']) {
		if(strpos(dirname($i['verb'],'activitystrea.ms/schema/1.0'))) {
			$ret['@type'] = ucfirst(basename($i['verb']));
		}
		elseif(strpos(dirname($i['verb'],'purl.org/zot'))) {
			$ret['@type'] = 'zot:' . ucfirst(basename($i['verb']));
		}
	}
	$ret['@id'] = $i['plink'];

	$ret['published'] = datetime_convert('UTC','UTC',$i['created'],ATOM_TIME);

	// we need to pass the parent into this
//	if($i['id'] != $i['parent'] && $i['obj_type'] === ACTIVITY_OBJ_NOTE) {
//		$ret['inReplyTo'] = asencode_note
//	}

	if($i['obj_type'] === ACTIVITY_OBJ_NOTE)
		$ret['object'] = asencode_note($i);

	$ret['actor'] = asencode_person($i['author']);

	return $ret;
}

function asencode_note($i) {

	$ret = array();

	$ret['@type'] = 'Note';
	$ret['@id'] = $i['plink'];
	if($i['title'])
		$ret['title'] = bbcode($i['title']);

	$ret['content'] = bbcode($i['body']);
	$ret['zot:owner'] = asencode_person($i['owner']);
	$ret['published'] = datetime_convert('UTC','UTC',$i['created'],ATOM_TIME);
	if($i['created'] !== $i['edited'])
		$ret['updated'] = datetime_convert('UTC','UTC',$i['edited'],ATOM_TIME);

	return $ret;
}


function asencode_person($p) {
	$ret = array();
	$ret['@type'] = 'Person';
	$ret['@id'] = 'acct:' . $p['xchan_addr'];
	$ret['displayName'] = $p['xchan_name'];
	$ret['icon'] = array(
		'@type' => 'Link',
		'mediaType' => $p['xchan_photo_mimetype'],
		'href' => $p['xchan_photo_m']
	);
	$ret['url'] = array(
		'@type' => 'Link',
		'mediaType' => 'text/html',
		'href' => $p['xchan_url']
	);

	return $ret;
}