aboutsummaryrefslogtreecommitdiffstats
path: root/include/network.php
blob: f822b644df3750ae1224c5b02e49f9a7746f5d97 (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
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
<?php
/**
 * @file include/network.php
 */

/**
 * @brief Returns path to CA file.
 *
 * @return string
 */
function get_capath() {
	return appdirpath() . '/library/cacert.pem';
}

/**
 * @brief fetches an URL.
 *
 * @param string $url
 *    URL to fetch
 * @param boolean $binary default false
 *    TRUE if asked to return binary results (file download)
 * @param int $redirects default 0
 *    internal use, recursion counter
 * @param array $opts (optional parameters) assoziative array with:
 *  * \b accept_content => supply Accept: header with 'accept_content' as the value
 *  * \b timeout => int seconds, default system config value or 60 seconds
 *  * \b http_auth => username:password
 *  * \b novalidate => do not validate SSL certs, default is to validate using our CA list
 *  * \b nobody => only return the header
 *  * \b filep => stream resource to write body to. header and body are not returned when using this option.
 *
 * @return array an assoziative array with:
 *  * \e int \b return_code => HTTP return code or 0 if timeout or failure
 *  * \e boolean \b success => boolean true (if HTTP 2xx result) or false
 *  * \e string \b header => HTTP headers 
 *  * \e string \b body => fetched content
 */
function z_fetch_url($url, $binary = false, $redirects = 0, $opts = array()) {

	$ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");

	$ch = @curl_init($url);
	if(($redirects > 8) || (! $ch)) 
		return $ret;

	@curl_setopt($ch, CURLOPT_HEADER, true);
	@curl_setopt($ch, CURLINFO_HEADER_OUT, true);
	@curl_setopt($ch, CURLOPT_CAINFO, get_capath());
	@curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
	@curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
	@curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Red)");

	$ciphers = @get_config('system','curl_ssl_ciphers');
	if($ciphers)
		@curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, $ciphers);

	if(x($opts,'filep')) {
		@curl_setopt($ch, CURLOPT_FILE, $opts['filep']);
		@curl_setopt($ch, CURLOPT_HEADER, $false);
	}

	if(x($opts,'headers'))
		@curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);

	if(x($opts,'nobody'))
		@curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);

	if(x($opts,'timeout') && intval($opts['timeout'])) {
		@curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
	}
	else {
		$curl_time = intval(get_config('system','curl_timeout'));
		@curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
	}

	if(x($opts,'http_auth')) {
		// "username" . ':' . "password"
		@curl_setopt($ch, CURLOPT_USERPWD, $opts['http_auth']);
	}

	@curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 
		((x($opts,'novalidate') && intval($opts['novalidate'])) ? false : true));

	$prx = get_config('system','proxy');
	if(strlen($prx)) {
		@curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
		@curl_setopt($ch, CURLOPT_PROXY, $prx);
		$prxusr = @get_config('system','proxyuser');
		if(strlen($prxusr))
			@curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
	}
	if($binary)
		@curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);


	// don't let curl abort the entire application'
	// if it throws any errors.

	$s = @curl_exec($ch);

	$base = $s;
	$curl_info = @curl_getinfo($ch);
	$http_code = $curl_info['http_code'];
	//logger('fetch_url:' . $http_code . ' data: ' . $s);
	$header = '';

	// Pull out multiple headers, e.g. proxy and continuation headers
	// allow for HTTP/2.x without fixing code

	while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
		$chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
		$header .= $chunk;
		$base = substr($base,strlen($chunk));
	}

	if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307 || $http_code == 308) {
		$matches = array();
		preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
		$newurl = trim(array_pop($matches));
		if(strpos($newurl,'/') === 0)
			$newurl = $url . $newurl;
		$url_parsed = @parse_url($newurl);
		if (isset($url_parsed)) {
			@curl_close($ch);
			return z_fetch_url($newurl,$binary,++$redirects,$opts);
		}
	}

	$rc = intval($http_code);
	$ret['return_code'] = $rc;
	$ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
	if(! $ret['success']) {
		$ret['error'] = curl_error($ch);
		$ret['debug'] = $curl_info;
		logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
		logger('z_fetch_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
	}
	$ret['body'] = substr($s,strlen($header));
	$ret['header'] = $header;

	if(x($opts,'debug')) {
		$ret['debug'] = $curl_info;
	}

	@curl_close($ch);
	return($ret);
}


/**
 * @brief
 *
 * @param string $url
 *    URL to post
 * @param mixed $params
 *   The full data to post in a HTTP "POST" operation. This parameter can 
 *   either be passed as a urlencoded string like 'para1=val1&para2=val2&...' 
 *   or as an array with the field name as key and field data as value. If value 
 *   is an array, the Content-Type header will be set to multipart/form-data. 
 * @param int $redirects = 0
 *    internal use, recursion counter
 * @param array $opts (optional parameters)
 *    'accept_content' => supply Accept: header with 'accept_content' as the value
 *    'timeout' => int seconds, default system config value or 60 seconds
 *    'http_auth' => username:password
 *    'novalidate' => do not validate SSL certs, default is to validate using our CA list
 *    'filep' => stream resource to write body to. header and body are not returned when using this option.
 * @return array an assoziative array with:
 *  * \e int \b return_code => HTTP return code or 0 if timeout or failure
 *  * \e boolean \b success => boolean true (if HTTP 2xx result) or false
 *  * \e string \b header => HTTP headers
 *  * \e string \b body => content
 *  * \e string \b debug => from curl_info()
 */
function z_post_url($url,$params, $redirects = 0, $opts = array()) {

	$ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");

	$ch = curl_init($url);
	if(($redirects > 8) || (! $ch)) 
		return $ret;

	@curl_setopt($ch, CURLOPT_HEADER, true);
	@curl_setopt($ch, CURLINFO_HEADER_OUT, true);
	@curl_setopt($ch, CURLOPT_CAINFO, get_capath());
	@curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
	@curl_setopt($ch, CURLOPT_POST,1);
	@curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
	@curl_setopt($ch, CURLOPT_USERAGENT, "Red");

	$ciphers = @get_config('system','curl_ssl_ciphers');
	if($ciphers)
		@curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, $ciphers);

	if(x($opts,'filep')) {
		@curl_setopt($ch, CURLOPT_FILE, $opts['filep']);
		@curl_setopt($ch, CURLOPT_HEADER, $false);
	}

	if(x($opts,'headers')) {
		@curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
logger('headers: ' . print_r($opts['headers'],true) . 'redir: ' . $redirects);
	}
 
	if(x($opts,'nobody'))
		@curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);

	if(x($opts,'timeout') && intval($opts['timeout'])) {
		@curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
	}
	else {
		$curl_time = intval(get_config('system','curl_timeout'));
		@curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
	}

	if(x($opts,'http_auth')) {
		// "username" . ':' . "password"
		@curl_setopt($ch, CURLOPT_USERPWD, $opts['http_auth']);
	}

	@curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 
		((x($opts,'novalidate') && intval($opts['novalidate'])) ? false : true));

	$prx = get_config('system','proxy');
	if(strlen($prx)) {
		@curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
		@curl_setopt($ch, CURLOPT_PROXY, $prx);
		$prxusr = get_config('system','proxyuser');
		if(strlen($prxusr))
			@curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
	}

	// don't let curl abort the entire application
	// if it throws any errors.

	$s = @curl_exec($ch);

	$base = $s;
	$curl_info = @curl_getinfo($ch);
	$http_code = $curl_info['http_code'];

	$header = '';

	// Pull out multiple headers, e.g. proxy and continuation headers
	// allow for HTTP/2.x without fixing code

	while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
		$chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
		$header .= $chunk;
		$base = substr($base,strlen($chunk));
	}

	// would somebody take lighttpd and just shoot it?

	if($http_code == 417) {
		curl_close($ch);
		if($opts) {
			if($opts['headers'])
				$opts['headers'][] = 'Expect:';
			else
				$opts['headers'] = array('Expect:');
		}
		else
			$opts = array('headers' => array('Expect:'));
		return z_post_url($url,$params,++$redirects,$opts);
	}

	if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307 || $http_code == 308) {
		$matches = array();
		preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
		$newurl = trim(array_pop($matches));
		if(strpos($newurl,'/') === 0)
			$newurl = $url . $newurl;
		$url_parsed = @parse_url($newurl);
		if (isset($url_parsed)) {
			curl_close($ch);
			if($http_code == 303) {
				return z_fetch_url($newurl,false,$redirects++,$opts);
			} else {
				return z_post_url($newurl,$params,++$redirects,$opts);
			}
		}
	}
	$rc = intval($http_code);
	$ret['return_code'] = $rc;
	$ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
	if(! $ret['success']) {
		$ret['error'] = curl_error($ch);
		$ret['debug'] = $curl_info;
		logger('z_post_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
		logger('z_post_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
	}

	$ret['body'] = substr($s, strlen($header));
	$ret['header'] = $header;

	if(x($opts,'debug')) {
		$ret['debug'] = $curl_info;
	}

	curl_close($ch);
	return($ret);
}

/**
 * @brief Like z_post_url() but with an application/json HTTP header.
 *
 * Add a "Content-Type: application/json" HTTP-header to $opts and call z_post_url().
 *
 * @see z_post_url()
 *
 * @param string $url
 * @param array $params
 * @param number $redirects default 0
 * @param array $opts (optional) curl options
 * @return z_post_url()
 */
function z_post_url_json($url, $params, $redirects = 0, $opts = array()) {

	$opts = array_merge($opts, array('headers' => array('Content-Type: application/json')));

	return z_post_url($url,json_encode($params),$redirects,$opts);
}


function json_return_and_die($x, $content_type = 'application/json') {
	header("Content-type: $content_type");
	echo json_encode($x);
	killme();
}



// Generic XML return
// Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable 
// of $st and an optional text <message> of $message and terminates the current process. 


function xml_status($st, $message = '') {

	$xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');

	if($st)
		logger('xml_status returning non_zero: ' . $st . " message=" . $message);

	header( "Content-type: text/xml" );
	echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
	echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
	killme();
}



/**
 * @brief Send HTTP status header 
 *
 * @param int $val
 *    integer HTTP status result value
 * @param string $msg
 *    optional message
 * @returns nil
 */
function http_status($val, $msg = '') {
	if ($val >= 400)
		$msg = (($msg) ? $msg : 'Error');
	if ($val >= 200 && $val < 300)
		$msg = (($msg) ? $msg : 'OK');

	logger('http_status_exit ' . $val . ' ' . $msg);	
	header($_SERVER['SERVER_PROTOCOL'] . ' ' . $val . ' ' . $msg);
}



/**
 * @brief Send HTTP status header and exit.
 *
 * @param int $val
 *    integer HTTP status result value
 * @param string $msg
 *    optional message
 * @returns (does not return, process is terminated)
 */
function http_status_exit($val, $msg = '') {
	http_status($val, $msg);
	killme();
}



// convert an XML document to a normalised, case-corrected array
// used by webfinger


function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {

		// If we're getting too deep, bail out
		if ($recursion_depth > 512) {
				return(null);
		}

		if (!is_string($xml_element) &&
		!is_array($xml_element) &&
		(get_class($xml_element) == 'SimpleXMLElement')) {
				$xml_element_copy = $xml_element;
				$xml_element = get_object_vars($xml_element);
		}

		if (is_array($xml_element)) {
				$result_array = array();
				if (count($xml_element) <= 0) {
						return (trim(strval($xml_element_copy)));
				}

				foreach($xml_element as $key=>$value) {

						$recursion_depth++;
						$result_array[strtolower($key)] =
				convert_xml_element_to_array($value, $recursion_depth);
						$recursion_depth--;
				}
				if ($recursion_depth == 0) {
						$temp_array = $result_array;
						$result_array = array(
								strtolower($xml_element_copy->getName()) => $temp_array,
						);
				}

				return ($result_array);

		} else {
				return (trim(strval($xml_element)));
		}
}

// Take a URL from the wild, prepend http:// if necessary
// and check DNS to see if it's real (or check if is a valid IP address)
// return true if it's OK, false if something is wrong with it


function validate_url(&$url) {
	
	// no naked subdomains (allow localhost for tests)
	if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
		return false;
	if(substr($url,0,4) != 'http')
		$url = 'http://' . $url;
	$h = @parse_url($url);
	
	if(($h) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
		return true;
	}
	return false;
}

// checks that email is an actual resolvable internet address


function validate_email($addr) {

	if(get_config('system','disable_email_validation'))
		return true;

	if(! strpos($addr,'@'))
		return false;
	$h = substr($addr,strpos($addr,'@') + 1);

	if(($h) && (@dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
		return true;
	}
	return false;
}

// Check $url against our list of allowed sites,
// wildcards allowed. If allowed_sites is unset return true;
// If url is allowed, return true.
// otherwise, return false


function allowed_url($url) {

	$h = @parse_url($url);

	if(! $h) {
		return false;
	}

	$str_allowed = get_config('system','allowed_sites');
	if(! $str_allowed)
		return true;

	$found = false;

	$host = strtolower($h['host']);

	// always allow our own site

	if($host == strtolower($_SERVER['SERVER_NAME']))
		return true;

	$fnmatch = function_exists('fnmatch');
	$allowed = explode(',',$str_allowed);

	if(count($allowed)) {
		foreach($allowed as $a) {
			$pat = strtolower(trim($a));
			if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
				$found = true; 
				break;
			}
		}
	}
	return $found;
}

// check if email address is allowed to register here.
// Compare against our list (wildcards allowed).
// Returns false if not allowed, true if allowed or if
// allowed list is not configured.


function allowed_email($email) {


	$domain = strtolower(substr($email,strpos($email,'@') + 1));
	if(! $domain)
		return false;

	$str_allowed = get_config('system','allowed_email');
	$str_not_allowed = get_config('system','not_allowed_email');
		
	if(! $str_allowed && ! $str_not_allowed)
		return true;

	$return = false;
	$found_allowed = false;	
	$found_not_allowed = false;
	
	$fnmatch = function_exists('fnmatch');

	$allowed = explode(',',$str_allowed);

	if(count($allowed)) {
		foreach($allowed as $a) {
			$pat = strtolower(trim($a));
			if(($fnmatch && fnmatch($pat,$email)) || ($pat == $domain)) {
				$found_allowed = true; 
				break;
			}
		}
	}

	$not_allowed = explode(',',$str_not_allowed);

	if(count($not_allowed)) {
		foreach($not_allowed as $na) {
			$pat = strtolower(trim($na));
			if(($fnmatch && fnmatch($pat,$email)) || ($pat == $domain)) {
				$found_not_allowed = true; 
				break;
			}
		}
	}	
	
	if ($found_allowed) {
		$return = true;	
	} elseif (!$str_allowed && !$found_not_allowed) {
		$return = true;	
	}
	return $return;
}



function parse_xml_string($s,$strict = true) {
	if($strict) {
		if(! strstr($s,'<?xml'))
			return false;
		$s2 = substr($s,strpos($s,'<?xml'));
	}
	else
		$s2 = $s;
	libxml_use_internal_errors(true);

	$x = @simplexml_load_string($s2);
	if(! $x) {
		logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
		foreach(libxml_get_errors() as $err)
			logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
		libxml_clear_errors();
	}
	return $x;
}


function scale_external_images($s, $include_link = true, $scale_replace = false) {

	$a = get_app();

	// Picture addresses can contain special characters
	$s = htmlspecialchars_decode($s, ENT_COMPAT);

	$matches = null;
	$c = preg_match_all('/\[([zi])mg(.*?)\](.*?)\[\/[zi]mg\]/ism',$s,$matches,PREG_SET_ORDER);
	if($c) {
		require_once('include/photo/photo_driver.php');

		foreach($matches as $mtch) {
			logger('scale_external_image: ' . $mtch[2] . ' ' . $mtch[3]);
			
			if(substr($mtch[1],0,1) == '=') {
				$owidth = intval(substr($mtch[2],1));
				if(intval($owidth) > 0 && intval($owidth) < 1024)
					continue;
			}

			$hostname = str_replace('www.','',substr(z_root(),strpos(z_root(),'://')+3));
			if(stristr($mtch[3],$hostname))
				continue;

			// $scale_replace, if passed, is an array of two elements. The
			// first is the name of the full-size image. The second is the
			// name of a remote, scaled-down version of the full size image.
			// This allows Friendica to display the smaller remote image if
			// one exists, while still linking to the full-size image
			if($scale_replace)
				$scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[3]);
			else
				$scaled = $mtch[3];
			$i = z_fetch_url($scaled,true);


			$cache = get_config('system','itemcache');
			if (($cache != '') and is_dir($cache)) {
				$cachefile = $cache."/".hash("md5", $scaled);
				file_put_contents($cachefile, $i['body']);
			}

			// guess mimetype from headers or filename

			$type = guess_image_type($mtch[3],$i['header']);
			if(strpos($type,'image') === false)
				continue;
			
			if($i['success']) {
				$ph = photo_factory($i['body'], $type);
				if($ph->is_valid()) {
					$orig_width = $ph->getWidth();
					$orig_height = $ph->getHeight();

					if($orig_width > 1024 || $orig_height > 1024) {
						$tag = (($match[1] == 'z') ? 'zmg' : 'img');
						$ph->scaleImage(1024);
						$new_width = $ph->getWidth();
						$new_height = $ph->getHeight();
						logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
						$s = str_replace($mtch[0],'[' . $tag . '=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/' . $tag . ']'
							. "\n" . (($include_link) 
								? '[zrl=' . $mtch[2] . ']' . t('view full size') . '[/zrl]' . "\n"
								: ''),$s);
						logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
					}
				}
			}
		}
	}

	// replace the special char encoding

	$s = htmlspecialchars($s,ENT_COMPAT,'UTF-8');

	return $s;
}

/**
 * xml2array() will convert the given XML text to an array in the XML structure.
 * Link: http://www.bin-co.com/php/scripts/xml2array/
 * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
 * Arguments : $contents - The XML text
 *                $namespaces - true or false include namespace information in the returned array as array elements.
 *                $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
 *                $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
 * Examples: $array =  xml2array(file_get_contents('feed.xml'));
 *              $array =  xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
 */ 

function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
	if(!$contents) return array();

	if(!function_exists('xml_parser_create')) {
		logger('xml2array: parser function missing');
		return array();
	}


	libxml_use_internal_errors(true);
	libxml_clear_errors();

	if($namespaces)
		$parser = @xml_parser_create_ns("UTF-8",':');
	else
		$parser = @xml_parser_create();

	if(! $parser) {
		logger('xml2array: xml_parser_create: no resource');
		return array();
	}

	xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); 
	// http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
	@xml_parse_into_struct($parser, trim($contents), $xml_values);
	@xml_parser_free($parser);

	if(! $xml_values) {
		logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
		foreach(libxml_get_errors() as $err)
			logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
		libxml_clear_errors();
		return;
	}

	//Initializations
	$xml_array = array();
	$parents = array();
	$opened_tags = array();
	$arr = array();

	$current = &$xml_array; // Reference

	// Go through the tags.
	$repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
	foreach($xml_values as $data) {
		unset($attributes,$value); // Remove existing values, or there will be trouble

		// This command will extract these variables into the foreach scope
		// tag(string), type(string), level(int), attributes(array).
		extract($data); // We could use the array by itself, but this cooler.

		$result = array();
		$attributes_data = array();
		
		if(isset($value)) {
			if($priority == 'tag') $result = $value;
			else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
		}

		//Set the attributes too.
		if(isset($attributes) and $get_attributes) {
			foreach($attributes as $attr => $val) {
				if($priority == 'tag') $attributes_data[$attr] = $val;
				else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
			}
		}

		// See tag status and do the needed.
		if($namespaces && strpos($tag,':')) {
			$namespc = substr($tag,0,strrpos($tag,':')); 
			$tag = strtolower(substr($tag,strlen($namespc)+1));
			$result['@namespace'] = $namespc;
		}
		$tag = strtolower($tag);

		if($type == "open") {   // The starting of the tag '<tag>'
			$parent[$level-1] = &$current;
			if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
				$current[$tag] = $result;
				if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
				$repeated_tag_index[$tag.'_'.$level] = 1;

				$current = &$current[$tag];

			} else { // There was another element with the same tag name

				if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
					$current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
					$repeated_tag_index[$tag.'_'.$level]++;
				} else { // This section will make the value an array if multiple tags with the same name appear together
					$current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
					$repeated_tag_index[$tag.'_'.$level] = 2;
					
					if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
						$current[$tag]['0_attr'] = $current[$tag.'_attr'];
						unset($current[$tag.'_attr']);
					}

				}
				$last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
				$current = &$current[$tag][$last_item_index];
			}

		} elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
			//See if the key is already taken.
			if(!isset($current[$tag])) { //New Key
				$current[$tag] = $result;
				$repeated_tag_index[$tag.'_'.$level] = 1;
				if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;

			} else { // If taken, put all things inside a list(array)
				if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...

					// ...push the new element into that array.
					$current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
					
					if($priority == 'tag' and $get_attributes and $attributes_data) {
						$current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
					}
					$repeated_tag_index[$tag.'_'.$level]++;

				} else { // If it is not an array...
					$current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
					$repeated_tag_index[$tag.'_'.$level] = 1;
					if($priority == 'tag' and $get_attributes) {
						if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
							
							$current[$tag]['0_attr'] = $current[$tag.'_attr'];
							unset($current[$tag.'_attr']);
						}
						
						if($attributes_data) {
							$current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
						}
					}
					$repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
				}
			}

		} elseif($type == 'close') { // End of tag '</tag>'
			$current = &$parent[$level-1];
		}
	}
	
	return($xml_array);
}  


function email_header_encode($in_str, $charset = 'UTF-8') {
	$out_str = $in_str;
	$need_to_convert = false;

	for($x = 0; $x < strlen($in_str); $x ++) {
		if((ord($in_str[$x]) == 0) || ((ord($in_str[$x]) > 128))) {
			$need_to_convert = true;
		}
	}

	if(! $need_to_convert)
		return $in_str;

	if ($out_str && $charset) {

		// define start delimimter, end delimiter and spacer
		$end = "?=";
		$start = "=?" . $charset . "?B?";
		$spacer = $end . "\r\n " . $start;

		// determine length of encoded text within chunks
		// and ensure length is even
		$length = 75 - strlen($start) - strlen($end);

		/*
			[EDIT BY danbrown AT php DOT net: The following
			is a bugfix provided by (gardan AT gmx DOT de)
			on 31-MAR-2005 with the following note:
			"This means: $length should not be even,
			but divisible by 4. The reason is that in
			base64-encoding 3 8-bit-chars are represented
			by 4 6-bit-chars. These 4 chars must not be
			split between two encoded words, according
			to RFC-2047.
		*/
		$length = $length - ($length % 4);

		// encode the string and split it into chunks
		// with spacers after each chunk
		$out_str = base64_encode($out_str);
		$out_str = chunk_split($out_str, $length, $spacer);

		// remove trailing spacer and
		// add start and end delimiters
		$spacer = preg_quote($spacer,'/');
		$out_str = preg_replace("/" . $spacer . "$/", "", $out_str);
		$out_str = $start . $out_str . $end;
	}
	return $out_str;
}

function email_send($addr, $subject, $headers, $item) {
	//$headers .= 'MIME-Version: 1.0' . "\n";
	//$headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
	//$headers .= 'Content-Type: text/plain; charset=UTF-8' . "\n";
	//$headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";

	$part = uniqid("", true);

	$html	= prepare_body($item);

	$headers .= "Mime-Version: 1.0\n";
	$headers .= 'Content-Type: multipart/alternative; boundary="=_'.$part.'"'."\n\n";

	$body = "\n--=_".$part."\n";
	$body .= "Content-Transfer-Encoding: 8bit\n";
	$body .= "Content-Type: text/plain; charset=utf-8; format=flowed\n\n";

	$body .= html2plain($html)."\n";

	$body .= "--=_".$part."\n";
	$body .= "Content-Transfer-Encoding: 8bit\n";
	$body .= "Content-Type: text/html; charset=utf-8\n\n";

	$body .= '<html><head></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space; ">'.$html."</body></html>\n";

	$body .= "--=_".$part."--";

	//$message = '<html><body>' . $html . '</body></html>';
	//$message = html2plain($html);
	logger('notifier: email delivery to ' . $addr);
	mail($addr, $subject, $body, $headers);
}



function discover_by_url($url,$arr = null) {
	require_once('library/HTML5/Parser.php');

	$x = scrape_feed($url);
	if(! $x) {
		if(! $arr)
			return false;
		$network = (($arr['network']) ? $arr['network'] : 'unknown');
		$name = (($arr['name']) ? $arr['name'] : 'unknown');
		$photo = (($arr['photo']) ? $arr['photo'] : '');
		$addr = (($arr['addr']) ? $arr['addr'] : '');
		$guid = $url;
	}

	$profile = $url;

	logger('scrape_feed results: ' . print_r($x,true));

	if($x['feed_atom'])
		$guid = $x['feed_atom'];
	if($x['feed_rss'])
		$guid = $x['feed_rss'];

	if(! $guid)
		return false;


	// try and discover stuff from the feeed

	require_once('library/simplepie/simplepie.inc');
	$feed = new SimplePie();
	$level = 0;
    $x = z_fetch_url($guid,false,$level,array('novalidate' => true));
	if(! $x['success']) {
		logger('probe_url: feed fetch failed for ' . $poll);
		return false;
	}
	$xml = $x['body'];
	logger('probe_url: fetch feed: ' . $guid . ' returns: ' . $xml, LOGGER_DATA);
	logger('probe_url: scrape_feed: headers: ' . $x['header'], LOGGER_DATA);

	// Don't try and parse an empty string
	$feed->set_raw_data(($xml) ? $xml : '<?xml version="1.0" encoding="utf-8" ?><xml></xml>');

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

	$name = unxmlify(trim($feed->get_title()));
	$photo = $feed->get_image_url();
	$author = $feed->get_author();

	if($author) {
		if(! $name)
			$name = unxmlify(trim($author->get_name()));
		if(! $name) {
			$name = trim(unxmlify($author->get_email()));
			if(strpos($name,'@') !== false)
				$name = substr($name,0,strpos($name,'@'));
		}
		if(! $profile && $author->get_link())
			$profile = trim(unxmlify($author->get_link()));
		if(! $photo) {
			$rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
			if($rawtags) {
				$elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
				if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo'))
					$photo = $elems['link'][0]['attribs']['']['href'];
			}
		}
	}
	else {
		$item = $feed->get_item(0);
		if($item) {
			$author = $item->get_author();
			if($author) {
				if(! $name) {
					$name = trim(unxmlify($author->get_name()));
					if(! $name)
						$name = trim(unxmlify($author->get_email()));
					if(strpos($name,'@') !== false)
						$name = substr($name,0,strpos($name,'@'));
				}
				if(! $profile && $author->get_link())
					$profile = trim(unxmlify($author->get_link()));
			}
			if(! $photo) {
				$rawmedia = $item->get_item_tags('http://search.yahoo.com/mrss/','thumbnail');
				if($rawmedia && $rawmedia[0]['attribs']['']['url'])
					$photo = unxmlify($rawmedia[0]['attribs']['']['url']);
			}
			if(! $photo) {
				$rawtags = $item->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
				if($rawtags) {
					$elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
					if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo'))
						$photo = $elems['link'][0]['attribs']['']['href'];
				}
			}
		}
	}
	if($poll === $profile)
		$lnk = $feed->get_permalink();
	if(isset($lnk) && strlen($lnk))
		$profile = $lnk;

	if(! $network) {
		$network = 'rss';
	}

	if(! $name)
		$name = notags($feed->get_description());

	if(! $guid)
		return false;

	$r = q("select * from xchan where xchan_hash = '%s' limit 1",
		dbesc($guid)
	);
	if($r)
		return true;

	if(! $photo)
		$photo = z_root() . '/images/rss_icon.png';

	$r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_pubkey, xchan_addr, xchan_url, xchan_name, xchan_network, xchan_instance_url, xchan_name_date ) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
		dbesc($guid),
		dbesc($guid),
		dbesc($pubkey),
		dbesc($addr),
		dbesc($profile),
		dbesc($name),
		dbesc($network),
		dbesc(z_root()),
		dbesc(datetime_convert())
	);

	$photos = import_xchan_photo($photo,$guid);
	$r = q("update xchan set xchan_photo_date = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_hash = '%s'",
		dbesc(datetime_convert()),
		dbesc($photos[0]),
		dbesc($photos[1]),
		dbesc($photos[2]),
		dbesc($photos[3]),
		dbesc($guid)
	);
	return true;

}


function discover_by_webbie($webbie) {
	require_once('library/HTML5/Parser.php');

	$result   = array();

	$network  = null;

	$diaspora = false;
	$gnusoc   = false;
	$dfrn     = false;
	
	$has_salmon = false;
	$salmon_key = false;
	$atom_feed = false;
	$diaspora_base = '';
	$diaspora_guid = '';
	$diaspora_key = '';

	$webbie = strtolower($webbie);

	$x = webfinger_rfc7033($webbie,true);
	if($x && array_key_exists('links',$x) && $x['links']) {
		foreach($x['links'] as $link) {
			if(array_key_exists('rel',$link)) {

				// If we discover zot - don't search further; grab the info and get out of
				// here. 

				if($link['rel'] === PROTOCOL_ZOT) {
					logger('discover_by_webbie: zot found for ' . $webbie, LOGGER_DEBUG);
					if(array_key_exists('zot',$x) && $x['zot']['success'])
						$i = import_xchan($x['zot']);
					else {
						$z = z_fetch_url($link['href']);
						if($z['success']) {
							$j = json_decode($z['body'],true);
							$i = import_xchan($j);
							return true;
						}
					}
				}
				if($link['rel'] == NAMESPACE_DFRN) {
					 $dfrn = $link['href'];
				}
				if($link['rel'] == 'magic-public-key') {
        			if(substr($link['href'],0,5) === 'data:') {
						$salmon_key = convert_salmon_key($link['href']);
					}
				}
				if($link['rel'] == 'salmon') {
					$has_salmon = true;
					$salmon = $link['href'];
				}
				if($link['rel'] == 'http://schemas.google.com/g/2010#updates-from') {
					$atom_feed = $link['href'];
				}
			}
		}
	}

	logger('webfinger: ' . print_r($x,true), LOGGER_DATA, LOG_INFO);

	$arr = array('address' => $webbie, 'success' => false, 'webfinger' => $x);
	call_hooks('discover_channel_webfinger', $arr);
	if($arr['success'])
		return true;

	$aliases = array();

	// Now let's make some decisions on what we may need
	// to obtain further info

	$probe_atom  = false;
	$probe_old   = false;
	$probe_hcard = false;

	$address  = '';
	$location = '';
	$nickname = '';
	$fullname = '';
	$avatar   = '';
	$pubkey   = '';

	if(is_array($x)) {
		if(array_key_exists('address',$x)) 
			$address = $x['address'];
		if(array_key_exists('location',$x)) 
			$location = $x['location'];
		if(array_key_exists('nickname',$x)) 
			$nickname = $x['nickname'];
	}

	if(! $x)
		$probe_old = true;

	if($probe_old) {
		$y = old_webfinger($webbie);			
		if($y) {
			logger('old_webfinger: ' . print_r($x,true));
			foreach($y as $link) {
				if($link['@attributes']['rel'] === NAMESPACE_DFRN)
					$dfrn = unamp($link['@attributes']['href']);				
				if($link['@attributes']['rel'] === 'salmon')
					$notify = unamp($link['@attributes']['href']);
	 			if($link['@attributes']['rel'] === NAMESPACE_FEED)
					$poll = unamp($link['@attributes']['href']);
				if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
					$hcard = unamp($link['@attributes']['href']);
				if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
					$profile = unamp($link['@attributes']['href']);
				if($link['@attributes']['rel'] === 'http://portablecontacts.net/spec/1.0')
					$poco = unamp($link['@attributes']['href']);
				if($link['@attributes']['rel'] === 'http://joindiaspora.com/seed_location') {
					$diaspora_base = unamp($link['@attributes']['href']);
					$diaspora = true;
				}
				if($link['@attributes']['rel'] === 'http://joindiaspora.com/guid') {
					$diaspora_guid = unamp($link['@attributes']['href']);
					$diaspora = true;
				}
				if($link['@attributes']['rel'] === 'diaspora-public-key') {
					$diaspora_key = base64_decode(unamp($link['@attributes']['href']));
					if(strstr($diaspora_key,'RSA '))
						$pubkey = rsatopem($diaspora_key);
					else
						$pubkey = $diaspora_key;
					$diaspora = true;
				}
				if($link['@attributes']['rel'] == 'magic-public-key') {
        			if(substr($link['@attributes']['href'],0,5) === 'data:') {
						$salmon_key = convert_salmon_key($link['@attributes']['href']);
					}
				}
				if($link['@attributes']['rel'] == 'salmon') {
					$has_salmon = true;
					$salmon = $link['@attributes']['href'];
				}

				if($link['@attributes']['rel'] == 'http://schemas.google.com/g/2010#updates-from') {
					$atom_feed = $link['@attributes']['href'];
				}
				if($link['@attributes']['rel'] === 'alias') {
					$aliases[] = $link['@attributes']['href'];
				}
				if($link['@attributes']['rel'] === 'subject') {
					$subject = $link['@attributes']['href'];
				}
			}
		}
	}

	if($subject || $aliases) {
		if(strpos($webbie,'@')) {
			$rhs = substr($webbie,strpos($webbie,'@')+1);
		}
		else {
			$m = parse_url($webbie);
			if($m) {
				$rhs = $m['host'] . (($m['port']) ? ':' . $m['port'] : '');
			}
		}

		$v = array('subject' => $subject,'aliases' => $aliases);
		$address = find_webfinger_address($v,$rhs);
		$location = find_webfinger_location($v,$rhs);
		if($address)
			$nickname = substr($address,0,strpos($address,'@'));

	}

	if($salmon_key && $has_salmon && $atom_feed && (! $dfrn) && (! $diaspora)) {
		$gnusoc = true;
		$probe_atom = true;
	}

	if(! $pubkey)
		$pubkey = $salmon_key;

	if(($dfrn || $diaspora) && $hcard)
		$probe_hcard = true;

	if(! $fullname)
		$fullname = $nickname;

	if($probe_atom) {
		$k = z_fetch_url($atom_feed);
		if($k['success'])
			$feed_meta = feed_meta($k['body']);
		if($feed_meta) {

			// stash any discovered pubsubhubbub hubs in case we need to follow them
			// this will save an expensive lookup later

			if($feed_meta['hubs'] && $address) {
				set_xconfig($address,'system','push_hubs',$feed_meta['hubs']);
				set_xconfig($address,'system','feed_url',$atom_feed);
			}
			if($feed_meta['author']['author_name']) {
				$fullname = $feed_meta['author']['author_name'];
			}
			if(! $avatar) {
				if($feed_meta['author']['author_photo'])
					$avatar = $feed_meta['author']['author_photo'];
			}

			// for GNU-social over-ride any url aliases we may have picked up in webfinger
			// The author.uri element in the feed is likely to be more accurate

			if($gnusoc && $feed_meta['author']['author_uri'])
				$location = $feed_meta['author']['author_uri'];
		}
	}
	else {
		if($probe_hcard) {
			$vcard = scrape_vcard($hcard);
			if($vcard) {
				logger('vcard: ' . print_r($vcard,true), LOGGER_DATA);
				if($vcard['fn'])
					$fullname = $vcard['fn'];
				if($vcard['photo'] && (strpos($vcard['photo'],'http') !== 0))
					$vcard['photo'] = $diaspora_base . '/' . $vcard['photo'];			
				if(! $avatar)
					$avatar = $vcard['photo'];

			}
		}
	}

	if(($profile) && (! $location))
		$location = $profile;

	if($location) { 
		$m = parse_url($location);
		$base = $m['scheme'] . '://' . $m['host'];
		$host = $m['host'];
	}


	if($diaspora && $diaspora_base && $diaspora_guid) {
		if($dfrn)
			$network = 'friendica-over-diaspora';
		else
			$network = 'diaspora';

		$base = trim($diaspora_base,'/');
		$notify = $base . '/receive';

	}
	else {
		if($gnusoc) {
			$network = 'gnusoc';
			$notify = $salmon;
		}
	}


	logger('network: ' . $network);
	logger('address: ' . $address);
	logger('fullname: ' . $fullname);
	logger('pubkey: ' . $pubkey);
	logger('location: ' . $location);



	// if we have everything we need, let's create the records

	if($network && $address && $fullname && $pubkey && $location) {	
		$r = q("select * from xchan where xchan_hash = '%s' limit 1",
			dbesc($address)
		);
		if($r) {
			$r = q("update xchan set xchan_name = '%s', xchan_network = '%s', xchan_name_date = '%s' where xchan_hash = '%s' limit 1",
				dbesc($fullname),
				dbesc($network),
				dbesc(datetime_convert()),
				dbesc($address)
			);
		}
		else {
			$r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_pubkey, xchan_addr, xchan_url, xchan_name, xchan_network, xchan_name_date ) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
				dbesc($address),
				dbesc(($diaspora_guid) ? $diaspora_guid : $location),
				dbesc($pubkey),
				dbesc($address),
				dbesc($location),
				dbesc($fullname),
				dbesc($network),
				dbescdate(datetime_convert())
			);
		}

		$r = q("select * from hubloc where hubloc_hash = '%s' limit 1",
			dbesc($address)
		);

		if(! $r) {
			$r = q("insert into hubloc ( hubloc_guid, hubloc_hash, hubloc_addr, hubloc_network, hubloc_url, hubloc_host, hubloc_callback, hubloc_updated, hubloc_primary ) values ('%s','%s','%s','%s','%s','%s','%s','%s', 1)",
				dbesc(($diaspora_guid) ? $diaspora_guid : $location),
				dbesc($address),
				dbesc($address),
				dbesc($network),
				dbesc($base),
				dbesc($host),
				dbesc($notify),
				dbescdate(datetime_convert())
			);
		}
		$photos = import_xchan_photo($avatar,$address);
		$r = q("update xchan set xchan_photo_date = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_hash = '%s'",
			dbescdate(datetime_convert()),
			dbesc($photos[0]),
			dbesc($photos[1]),
			dbesc($photos[2]),
			dbesc($photos[3]),
			dbesc($address)
		);
		return true;
	}
	return false;
}



function webfinger_rfc7033($webbie,$zot = false) {


	if(strpos($webbie,'@')) {
		$lhs = substr($webbie,0,strpos($webbie,'@'));
		$rhs = substr($webbie,strpos($webbie,'@')+1);
		$resource = 'acct:' . $webbie;
	}
	else {
		$m = parse_url($webbie);
		if($m) {
			if($m['scheme'] !== 'https')
				return false;
			$rhs = $m['host'] . (($m['port']) ? ':' . $m['port'] : '');
			$resource = urlencode($webbie);
		}
		else
			return false;
	}
	logger('fetching url from resource: ' . $rhs . ':' . $webbie);

	$s = z_fetch_url('https://' . $rhs . '/.well-known/webfinger?f=&resource=' . $resource . (($zot) ? '&zot=1' : ''));

	if($s['success']) {
		$j = json_decode($s['body'],true);

		// We could have a number of URL aliases and webbies
		// make an executive decision about the most likely "best" of each
		// by comparing against some examples from known networks we're likely to encounter.
		// Otherwise we have to store every alias that we may ever encounter and 
		// validate every URL we ever find against every possible alias

		// @fixme pump.io is going to be a real bugger since it doesn't return subject or aliases
		// or provide lookup by url

		$j['address'] = find_webfinger_address($j,$rhs);
		$j['location'] = find_webfinger_location($j,$rhs);
		if($j['address'])
			$j['nickname'] = substr($j['address'],0,strpos($j['address'],'@'));
	}
	else
		return false;

	return($j);
}

function find_webfinger_address($j,$rhs) {
	if(is_array($j) && ($j)) {
		if(strpos($j['subject'],'acct:') !== false && strpos($j['subject'],'@' . $rhs))
			return str_replace('acct:','',$j['subject']);
		if($j['aliases']) {
			foreach($j['aliases'] as $alias) {
				if(strpos($alias,'acct:') !== false && strpos($alias,'@' . $rhs)) {
					return str_replace('acct:','',$alias);
				}
			}
		}
	}
	return '';
}


function find_webfinger_location($j,$rhs) {
	if(is_array($j) && ($j)) {
		if(strpos($j['subject'],'http') === 0) {
			$x = match_webfinger_location($j['subject'],$rhs);
			if($x)
				return $x;
		}
		if($j['aliases']) {
			foreach($j['aliases'] as $alias) {
				if(strpos($alias,'http') === 0) {
					$x = match_webfinger_location($alias,$rhs);
					if($x)
						return($x);
				}
			}
		}
	}
	return '';
}

function match_webfinger_location($s,$h) {

	// GNU-social and the older StatusNet - the $host/user/123 form doesn't work
	if(preg_match('|' . $h . '/index.php/user/([0-9]*?)$|',$s))
		return $s;
	// Redmatrix / hubzilla
	if(preg_match('|' . $h . '/channel/|',$s))
		return $s;
	// Friendica
	if(preg_match('|' . $h . '/profile/|',$s))
		return $s;

	$arr = array('test' => $s, 'host' => $h, 'success' => false);
	call_hooks('match_webfinger_location',$arr);
	if($arr['success'])
		return $s;
	return '';
}
	






function old_webfinger($webbie) {

	$host = '';
	if(strstr($webbie,'@'))
		$host = substr($webbie,strpos($webbie,'@') + 1);

	if(strlen($host)) {
		$tpl = fetch_lrdd_template($host);
		logger('old_webfinger: lrdd template: ' . $tpl,LOGGER_DATA);
		if(strlen($tpl)) {
			$pxrd = str_replace('{uri}', urlencode('acct:' . $webbie), $tpl);
			logger('old_webfinger: pxrd: ' . $pxrd,LOGGER_DATA);
			$links = fetch_xrd_links($pxrd);
			if(! count($links)) {
				// try with double slashes
				$pxrd = str_replace('{uri}', urlencode('acct://' . $webbie), $tpl);
				logger('old_webfinger: pxrd: ' . $pxrd,LOGGER_DATA);
				$links = fetch_xrd_links($pxrd);
			}
			return $links;
		}
	}
	return array();
}


function fetch_lrdd_template($host) {
	$tpl = '';

	$url1 = 'https://' . $host . '/.well-known/host-meta' ;
	$url2 = 'http://' . $host . '/.well-known/host-meta' ;
	$links = fetch_xrd_links($url1);
	logger('fetch_lrdd_template from: ' . $url1, LOGGER_DEBUG);
	logger('template (https): ' . print_r($links,true),LOGGER_DEBUG);
	if(! count($links)) {
		logger('fetch_lrdd_template from: ' . $url2);
		$links = fetch_xrd_links($url2);
		logger('template (http): ' . print_r($links,true),LOGGER_DEBUG);
	}
	if(count($links)) {
		foreach($links as $link)
			if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd' && (!$link['@attributes']['type'] || $link['@attributes']['type'] === 'application/xrd+xml'))
				$tpl = $link['@attributes']['template'];
	}
	if(! strpos($tpl,'{uri}'))
		$tpl = '';
	return $tpl;

}


function fetch_xrd_links($url) {

	logger('fetch_xrd_links: ' . $url, LOGGER_DEBUG);

	$redirects = 0;
	$x = z_fetch_url($url,false,$redirects,array('timeout' => 20));

	if(! $x['success'])
		return array();

	$xml = $x['body'];
	logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);

	if ((! $xml) || (! stristr($xml,'<xrd')))
		return array();

	// fix diaspora's bad xml
	$xml = str_replace(array('href=&quot;','&quot;/>'),array('href="','"/>'),$xml);

	$h = parse_xml_string($xml);
	if(! $h)
		return array();

	$arr = convert_xml_element_to_array($h);

	$links = array();

	if(isset($arr['xrd']['link'])) {
		$link = $arr['xrd']['link'];

		if(! isset($link[0]))
			$links = array($link);
		else
			$links = $link;
	}
	if(isset($arr['xrd']['alias'])) {
		$alias = $arr['xrd']['alias'];
		if(! isset($alias[0]))
			$aliases = array($alias);
		else
			$aliases = $alias;
		if(is_array($aliases) && count($aliases)) {
			foreach($aliases as $alias) {
				$links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
			}
		}
	}

	if(isset($arr['xrd']['subject'])) {
		$links[]['@attributes'] = array('rel' => 'subject' , 'href' => $arr['xrd']['subject']);
	}

	logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);

	return $links;
}


function scrape_vcard($url) {

	$a = get_app();

	$ret = array();

	logger('scrape_vcard: url=' . $url);

	$x = z_fetch_url($url);
	if(! $x['success'])
		return $ret;

	$s = $x['body'];

	if(! $s)
		return $ret;

	$headers = $x['header'];
	$lines = explode("\n",$headers);
	if(count($lines)) {
		foreach($lines as $line) {
			// don't try and run feeds through the html5 parser
			if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
				return ret;
		}
	}

	try {
		$dom = HTML5_Parser::parse($s);
	} catch (DOMException $e) {
		logger('scrape_vcard: parse error: ' . $e);
	}

	if(! $dom)
		return $ret;

	// Pull out hCard profile elements

	$largest_photo = 0;

	$items = $dom->getElementsByTagName('*');
	foreach($items as $item) {
		if(attribute_contains($item->getAttribute('class'), 'vcard')) {
			$level2 = $item->getElementsByTagName('*');
			foreach($level2 as $x) {
				if(attribute_contains($x->getAttribute('id'),'pod_location'))
					$ret['pod_location'] = $x->textContent;
				if(attribute_contains($x->getAttribute('class'),'fn'))
					$ret['fn'] = $x->textContent;
				if(attribute_contains($x->getAttribute('class'),'uid'))
					$ret['uid'] = $x->textContent;
				if(attribute_contains($x->getAttribute('class'),'nickname'))
					$ret['nick'] = $x->textContent;
				if(attribute_contains($x->getAttribute('class'),'searchable'))
					$ret['searchable'] = $x->textContent;
				if(attribute_contains($x->getAttribute('class'),'key'))
					$ret['public_key'] = $x->textContent;
				if(attribute_contains($x->getAttribute('class'),'given_name'))
					$ret['given_name'] = $x->textContent;
				if(attribute_contains($x->getAttribute('class'),'family_name'))
					$ret['family_name'] = $x->textContent;
				if(attribute_contains($x->getAttribute('class'),'url'))
					$ret['url'] = $x->textContent;

				if((attribute_contains($x->getAttribute('class'),'photo'))
					|| (attribute_contains($x->getAttribute('class'),'avatar'))) {
					$size = intval($x->getAttribute('width'));
					if(($size > $largest_photo) || (! $largest_photo)) {
						$ret['photo'] = $x->getAttribute('src');
						$largest_photo = $size;
					}
				}
			}
		}
	}

	return $ret;
}



function scrape_feed($url) {

	$a = get_app();

	$ret = array();
	$level = 0;
	$x = z_fetch_url($url,false,$level,array('novalidate' => true));

	if(! $x['success'])
		return $ret;

	$headers = $x['header'];
	$code = $x['return_code'];
	$s = $x['body'];

	logger('scrape_feed: returns: ' . $code . ' headers=' . $headers, LOGGER_DEBUG);

	if(! $s) {
		logger('scrape_feed: no data returned for ' . $url);
		return $ret;
	}


	$lines = explode("\n",$headers);
	if(count($lines)) {
		foreach($lines as $line) {
			if(stristr($line,'content-type:')) {
				if(stristr($line,'application/atom+xml') || stristr($s,'<feed')) {
					$ret['feed_atom'] = $url;
					return $ret;
				}
 				if(stristr($line,'application/rss+xml') || stristr($s,'<rss')) {
					$ret['feed_rss'] = $url;
					return $ret;
				}
			}
		}
		// perhaps an RSS version 1 feed with a generic or incorrect content-type?
		if(stristr($s,'</item>')) {
			$ret['feed_rss'] = $url;
			return $ret;
		}
	}

	try {
		$dom = HTML5_Parser::parse($s);
	} catch (DOMException $e) {
		logger('scrape_feed: parse error: ' . $e);
	}

	if(! $dom) {
		logger('scrape_feed: failed to parse.');
		return $ret;
	}


	$head = $dom->getElementsByTagName('base');
	if($head) {
		foreach($head as $head0) {
			$basename = $head0->getAttribute('href');
			break;
		}
	}
	if(! $basename)
		$basename = implode('/', array_slice(explode('/',$url),0,3)) . '/';

	$items = $dom->getElementsByTagName('link');

	// get Atom/RSS link elements, take the first one of either.

	if($items) {
		foreach($items as $item) {
			$x = $item->getAttribute('rel');
			if(($x === 'alternate') && ($item->getAttribute('type') === 'application/atom+xml')) {
				if(! x($ret,'feed_atom'))
					$ret['feed_atom'] = $item->getAttribute('href');
			}
			if(($x === 'alternate') && ($item->getAttribute('type') === 'application/rss+xml')) {
				if(! x($ret,'feed_rss'))
					$ret['feed_rss'] = $item->getAttribute('href');
			}
		}
	}

	// Drupal and perhaps others only provide relative URL's. Turn them into absolute.

	if(x($ret,'feed_atom') && (! strstr($ret['feed_atom'],'://')))
		$ret['feed_atom'] = $basename . $ret['feed_atom'];
	if(x($ret,'feed_rss') && (! strstr($ret['feed_rss'],'://')))
		$ret['feed_rss'] = $basename . $ret['feed_rss'];

	return $ret;
}



function service_plink($contact, $guid) {

	$plink = '';

	$m = parse_url($contact['xchan_url']);
	if($m) {
		$url = $m['scheme'] . '://' . $m['host'] . (($m['port']) ? ':' . $m['port'] : '');
	}
	else
		$url = 'https://' . substr($contact['xchan_addr'],strpos($contact['xchan_addr'],'@')+1);

	$handle = substr($contact['xchan_addr'], 0, strpos($contact['xchan_addr'],'@'));

	if($contact['xchan_network'] === 'diaspora')
		$plink = $url . '/posts/' . $guid;
	if($contact['xchan_network'] === 'friendica-over-diaspora')
		$plink = $url . '/display/' . $handle . '/' . $guid;
	if($contact['xchan_network'] === 'zot')
		$plink = $url . '/channel/' . $handle . '?f=&mid=' . $guid;

	return $plink;
}


function format_and_send_email($sender,$xchan,$item) {

	require_once('include/enotify.php');

	$title = $item['title'];
	$body = $item['body'];

    $textversion = strip_tags(html_entity_decode(bbcode(str_replace(array("\\r", "\\n"), array( "", "\n"), $body)),ENT_QUOTES,'UTF-8'));

	$htmlversion = bbcode(str_replace(array("\\r","\\n"), array("","<br />\n"),$body));

   $banner     = t('$Projectname Notification');
    $product    = t('$projectname'); // PLATFORM_NAME;
    $siteurl    = z_root();
    $thanks     = t('Thank You,');
    $sitename   = get_config('system','sitename');
    $site_admin = sprintf( t('%s Administrator'), $sitename);

		// load the template for private message notifications
		$tpl = get_markup_template('email_notify_html.tpl');
		$email_html_body = replace_macros($tpl,array(
			'$banner'	    => $banner,
			'$notify_icon'  => Zotlabs\Project\System::get_notify_icon(),
			'$product'	    => $product,
			'$preamble'	    => '',
			'$sitename'	    => $sitename,
			'$siteurl'	    => $siteurl,
			'$source_name'  => $sender['xchan_name'],
			'$source_link'  => $sender['xchan_url'],
			'$source_photo' => $sender['xchan_photo_m'],
			'$username'	    => $xchan['xchan_name'],
			'$hsitelink'	=> $datarray['hsitelink'],
			'$hitemlink'	=> $datarray['hitemlink'],
			'$thanks'	    => $thanks,
			'$site_admin'   => $site_admin,
			'$title'		=> $title,
			'$htmlversion'  => $htmlversion,
		));

		// load the template for private message notifications
		$tpl = get_markup_template('email_notify_text.tpl');
		$email_text_body = replace_macros($tpl, array(
			'$banner'       => $banner,
			'$product'      => $product,
			'$preamble'     => '',
			'$sitename'     => $sitename,
			'$siteurl'      => $siteurl,
			'$source_name'  => $sender['xchan_name'],
			'$source_link'  => $sender['xchan_url'],
			'$source_photo' => $sender['xchan_photo_m'],
			'$username'     => $xchan['xchan_name'],
			'$hsitelink'    => $datarray['hsitelink'],
			'$hitemlink'    => $datarray['hitemlink'],
			'$thanks'       => $thanks,
			'$site_admin'   => $site_admin,
			'$title'        => $title,
			'$textversion'  => $textversion
		));

		$sender_name = t('Administrator');
		
  		$hostname = App::get_hostname();
	    if(strpos($hostname,':'))
    	    $hostname = substr($hostname,0,strpos($hostname,':'));
		$sender_email = 'noreply' . '@' . $hostname;

		// use the EmailNotification library to send the message

		enotify::send(array(
			'fromName'             => $product,
			'fromEmail'            => $sender_email,
			'replyTo'              => $sender_email,
			'toEmail'              => str_replace('mailto:','',$xchan['xchan_addr']),
			'messageSubject'       => (($title) ? $title : t('No Subject')),
			'htmlVersion'          => $email_html_body,
			'textVersion'          => $email_text_body,
			'additionalMailHeader' => '',
		));

}


function do_delivery($deliveries) {

	if(! (is_array($deliveries) && count($deliveries)))
		return;

	$interval = ((get_config('system','delivery_interval') !== false) 
			? intval(get_config('system','delivery_interval')) : 2 );

	$deliveries_per_process = intval(get_config('system','delivery_batch_count'));

	if($deliveries_per_process <= 0)
		$deliveries_per_process = 1;


	$deliver = array();
	foreach($deliveries as $d) {

		$deliver[] = $d;

		if(count($deliver) >= $deliveries_per_process) {
			proc_run('php','include/deliver.php',$deliver);
			$deliver = array();
			if($interval)
				@time_sleep_until(microtime(true) + (float) $interval);
		}
	}

	// catch any stragglers

	if($deliver)
		proc_run('php','include/deliver.php',$deliver);
	

}


function get_site_info() {

	global $db;
	global $a;

	$register_policy = Array('REGISTER_CLOSED', 'REGISTER_APPROVE', 'REGISTER_OPEN');
	$directory_mode = Array('DIRECTORY_MODE_NORMAL', 'DIRECTORY_MODE_PRIMARY', 'DIRECTORY_MODE_SECONDARY', 256 => 'DIRECTORY_MODE_STANDALONE');
		
	$sql_extra = '';

	$r = q("select * from channel left join account on account_id = channel_account_id where ( account_roles & 4096 )>0 and account_default_channel = channel_id");


	if($r) {
		$admin = array();
		foreach($r as $rr) {
			if($rr['channel_pageflags'] & PAGE_HUBADMIN)
				$admin[] = array( 'name' => $rr['channel_name'], 'address' => $rr['channel_address'] . '@' . App::get_hostname(), 'channel' => z_root() . '/channel/' . $rr['channel_address']);
		}
		if(! $admin) {
			foreach($r as $rr) {
				$admin[] = array( 'name' => $rr['channel_name'], 'address' => $rr['channel_address'] . '@' . App::get_hostname(), 'channel' => z_root() . '/channel/' . $rr['channel_address']);
			}
		}
	}
	else {
		$admin = false;
	}

	$def_service_class = get_config('system','default_service_class');
	if($def_service_class)
		$service_class = get_config('service_class',$def_service_class);
	else
		$service_class = false;

	$visible_plugins = array();
	if(is_array(App::$plugins) && count(App::$plugins)) {
		$r = q("select * from addon where hidden = 0");
		if(count($r))
			foreach($r as $rr)
				$visible_plugins[] = $rr['name'];
	}
	sort($visible_plugins);

	if(@is_dir('.git') && function_exists('shell_exec'))
		$commit = trim(@shell_exec('git log -1 --format="%h"'));
	if(! isset($commit) || strlen($commit) > 16)
		$commit = '';

	$site_info = get_config('system','info');
	$site_name = get_config('system','sitename');
	if(! get_config('system','hidden_version_siteinfo')) {
		$version = Zotlabs\Project\System::get_project_version();
		$tag = Zotlabs\Project\System::get_std_version();

		if(@is_dir('.git') && function_exists('shell_exec')) {
			$commit = trim( @shell_exec('git log -1 --format="%h"'));
		}

		if(! isset($commit) || strlen($commit) > 16)
			$commit = '';
	}
	else {
			$version = $commit = '';
	}
		
	//Statistics
	$channels_total_stat = intval(get_config('system','channels_total_stat'));
	$channels_active_halfyear_stat = intval(get_config('system','channels_active_halfyear_stat'));
	$channels_active_monthly_stat = intval(get_config('system','channels_active_monthly_stat'));
	$local_posts_stat = intval(get_config('system','local_posts_stat'));
	$hide_in_statistics = intval(get_config('system','hide_in_statistics'));
	$site_expire = intval(get_config('system', 'default_expire_days'));

	load_config('feature_lock');
	$locked_features = array();
	if(is_array(App::$config['feature_lock']) && count(App::$config['feature_lock'])) {
		foreach(App::$config['feature_lock'] as $k => $v) {
			if($k === 'config_loaded')
				continue;
			$locked_features[$k] = intval($v);
		}
	}


		
	$data = Array(
		'version' => $version,
		'version_tag' => $tag,
		'server_role' => Zotlabs\Project\System::get_server_role(),
		'commit' => $commit,
		'url' => z_root(),
		'plugins' => $visible_plugins,
		'register_policy' =>  $register_policy[get_config('system','register_policy')],
		'invitation_only' => intval(get_config('system','invitation_only')),
		'directory_mode' =>  $directory_mode[get_config('system','directory_mode')],
		'language' => get_config('system','language'),
		'rss_connections' => intval(get_config('system','feed_contacts')),
		'expiration' => $site_expire,
		'default_service_restrictions' => $service_class,
		'locked_features' => $locked_features,
		'admin' => $admin,
		'site_name' => (($site_name) ? $site_name : ''),
		'platform' => Zotlabs\Project\System::get_platform_name(),
		'dbdriver' => \DBA::$dba->getdriver(),
		'lastpoll' => get_config('system','lastpoll'),
		'info' => (($site_info) ? $site_info : ''),
		'channels_total' => $channels_total_stat,
		'channels_active_halfyear' => $channels_active_halfyear_stat,
		'channels_active_monthly' => $channels_active_monthly_stat,
		'local_posts' => $local_posts_stat,
		'hide_in_statistics' => $hide_in_statistics
	);
	return $data;
}



function check_siteallowed($url) {

	$retvalue = true;


	$arr = array('url' => $url);
	call_hooks('check_siteallowed',$arr);

	if(array_key_exists('allowed',$arr))
		return $arr['allowed'];

	$bl1 = get_config('system','whitelisted_sites');
	if(is_array($bl1) && $bl1) {
		foreach($bl1 as $bl) {
			if($bl1 === '*')
				$retvalue = true;
			if($bl && strpos($url,$bl) !== false)
				return true;
		}
	}
	$bl1 = get_config('system','blacklisted_sites');
	if(is_array($bl1) && $bl1) {
		foreach($bl1 as $bl) {
			if($bl1 === '*')
				$retvalue = false;
			if($bl && strpos($url,$bl) !== false) {
				return false;
			}
		}
	}
	return $retvalue;
}

function check_channelallowed($hash) {

	$retvalue = true;

	$arr = array('hash' => $hash);
	call_hooks('check_channelallowed',$arr);

	if(array_key_exists('allowed',$arr))
		return $arr['allowed'];

	$bl1 = get_config('system','whitelisted_channels');
	if(is_array($bl1) && $bl1) {
		foreach($bl1 as $bl) {
			if($bl1 === '*')
				$retvalue = true;
			if($bl && strpos($hash,$bl) !== false)
				return true;
		}
	}
	$bl1 = get_config('system','blacklisted_channels');
	if(is_array($bl1) && $bl1) {
		foreach($bl1 as $bl) {
			if($bl1 === '*')
				$retvalue = false;
			if($bl && strpos($hash,$bl) !== false) {
				return false;
			}
		}
	}
	return $retvalue;
}

function deliverable_singleton($xchan) {
	$r = q("select abook_instance from abook where abook_xchan = '%s' limit 1",
		dbesc($xchan['xchan_hash'])
	);
	if($r) {
		if(! $r[0]['abook_instance'])
			return true;
		if(strpos($r[0]['abook_instance'],z_root()) !== false)
			return true;
	}
	return false;
}