summaryrefslogtreecommitdiffstats
path: root/httprl.module
blob: 1fd1ed4c1dffec63d4f458959355b3dbabde4c74 (plain)
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
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
<?php
/**
 * @file
 * HTTP Parallel Request Library module.
 */

/**
 * Default maximum number of seconds a single request call may take.
 */
define('HTTPRL_TIMEOUT', 30.0);

/**
 * Default maximum number of seconds a function call may take.
 */
define('HTTPRL_GLOBAL_TIMEOUT', 120.0);

/**
 * Error code indicating that the request made by httprl_request() exceeded
 * the maximum allowed redirects without reaching the final target.
 */
define('HTTPRL_REQUEST_ALLOWED_REDIRECTS_EXHAUSTED', -2);

/**
 * Error code indicating that the call to fwrite() failed.
 */
define('HTTPRL_REQUEST_FWRITE_FAIL', -3);

/**
 * Error code indicating that all requests made by httprl_send_request
 * exceeded the specified timeout.
 */
define('HTTPRL_FUNCTION_TIMEOUT', -4);

/**
 * Error code indicating that this request made by stream_select() couldn't
 * open a read and/or write steam after a minimum of ~2.5 seconds.
 */
define('HTTPRL_STREAM_SELECT_TIMEOUT', -5);

/**
 * parse_url() was unable to parse the given url.
 */
define('HTTPRL_URL_PARSE_ERROR', -1001);

/**
 * Given URL is missing a schema (http, https, feed).
 */
define('HTTPRL_URL_MISSING_SCHEMA', -1002);

/**
 * Invalid schema. Only http, feed, and https allowed currently.
 */
define('HTTPRL_URL_INVALID_SCHEMA', -1003);

/**
 * An error occurred before the system connect() call. This is most likely due
 * to a problem initializing the stream.
 */
define('HTTPRL_ERROR_INITIALIZING_STREAM', -1004);

/**
 * Error code indicating that software caused the connection to be aborted.
 *
 * @see http://msdn.microsoft.com/en-us/library/aa924071.aspx
 */
define('HTTPRL_REQUEST_ABORTED', -10053);

/**
 * Error code indicating that the connection was forcibly closed by the remote
 * host.
 *
 * @see http://msdn.microsoft.com/en-us/library/aa924071.aspx
 */
define('HTTPRL_CONNECTION_RESET', -10054);

/**
 * Error code indicating that the request exceeded the specified timeout.
 *
 * @see http://msdn.microsoft.com/en-us/library/aa924071.aspx
 */
define('HTTPRL_REQUEST_TIMEOUT', -10060);

/**
 * Error code indicating that the endpoint server has refused or dropped the
 * connection.
 *
 * @see http://msdn.microsoft.com/en-us/library/aa924071.aspx
 */
define('HTTPRL_CONNECTION_REFUSED', -10061);

/**
 * Error code indicating that the host is unknown or can not be found.
 *
 * @see http://msdn.microsoft.com/en-us/library/aa924071.aspx
 */
define('HTTPRL_HOST_NOT_FOUND', -11001);

/**
 * HTTP encapsulation boundary string.
 */
define('HTTPRL_MULTIPART_BOUNDARY', '---------------------------' . str_replace('.', '', microtime(TRUE)));

/**
 * Implement hook_menu().
 */
function httprl_menu() {
  $items = array();

  // Non blocking test URL.
  $items['admin/httprl-test'] = array(
    'title' => 'HTTPRL',
    'page callback' => 'httprl_nonblockingtest_page',
    'access callback' => TRUE,
    'description' => 'Test URL to make sure non blocking requests work.',
    'type' => MENU_CALLBACK,
    'file' => 'httprl.nonblocktest.inc',
  );

  // Admin page.
  if (defined('VERSION') && substr(VERSION, 0, 1) >= 7) {
    $config_url = 'admin/config/development/httprl';
  }
  else {
    $config_url = 'admin/settings/httprl';
  }
  $items[$config_url] = array(
    'title' => 'HTTPRL',
    'description' => 'Configure HTTPRL settings.',
    'access arguments' => array('administer site configuration'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('httprl_admin_settings_form'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'httprl.admin.inc',
  );

  // Async Function Callback.
  $items['httprl_async_function_callback'] = array(
    'title' => 'HTTPRL',
    'page callback' => 'httprl_async_page',
    'access callback' => TRUE,
    'description' => 'URL for async function workers.',
    'type' => MENU_CALLBACK,
    'file' => 'httprl.async.inc',
  );

  return $items;
}

/**
 * Implement hook_cron().
 *
 * This hook should be ran about once a day to once an hour.
 */
function httprl_cron() {
  // Let expiration times vary by 30 seconds or so.
  $fuzz_factor = 30;

  // Remove expired locks from the semaphore database table.
  if (defined('VERSION') && substr(VERSION, 0, 1) >= 7) {
    db_delete('semaphore')
      ->condition('value', 'httprl')
      ->condition('expire', REQUEST_TIME - $fuzz_factor, '<')
      ->execute();
  }
  else {
    db_query("DELETE FROM {semaphore} WHERE value = 'httprl' AND expire < %f", time() - $fuzz_factor);
  }
}

/**
 * Helper function to build an URL for asynchronous requests to self.
 *
 * @param $path
 *   Path to a URI excluding everything to the left and including the base path.
 * @param $detect_schema
 *   If TRUE it will see if this request is https; if so, it will set the full
 *   url to be https as well.
 */
function httprl_build_url_self($path = '', $detect_schema = FALSE) {
  global $base_path, $conf;
  static $variable_loaded = FALSE;

  if (!empty($base_path)) {
    $root_path = $base_path;
  }
  else {
    // $_SERVER['SCRIPT_NAME'] can, in contrast to $_SERVER['PHP_SELF'], not
    // be modified by a visitor.
    if ($dir = trim(dirname($_SERVER['SCRIPT_NAME']), '\,/')) {
      $base_path = "/$dir/";
    }
    else {
      $root_path = '/';
    }
  }

  // Server auth.
  $auth = '';
  if (isset($_SERVER['AUTH_TYPE']) && $_SERVER['AUTH_TYPE'] == 'Basic') {
    $auth = $_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW'] . '@';
  }

  // Get Host.
  $ip = httprl_variable_get('httprl_server_addr', FALSE);
  if ($ip == -1) {
    $ip = $_SERVER['HTTP_HOST'];
  }
  elseif (empty($ip)) {
    $ip = empty($_SERVER['SERVER_ADDR']) ? '127.0.0.1' : $_SERVER['SERVER_ADDR'];
    // Check for IPv6. If IPv6 convert to IPv4 if possible.
    if (strpos($ip, ':') !== FALSE) {
      if ($_SERVER['SERVER_ADDR'] == '::1') {
        $ip = "127.0.0.1";
      }
      elseif (preg_match('/^::\d+.\d+.\d+.\d+$/', $ip)) {
        $ip = substr($ip, 2);
      }
      elseif (!empty($_SERVER['HTTP_HOST'])) {
        // Last option is to use the IP from the host name.
        $ip = gethostbyname($_SERVER['HTTP_HOST']);
      }
    }
  }

  // Port.
  $port = '';
//   if (   isset($_SERVER['SERVER_PORT'])
//       && is_numeric($_SERVER['SERVER_PORT'])
//       && ($_SERVER['SERVER_PORT'] != 80 || $_SERVER['SERVER_PORT'] != 443)
//         ) {
//     $port = ':' . $_SERVER['SERVER_PORT'];
//   }

  // http or https.
  $schema = httprl_get_server_schema() . '://';

  return $schema . $auth . $ip . $port . $root_path . $path;
}

/**
 * Run parse_url and handle any errors.
 *
 * @param $url
 *   String containing the URL to be parsed by parse_url().
 * @param &$result
 *   Result object; used only for error handling in this function.
 *
 * @return $uri
 *   Array from parse_url().
 */
function httprl_parse_url($url, &$result) {
  // Parse the URL and make sure we can handle the schema.
  $uri = @parse_url($url);

  // If the t function is not available use httprl_pr.
  if (function_exists('t')) {
    $t = 't';
  }
  else {
    $t = 'httprl_pr';
  }

  if (empty($uri)) {
    // Set error code for failed request.
    $result->error = $t('Unable to parse URL.');
    $result->code = HTTPRL_URL_PARSE_ERROR;
  }
  elseif (!isset($uri['scheme'])) {
    // Set error code for failed request.
    $result->error = $t('Missing schema.');
    $result->code = HTTPRL_URL_MISSING_SCHEMA;
  }

  return $uri;
}

/**
 * Set the default options in the $options array.
 *
 * @param &$options
 *   Array containing options.
 */
function httprl_set_default_options(&$options) {
  global $base_root;

  // Merge the default options.
  $options += array(
    'headers' => array(),
    'method' => 'GET',
    'data' => NULL,
    'max_redirects' => 3,
    'timeout' => HTTPRL_TIMEOUT,
    'context' => NULL,
    'blocking' => TRUE,
    'version' => '1.0',
    'referrer' => FALSE,
    'domain_connections' => 2,
    'global_connections' => 128,
    'global_timeout' => HTTPRL_GLOBAL_TIMEOUT,
    'chunk_size_read' => 32768,
    'chunk_size_write' => 1024,
    'async_connect' => TRUE,
  );

  // Merge the default headers.
  // Set user agent to drupal.
  // Set connection to closed to prevent keep-alive from causing a timeout.
  $options['headers'] += array(
    'User-Agent' => 'Drupal (+http://drupal.org/)',
    'Connection' => 'close',
  );

  // Set referrer to current page.
  if (!isset($options['headers']['Referer']) && !empty($options['referrer'])) {
    if (function_exists('request_uri')) {
      $options['headers']['Referer'] = $base_root . request_uri();
    }
  }

  // stream_socket_client() requires timeout to be a float.
  $options['timeout'] = (float) $options['timeout'];
}

/**
 * If server uses a proxy, change the request to utilize said proxy.
 *
 * @param &$uri
 *   Array from parse_url().
 * @param &$options
 *   Array containing options.
 * @param $url
 *   String containing the URL.
 *
 * @return $proxy_server
 *   String containing the proxy servers host name if one is to be used.
 */
function httprl_setup_proxy(&$uri, &$options, $url) {
  // Proxy setup
  $proxy_server = httprl_variable_get('proxy_server', '');
  // Use a proxy if one is defined and the host is not on the excluded list.
  if ($proxy_server && _httprl_use_proxy($uri['host'])) {
    // Set the scheme so we open a socket to the proxy server.
    $uri['scheme'] = 'proxy';
    // Set the path to be the full URL.
    $uri['path'] = $url;
    // Since the full URL is passed as the path, we won't use the parsed query.
    unset($uri['query']);

    // Add in username and password to Proxy-Authorization header if needed.
    if ($proxy_username = httprl_variable_get('proxy_username', '')) {
      $proxy_password = httprl_variable_get('proxy_password', '');
      $options['headers']['Proxy-Authorization'] = 'Basic ' . base64_encode($proxy_username . (!empty($proxy_password) ? ":" . $proxy_password : ''));
    }
    // Some proxies reject requests with any User-Agent headers, while others
    // require a specific one.
    $proxy_user_agent = httprl_variable_get('proxy_user_agent', '');
    // The default value matches neither condition.
    if (is_null($proxy_user_agent)) {
      unset($options['headers']['User-Agent']);
    }
    elseif ($proxy_user_agent) {
      $options['headers']['User-Agent'] = $proxy_user_agent;
    }
  }
  return $proxy_server;
}

/**
 * Create the TCP/SSL socket connection string.
 *
 * @param $uri
 *   Array from parse_url().
 * @param &$options
 *   Array containing options.
 * @param $proxy_server
 *   String containing the proxy servers host name if one is to be used.
 * @param &$result
 *   Result object; used only for error handling in this function.
 *
 * @return $socket
 *   String containing the TCP/SSL socket connection URI.
 */
function httprl_set_socket($uri, &$options, $proxy_server, &$result) {
  $socket = '';
  switch ($uri['scheme']) {
    case 'proxy':
      // Make the socket connection to a proxy server.
      $socket = 'tcp://' . $proxy_server . ':' . httprl_variable_get('proxy_port', 8080);
      // The Host header still needs to match the real request.
      $options['headers']['Host'] = $uri['host'];
      $options['headers']['Host'] .= isset($uri['port']) && $uri['port'] != 80 ? ':' . $uri['port'] : '';
      break;

    case 'http':
    case 'feed':
      $port = isset($uri['port']) ? $uri['port'] : 80;
      $socket = 'tcp://' . $uri['host'] . ':' . $port;
      // RFC 2616: "non-standard ports MUST, default ports MAY be included".
      // We don't add the standard port to prevent from breaking rewrite rules
      // checking the host that do not take into account the port number.
      if (empty($options['headers']['Host'])) {
        $options['headers']['Host'] = $uri['host'];
      }
      if ($port != 80) {
        $options['headers']['Host'] .= ':' . $port;
      }
      break;

    case 'https':
      // Note: Only works when PHP is compiled with OpenSSL support.
      $port = isset($uri['port']) ? $uri['port'] : 443;
      $socket = 'ssl://' . $uri['host'] . ':' . $port;
      if (empty($options['headers']['Host'])) {
        $options['headers']['Host'] = $uri['host'];
      }
      if ($port != 443) {
        $options['headers']['Host'] .= ':' . $port;
      }
      break;

    default:
      // If the t function is not available use httprl_pr.
      if (function_exists('t')) {
        $t = 't';
      }
      else {
        $t = 'httprl_pr';
      }

      $result->error = $t('Invalid schema @scheme.', array('@scheme' => $uri['scheme']));
      $result->code = HTTPRL_URL_INVALID_SCHEMA;

  }

  return $socket;
}

/**
 * Select which connect flags to use in stream_socket_client().
 *
 * @param &$options
 *   Array containing options.
 * @param $uri
 *   Array from parse_url().
 *
 * @return $flags
 *   STREAM_CLIENT_CONNECT or STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT.
 */
function httprl_set_connection_flag(&$options, $uri) {
  // Set connection flag.
  if ($options['async_connect']) {
    // Workaround for PHP bug with STREAM_CLIENT_ASYNC_CONNECT and SSL
    // https://bugs.php.net/bug.php?id=48182 - Fixed in PHP 5.2.11 and 5.3.1
    if ($uri['scheme'] == 'https' && (version_compare(PHP_VERSION, '5.2.11', '<') || version_compare(PHP_VERSION, '5.3.0', '='))) {
      $flags = STREAM_CLIENT_CONNECT;
      $options['async_connect'] = FALSE;
    }
    else {
      $flags = STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT;
    }
  }
  else {
    $flags = STREAM_CLIENT_CONNECT;
  }
  return $flags;
}

/**
 * If data is being sent out in this request, handle it correctly.
 *
 * If $options['data'] is not a string, convert it to a string using
 * http_build_query(). Set the Content-Length header correctly. Set the
 * Content-Type to application/x-www-form-urlencoded if not already set and
 * using method is POST.
 *
 * @todo
 *   Proper mime support.
 *
 * @param &$options
 *   Array containing options.
 */
function httprl_handle_data(&$options) {
  // Encode data if not already done.
  if (!empty($options['data']) && !is_string($options['data'])) {
    // No files passed in, url-encode the data.
    if (empty($options['data']['files']) || !is_array($options['data']['files'])) {
      $options['data'] = http_build_query($options['data'], '', '&');

      // Set the Content-Type to application/x-www-form-urlencoded if the data
      // is not empty, the Content-Type is not set, and the method is POST or
      // PUT.
      if (!empty($options['data']) && !isset($options['headers']['Content-Type']) && ($options['method'] == 'POST' || $options['method'] == 'PUT')) {
        $options['headers']['Content-Type'] = 'application/x-www-form-urlencoded';
      }
    }
    else {
      $data_stream = '';
      // Add files to the request.
      foreach ($options['data']['files'] as $field_name => $info) {
        $multi_field = '[]';
        // Convert $info into an array if it's a string.
        // This makes for one code path (the foreach loop).
        if (is_string($info)) {
          $multi_field = '';
          $temp = $info;
          unset($info);
          $info[] = $temp;
        }
        foreach ($info as $fullpath) {
          // Strip '@' from the start of the path (cURL requirement).
          if (substr($fullpath, 0, 1) == "@") {
            $fullpath = substr($fullpath, 1);
          }
          $filename = basename($fullpath);
          // TODO: mime detection.
          $mimetype = 'application/octet-stream';

          // Build the datastream for this file.
          $data_stream .= '--' . HTTPRL_MULTIPART_BOUNDARY . "\r\n";
          $data_stream .= 'Content-Disposition: form-data; name="files[' . $field_name . ']' . $multi_field . '"; filename="' . $filename .  "\"\r\n";
          $data_stream .= 'Content-Transfer-Encoding: binary' . "\r\n";
          $data_stream .= 'Content-Type: ' . $mimetype . "\r\n\r\n";
          $data_stream .= file_get_contents($fullpath) . "\r\n";
        }
      }
      // Remove files from the data array as they have already been added.
      $data_array = $options['data'];
      unset($data_array['files']);
      // Add fields to the request too: $_POST['foo'] = 'bar'.
      httprl_multipart_encoder($data_stream, $data_array);

      // Signal end of request (note the trailing "--").
      $data_stream .= '--' . HTTPRL_MULTIPART_BOUNDARY . "--\r\n";
      $options['data'] = $data_stream;

      // Set the Content-Type to multipart/form-data if the data is not empty,
      // the Content-Type is not set, and the method is POST or PUT.
      if (!empty($options['data']) && !isset($options['headers']['Content-Type']) && ($options['method'] == 'POST' || $options['method'] == 'PUT')) {
        $options['headers']['Content-Type'] = 'multipart/form-data; boundary=' . HTTPRL_MULTIPART_BOUNDARY;
      }
    }
  }

  // Only add Content-Length if we actually have any content or if it is a POST
  // or PUT request. Some non-standard servers get confused by Content-Length in
  // at least HEAD/GET requests, and Squid always requires Content-Length in
  // POST/PUT requests.
  $content_length = httprl_strlen($options['data']);
  if ($content_length > 0 || $options['method'] == 'POST' || $options['method'] == 'PUT') {
    $options['headers']['Content-Length'] = $content_length;
  }
}

/**
 * Multipart encode a data array.
 *
 * PHP has http_build_query() which will url-encode data. There is no built in
 * function to multipart encode data thus we have this function below.
 *
 * @param $uri
 *   Array from parse_url().
 * @param &$options
 *   Array containing options.
 */
function httprl_multipart_encoder(&$data_stream, $data_array, $prepend = array()) {
  foreach ($data_array as $key => $value) {
    $key_array = $prepend;
    $key_array[] = $key;
    if (is_array($value)) {
      httprl_multipart_encoder($data_stream, $value, $key_array);
    }
    elseif (is_scalar($value)) {
      $key_string = array_shift($key_array);
      if (!empty($key_array)) {
        $key_string .= '[' . implode('][', $key_array) . ']';
      }
      $data_stream .= '--' . HTTPRL_MULTIPART_BOUNDARY . "\r\n";
      $data_stream .= 'Content-Disposition: form-data; name="' . $key_string . "\"\r\n\r\n";
      $data_stream .= $value . "\r\n";
    }
  }
}

/**
 * Set the Authorization header if a user is set in the URI.
 *
 * @param $uri
 *   Array from parse_url().
 * @param &$options
 *   Array containing options.
 */
function httprl_basic_auth($uri, &$options) {
  // If the server URL has a user then attempt to use basic authentication.
  if (isset($uri['user'])) {
    $options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (!empty($uri['pass']) ? ":" . $uri['pass'] : ''));
  }
}

/**
 * Build the request string.
 *
 * This string is what gets sent to the server once a connection has been made.
 *
 * @param $uri
 *   Array from parse_url().
 * @param $options
 *   Array containing options.
 *
 * @return $request
 *   String containing the data that will be written to the server.
 */
function httprl_build_request_string($uri, $options) {
  // Construct the path to act on.
  $path = isset($uri['path']) ? $uri['path'] : '/';
  if (isset($uri['query'])) {
    $path .= '?' . $uri['query'];
  }

  // Assemble the request together. HTTP version requires to be a float.
  $request = $options['method'] . ' ' . $path . ' HTTP/' . sprintf("%.1F", $options['version']) . "\r\n";
  foreach ($options['headers'] as $name => $value) {
    $request .= $name . ': ' . trim($value) . "\r\n";
  }
  $request .= "\r\n" . $options['data'];

  return $request;
}


/**
 * Read the error number & string and give a nice looking error in the output.
 *
 * This is a flexible and powerful HTTP client implementation. Correctly
 * handles GET, POST, PUT or any other HTTP requests.
 *
 * @param $errno
 *   Error number from stream_socket_client().
 * @param $errstr
 *   Error string from stream_socket_client().
 * @param $socket
 *   An integer holding the stream timeout value.
 * @param $result
 *   An object for httprl_send_request.
 * @return $result
 *   An object for httprl_send_request.
 */
function httprl_stream_connection_error_formatter($errno, $errstr, &$result) {
  // If the t function is not available use httprl_pr.
  if (function_exists('t')) {
    $t = 't';
    // Make sure drupal_convert_to_utf8() is available.
    if (defined('VERSION') && substr(VERSION, 0, 1) >= 7) {
      require_once DRUPAL_ROOT . '/includes/unicode.inc';
    }
    else {
      require_once './includes/unicode.inc';
    }

    // Convert error message to utf-8. Using ISO-8859-1 (Latin-1) as source
    // encoding could be wrong; it is a simple workaround :)
    $errstr = trim(drupal_convert_to_utf8($errstr, 'ISO-8859-1'));
  }
  else {
    $t = 'httprl_pr';
  }

  if (!$errno) {
    // If $errno is 0, it is an indication that the error occurred
    // before the connect() call.
    if (empty($errstr)) {
      // If the error string is empty as well, this is most likely due to a
      // problem initializing the stream.
      $result->code = HTTPRL_ERROR_INITIALIZING_STREAM;
      $result->error = $t('Error initializing socket @socket.', array('@socket' => $result->socket));
    }
    elseif (stripos($errstr, 'network_getaddresses: getaddrinfo failed:') !== FALSE) {
      // Host not found. No such host is known. The name is not an official host
      // name or alias.
      $result->code = HTTPRL_HOST_NOT_FOUND;
      $result->error = $errstr;
    }
  }
  else {
    // When a network error occurs, we use a negative number so it does not
    // clash with the HTTP status codes.
    $result->code = (int) -$errno;
    $result->error = !empty($errstr) ? $errstr : $t('Error opening socket @socket.', array('@socket' => $result->socket));
  }
}

/**
 * Use stream_socket_client() to create a connection to the server.
 *
 * @param $socket
 *   An integer holding the stream timeout value.
 * @param $flags
 *   STREAM_CLIENT_CONNECT or STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT.
 * @param $uri
 *   Array from parse_url().
 * @param $options
 *   Array containing options. Used for timeout and async_connect here.
 * @return array
 *   array($fp, $options, $errno, $errstr).
 */
function httprl_establish_stream_connection(&$result) {
  // Record start time.
  $start_time = microtime(TRUE);
  $result->fp = FALSE;

  // Try to make a connection, 3 max tries in loop.
  $count = 0;
  while (!$result->fp && $count < 3) {
    // Try the connection again not using async if in https mode.
    if ($count > 0) {
      if ($result->flags === STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT && $result->uri['scheme'] == 'https') {
        $result->flags = STREAM_CLIENT_CONNECT;
        $result->options['async_connect'] = FALSE;
      }
      else {
        // Break out of while loop if we can't connect.
        break;
      }
    }

    // Open the connection.
    if (empty($result->options['context'])) {
      $result->fp = @stream_socket_client($result->socket, $errno, $errstr, $result->options['timeout'], $result->flags);
    }
    else {
      // Create a stream with context. Context allows for the verification of
      // a SSL certificate.
      $result->fp = @stream_socket_client($result->socket, $errno, $errstr, $result->options['timeout'], $result->flags, $result->options['context']);
    }
    $count++;
  }

  // Make sure the stream opened properly. This check doesn't work if
  // async_connect is used, so only check it if async_connect is FALSE. Making
  // sure that stream_socket_get_name returns a "TRUE" value.
  if (   $result->fp
      && !$result->options['async_connect']
      && !stream_socket_get_name($result->fp, TRUE)
        ) {
    $errno = HTTPRL_CONNECTION_REFUSED;
    $errstr = 'Connection refused. No connection could be made because the target machine actively refused it.';
    $result->fp = FALSE;
  }

  // Report any errors or set the steram to non blocking mode.
  if (!$result->fp) {
    httprl_stream_connection_error_formatter($errno, $errstr, $result);
  }
  else {
    stream_set_blocking($result->fp, 0);
  }

  // Record end time.
  $end_time = microtime(TRUE);
  $extra = 0;
  if (isset($result->options['internal_states']['running_time'])) {
    $extra = $result->options['internal_states']['running_time'];
    unset($result->options['internal_states']['running_time']);
  }
  $result->running_time = $end_time - $start_time + $extra;
}

/**
 * Queue up a HTTP request in httprl_send_request.
 *
 * @see drupal_http_request()
 *
 * This is a flexible and powerful HTTP client implementation. Correctly
 * handles GET, POST, PUT or any other HTTP requests.
 *
 * @param $urls
 *   A string or an array containing a fully qualified URI(s).
 * @param array $options
 *   (optional) An array that can have one or more of the following elements:
 *   - headers: An array containing request headers to send as name/value pairs.
 *     Some of the more useful headers:
 *     - For POST: 'Content-Type' => 'application/x-www-form-urlencoded',
 *     - Limit number of bytes server sends back: 'Range' => 'bytes=0-1024',
 *     - Compression: 'Accept-Encoding' => 'gzip, deflate',
 *     - Let server know where request came from: 'Referer' => 'example.com',
 *     - Content-Types that are acceptable: 'Accept' => 'text/plain',
 *     - Send Cookies: 'Cookie' => 'key1=value1; key2=value2;',
 *     - Skip the cache: 'Cache-Control' => 'no-cache',
 *     - Skip the cache: 'Pragma' => 'no-cache',
 *     List of headers: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
 *   - method: A string containing the request method. Defaults to 'GET'.
 *   - data: A string containing the request body, formatted as
 *     'param=value&param=value&...'. Defaults to NULL.
 *   - max_redirects: An integer representing how many times a redirect
 *     may be followed. Defaults to 3.
 *   - timeout: A float representing the maximum number of seconds a connection
 *     may take. The default is 30 seconds. If a timeout occurs, the error code
 *     is set to the HTTPRL_REQUEST_TIMEOUT constant.
 *   - context: A context resource created with stream_context_create().
 *   - blocking: set to FALSE to make this not care about the returned data.
 *   - version: HTTP Version 1.0 or 1.1. Default is 1.0 for a good reason.
 *   - referrer: TRUE - send current page; FALSE - do not send current
 *     page. Default is FALSE.
 *   - domain_connections: Maximum number of simultaneous connections to a given
 *     domain name. Default is 8.
 *   - global_connections: Maximum number of simultaneous connections that can
 *     be open on the server. Default is 128.
 *   - global_timeout: A float representing the maximum number of seconds the
 *     function call may take. If a timeout occurs,the error code is set to the
 *     HTTPRL_FUNCTION_TIMEOUT constant. Default is 120 seconds.
 *   - chunk_size_write: max size of what will be written in fwrite().
 *   - chunk_size_read: max size of what will be read from fread().
 *   - async_connect: default is TRUE. FALSE may give more info on errors but is
 *     generally slower.
 *   - callback: Array where the first value is an array of options; the result
 *     is passed to the callback function as the first argument, the other
 *     options passed in this array are passed in after the result. The options
 *     array needs to contain the function name and the target variable for the
 *     result of the function.
 *   - background_callback: Array where the first value is an array of options;
 *     the result is passed to the callback function as the first argument, the
 *     other options passed in this array are passed in after the result. The
 *     options array needs to contain the function name. If the return or
 *     printed keys are not defined this function will run in non blocking mode
 *     and the parent will not be able to get the result; if the return or
 *     printed keys defined then this function will run in blocking mode and the
 *     returned and printed data as well as any variables passed by reference
 *     will be available to the parent.
 *   - alter_all_streams_function: Function name. This function runs at the end
 *     of httprl_post_processing() so that one can alter the $responses and
 *     $output variables inside of httprl_send_request. Defined function
 *     should have the following parameters:
 *       ($id, &$responses).
 *
 * @return array
 *   Array where key is the URL and the value is the return value from
 *   httprl_send_request.
 */
function httprl_request($urls, $options = array()) {
  // See if a full bootstrap has been done.
  $full_bootstrap = httprl_drupal_full_bootstrap();

  // Transform string to an array.
  if (!is_array($urls)) {
    $temp = $urls;
    unset($urls);
    $urls = array($temp);
    unset($temp);
  }

  if ($full_bootstrap) {
    // Allow other modules to alter things before we get started.
    // Run hook_pre_httprl_request_alter().
    $data = array($urls, $options);
    drupal_alter('pre_httprl_request', $data);
    list($urls, $options) = $data;
  }

  $connections = array();
  $return = array();
  // Set things up; but do not perform any IO.
  foreach ($urls as $url) {
    $result = new stdClass();
    $result->url = $url;
    $result->status = 'in progress';
    $result->code = 0;
    $result->chunk_size = 1024;
    $result->data = '';

    // Copy Options.
    $these_options = $options;

    // Setup the default options.
    httprl_set_default_options($these_options);

    // Parse the given URL and skip if an error occurred.
    $uri = httprl_parse_url($url, $result);
    if (isset($result->error)) {
      // Put all variables into an array for easy alterations.
      $connections[] = array(NULL, NULL, $uri, $url, $these_options, $result, NULL);
      $return[$url] = FALSE;
      // Stop processing this request as we have encountered an error.
      continue;
    }

    // Set the proxy server if one is required.
    $proxy_server = httprl_setup_proxy($uri, $these_options, $url);
    // Create the socket string and skip if an error occurred.
    $socket = httprl_set_socket($uri, $these_options, $proxy_server, $result, $return, $url);
    if (isset($result->error)) {
      // Put all variables into an array for easy alterations.
      $connections[] = array($socket, NULL, $uri, $url, $these_options, $result, NULL);
      $return[$url] = FALSE;
      // Stop processing this request as we have encountered an error.
      continue;
    }

    // Use a sync of async connection.
    $flags = httprl_set_connection_flag($these_options, $uri);
    // If any data is given, do the right things to this request so it works.
    httprl_handle_data($these_options);
    // Build the request string.
    $request = httprl_build_request_string($uri, $these_options);

    // Put all variables into an array for easy alterations.
    $connections[] = array($socket, $flags, $uri, $url, $these_options, $result, $request);
    $return[$url] = TRUE;
  }

  if ($full_bootstrap) {
    // Allow other programs to alter the connections before they are made.
    // run hook_httprl_request_alter().
    drupal_alter('httprl_request', $connections);
  }

  $results = array();
  foreach ($connections as $connection) {
    list($socket, $flags, $uri, $url, $options, $result, $request) = $connection;
    $result->request = $request;
    $result->options = $options;
    $result->socket = $socket;
    $result->flags = $flags;
    $result->uri = $uri;
    $result->running_time = 0;
    $results[] = $result;
  }

  httprl_send_request($results);
  return $return;
}

/**
 * Perform many HTTP requests.
 *
 * @see drupal_http_request()
 *
 * This is a flexible and powerful HTTP client implementation. Correctly
 * handles GET, POST, PUT or any other HTTP requests.
 *
 * @param $connections
 *   (optional) A file pointer.
 * @return bool
 *   TRUE if function worked as planed.
 */
function httprl_send_request($results = NULL) {
  static $responses = array();
  static $counter = 0;

  if (!is_null($results)) {
    // Put the connection information into the responses array.
    foreach ($results as $result) {
      $responses[$counter] = $result;
      $counter++;
    }
    return TRUE;
  }

  // Exit if there is nothing to do.
  if (empty($responses)) {
    return FALSE;
  }

  // If the t function is not available use httprl_pr.
  if (function_exists('t')) {
    $t = 't';
  }
  else {
    $t = 'httprl_pr';
  }

  // Create output array.
  $output = array();
  // Remove errors from responses array and set the global timeout.
  $global_timeout = 1;
  $global_connection_limit = 1;
  foreach ($responses as $id => &$result) {
    if (!empty($result->error)) {
      $result->status = 'Connection not made.';
      // Do post processing on the stream.
      httprl_post_processing($id, $responses, $output);
      continue;
    }

    // Get connection limits.
    $global_connection_limit = max($global_connection_limit, $result->options['global_connections']);
    if (!isset($domain_connection_limit[$result->options['headers']['Host']])) {
      $domain_connection_limit[$result->options['headers']['Host']] = max(1, $result->options['domain_connections']);
    }
    else {
      $domain_connection_limit[$result->options['headers']['Host']] = max($domain_connection_limit[$result->options['headers']['Host']], $result->options['domain_connections']);
    }

    $global_timeout = max($global_timeout, $result->options['global_timeout']);
  }

  // Record start time.
  $start_time_this_run = $start_time_global = microtime(TRUE);

  // Run the loop as long as we have a stream to read/write to.
  $empty_runs = 0;
  $stream_select_timeout = 1;
  $stream_write_count = 0;

  while (!empty($responses)) {

    // Initialize connection limits.
    $this_run = array();
    $global_connection_count = 0;
    $domain_connection_count = array();
    $restart_timers = FALSE;

    // Get time.
    $now = microtime(TRUE);

    // Calculate times.
    $elapsed_time = $now - $start_time_this_run;
    $start_time_this_run = $now;
    $global_time = $global_timeout - ($start_time_this_run - $start_time_global);

    $reset_empty_runs = FALSE;
    // Inspect each stream, checking for timeouts and connection limits.
    foreach ($responses as $id => &$result) {
      // See if function timed out.
      if ($global_time <= 0) {
        // Function timed out & the request is not done.
        if ($result->status == 'in progress') {
          $result->error = $t('Function timed out. Write.');
          // If stream is not done writing, then remove one from the write count.
          if (isset($result->fp)) {
            $stream_write_count--;
          }
        }
        else {
          $result->error = $t('Function timed out.');
        }
        $result->code = HTTPRL_FUNCTION_TIMEOUT;
        $result->status = 'Done.';

        // Do post processing on the stream and close it.
        httprl_post_processing($id, $responses, $output, $global_time);
        continue;
      }
      // Do not calculate local timeout if a file pointer doesn't exist.
      if (isset($result->fp)) {
        // Add the elapsed time to this stream.
        $result->running_time += $elapsed_time;
        // Calculate how much time is left of the original timeout value.
        $timeout = $result->options['timeout'] - $result->running_time;
        // No streams are ready from stream_select, See if end server has
        // dropped the connection, or has failed to make the connection.
        $socket_name = 'Not empty.';
        if ($empty_runs > 32) {
          // If nothing has happened after 32 runs, see if the connection has
          // been made.
          $socket_name = stream_socket_get_name($result->fp, TRUE);
        }

        // Connection was dropped or connection timed out.
        if ($timeout <= 0 || empty($socket_name)) {
          $result->error = $t('Connection timed out. If you believe this is a false error, turn off async_connect in the httprl options array and try again.');
          // Stream timed out & the request is not done.
          if ($result->status == 'in progress') {
            $result->error .= $t(' Write.');
            // If stream is not done writing, then remove one from the write count.
            $stream_write_count--;
          }
          else {
            $result->error .= $t(' Read.');
          }
          $result->code = HTTPRL_REQUEST_TIMEOUT;
          $result->status = 'Done.';

          // Do post processing on the stream.
          httprl_post_processing($id, $responses, $output, $timeout);
          $reset_empty_runs = TRUE;
          continue;
        }
      }

      // Connection was handled elsewhere.
      if (!isset($result->fp) && $result->status != 'in progress') {
        // Do post processing on the stream.
        httprl_post_processing($id, $responses, $output);
        $reset_empty_runs = TRUE;
        continue;
      }

      // Set the connection limits for this run.
      // Get the host name.
      $host = $result->options['headers']['Host'];
      // Set the domain connection limit if none has been defined yet.
      if (!isset($domain_connection_limit[$host])) {
        $domain_connection_limit[$host] = max(1, $result->options['domain_connections']);
      }
      // Count up the number of connections.
      $global_connection_count++;
      if (empty($domain_connection_count[$host])) {
        $domain_connection_count[$host] = 1;
      }
      else {
        $domain_connection_count[$host]++;
      }
      // If the conditions are correct, let the stream be ran in this loop.
      if ($global_connection_limit >= $global_connection_count && $domain_connection_limit[$host] >= $domain_connection_count[$host]) {
        // Establish a new connection.
        if (!isset($result->fp) && $result->status == 'in progress') {
          // Establish a connection to the server.
          httprl_establish_stream_connection($result);

          // Reset timer.
          $restart_timers = TRUE;

          // If connection can not be established bail out here.
          if (!$result->fp) {
            // Do post processing on the stream.
            httprl_post_processing($id, $responses, $output);
            $domain_connection_count[$host]--;
            $global_connection_count--;
            continue;
          }
          $stream_write_count++;

        }
        if (!empty($result->fp)) {
          $this_run[$id] = $result->fp;
        }
      }
    }

    // All streams removed; exit loop.
    if (empty($responses)) {
      break;
    }
    // Restart timers.
    if ($restart_timers) {
      $start_time_this_run = microtime(TRUE);
    }
    // No streams selected; restart loop from the top.
    if (empty($this_run)) {
      continue;
    }
    if ($reset_empty_runs) {
      $empty_runs = 0;
      $reset_empty_runs = FALSE;
    }



    // Set the read and write vars to the streams var.
    $read = $write = $this_run;
    $except = array();
    // Do some voodoo and open all streams at once. Wait 25ms for streams to
    // respond.
    $n = stream_select($read, $write, $except, $stream_select_timeout, 25000);
    $stream_select_timeout = 0;

    // We have some streams to read/write to.
    $rw_done = FALSE;
    if (!empty($n)) {
      $empty_runs = 0;

      // Readable sockets either have data for us, or are failed connection
      // attempts.
      foreach ($read as $r) {
        $id = array_search($r, $this_run);
        // Make sure ID is in the streams.
        if ($id === FALSE) {
          @fclose($r);
          continue;
        }
        // Do not read from the non blocking sockets.
        if (empty($responses[$id]->options['blocking'])) {
          // Do post processing on the stream and close it.
          httprl_post_processing($id, $responses, $output);
          continue;
        }

        // Read socket.
        $chunk = fread($r, $responses[$id]->chunk_size);
        if (httprl_strlen($chunk) > 0) {
          $rw_done = TRUE;
        }
        $responses[$id]->data .= $chunk;

        // Process the headers if we have some data.
        if (!empty($responses[$id]->data) && empty($responses[$id]->headers) &&
            (    strpos($responses[$id]->data, "\r\n\r\n")
              || strpos($responses[$id]->data, "\n\n")
              || strpos($responses[$id]->data, "\r\r")
                )
                  ) {
          // See if the headers are in the data stream.
          httprl_parse_data($responses[$id]);
          if (!empty($responses[$id]->headers)) {
            // Stream was a redirect, kill & close this connection; redirect is
            // being followed now.
            if (!empty($responses[$id]->options['internal_states']['kill'])) {
              fclose($r);
              unset($responses[$id]);
              continue;
            }

            // Now that we have the headers, increase the chunk size.
            $responses[$id]->chunk_size = $responses[$id]->options['chunk_size_read'];

            // If a range header is set, 200 was returned, and method is GET
            // calculate how many bytes need to be downloaded.
            if (!empty($responses[$id]->options['headers']['Range']) && $responses[$id]->code == 200 && $responses[$id]->method == 'GET') {
              $responses[$id]->ranges = httprl_get_ranges($responses[$id]->options['headers']['Range']);
              $responses[$id]->options['max_data_size'] = httprl_get_last_byte_from_range($responses[$id]->ranges);
            }
          }
        }

        // Close the connection if a Range request was made and the currently
        // downloaded data size is larger than the Range request.
        if (   !empty($responses[$id]->options['max_data_size'])
            && !is_null($responses[$id]->options['max_data_size'])
            && $responses[$id]->options['max_data_size'] < httprl_strlen($responses[$id]->data)
              ) {
          $responses[$id]->status = 'Done.';
          $responses[$id]->code = 206;

          // Make the data conform to the range request.
          $new_data = array();
          foreach ($responses[$id]->ranges as $range) {
            $new_data[] = substr($responses[$id]->data, $range['start'], ($range['end']+1) - $range['start']);
          }
          $responses[$id]->data = implode('', $new_data);

          // Do post processing on the stream.
          httprl_post_processing($id, $responses, $output);
          continue;
        }

        // Get stream data.
        $info = stream_get_meta_data($r);
        $alive = !$info['eof'] && !feof($r) && !$info['timed_out'] && httprl_strlen($chunk);
        if (!$alive) {
          if ($responses[$id]->status == 'in progress') {
            $responses[$id]->error = $t('Connection refused by destination. Write.');
            $responses[$id]->code = HTTPRL_CONNECTION_REFUSED;
          }
          $responses[$id]->status = 'Done.';

          // Do post processing on the stream.
          httprl_post_processing($id, $responses, $output);
          continue;
        }
        else {
          $responses[$id]->status = 'Reading data';
        }
      }

      // Write to each stream if it is available.
      if ($stream_write_count > 0) {
        foreach ($write as $w) {
          $id = array_search($w, $this_run);
          // Make sure ID is in the streams & status is for writing.
          if ($id === FALSE || empty($responses[$id]->status) || $responses[$id]->status != 'in progress') {
            continue;
          }

          // Calculate the number of bytes we need to write to the stream.
          if (!empty($responses[$id]->request_left)) {
            $data_to_send = $responses[$id]->request_left;
          }
          else {
            $data_to_send = $responses[$id]->request;
          }
          $len = httprl_strlen($data_to_send);
          if ($len > 0) {
            // Write to the stream.
            $bytes = fwrite($w, $data_to_send, min($responses[$id]->options['chunk_size_write'], $len));
          }
          else {
            // Nothing to write.
            $bytes = $len;
          }

          // See if we are done with writing.
          if ($bytes === FALSE) {
            // fwrite failed.
            $responses[$id]->error = $t('fwrite() failed.');
            $responses[$id]->code = HTTPRL_REQUEST_FWRITE_FAIL;
            $responses[$id]->status = 'Done.';
            $stream_write_count--;

            // Do post processing on the stream.
            httprl_post_processing($id, $responses, $output);
            continue;
          }
          elseif ($bytes >= $len) {
            $stream_write_count--;

            // Clear out the request_left variable.
            if (isset($responses[$id]->request_left)) {
              unset($responses[$id]->request_left);
            }

            // If this is a non blocking request then close the connection and destroy the stream.
            if (empty($responses[$id]->options['blocking'])) {
              $responses[$id]->status = 'Non-Blocking request sent out. Not waiting for the response.';
              // Do post processing on the stream.
              httprl_post_processing($id, $responses, $output);
              continue;
            }
            else {
              // All data has been written to the socket. We are read only from here on out.
              $responses[$id]->status = "Request sent, waiting for response.";
            }
            $rw_done = TRUE;
          }
          else {
            // There is more data to write to this socket. Cut what was sent
            // across the stream and resend whats left next time in the loop.
            $responses[$id]->request_left = substr($data_to_send, $bytes);
            $rw_done = TRUE;
          }
        }
      }
    }
    else {
      $empty_runs++;
    }
    if ($empty_runs > 400) {
      // If stream_select hasn't returned a valid read or write stream after
      // 10+ seconds, error out.
      foreach ($this_run as $id => $fp) {
        // stream_select timed out & the request is not done.
        $responses[$id]->error = $t('stream_select() timed out.');
        $responses[$id]->code = HTTPRL_STREAM_SELECT_TIMEOUT;
        $responses[$id]->status = 'Done.';

        // Do post processing on the stream.
        httprl_post_processing($id, $responses, $output);
        continue;
      }
    }
    if (!$rw_done) {
      // Wait 5ms for data buffers.
      usleep(5000);
    }
  }

  // Free memory/reset static variables.
  $responses = array();
  $counter = 0;

  return $output;
}

/**
 * Extract the header and meta data from the http data stream.
 *
 * @see drupal_http_request()
 *
 * @param $result
 *   An object from httprl_send_request.
 */
function httprl_parse_data(&$result) {
  // If in non blocking mode, skip.
  if (empty($result->options['blocking'])) {
    continue;
  }

  // If the headers are already parsed, skip.
  if (!empty($result->headers)) {
    continue;
  }

  // If the t function is not available use httprl_pr.
  if (function_exists('t')) {
    $t = 't';
  }
  else {
    $t = 'httprl_pr';
  }

  // Parse response headers from the response body.
  // Be tolerant of malformed HTTP responses that separate header and body with
  // \n\n or \r\r instead of \r\n\r\n.
  $response = $result->data;
  list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
  $response = preg_split("/\r\n|\n|\r/", $response);

  // Parse the response status line.
  $protocol_code_array = explode(' ', trim(array_shift($response)), 3);
  $result->protocol = $protocol_code_array[0];
  $code = (int) $protocol_code_array[1];
  // If the response does not include a description, don't try to process it.
  $result->status_message = isset($protocol_code_array[2]) ? $protocol_code_array[2] : '';
  unset($protocol_code_array);

  $result->headers = array();

  // Parse the response headers.
  $cookie_primary_counter = 0;
  while ($line = trim(array_shift($response))) {
    list($name, $value) = explode(':', $line, 2);
    $name = strtolower($name);

    // Parse cookies before they get added to the header.
    if ($name == 'set-cookie') {
      // Extract the key value pairs for this cookie.
      foreach (explode(';', $value) as $cookie_name_value) {
        $temp = explode('=', trim($cookie_name_value));
        $cookie_key = trim($temp[0]);
        $cookie_value = isset($temp[1]) ? trim($temp[1]) : '';
        unset($temp);
        // The cookie name-value pair always comes first (RFC 2109 4.2.2).
        if (!isset($result->cookies[$cookie_primary_counter])) {
          $result->cookies[$cookie_primary_counter] = array(
            'name' => $cookie_key,
            'value' => $cookie_value,
          );
        }
        // Extract the rest of the attribute-value pairs.
        else {
          $result->cookies[$cookie_primary_counter] += array(
            $cookie_key => $cookie_value,
          );
        }
      }
      $cookie_primary_counter++;
    }

    // Add key value pairs to the header; including cookies.
    if (isset($result->headers[$name]) && $name == 'set-cookie') {
      // RFC 2109: the Set-Cookie response header comprises the token Set-
      // Cookie:, followed by a comma-separated list of one or more cookies.
      $result->headers[$name] .= ',' . trim($value);
    }
    else {
      $result->headers[$name] = trim($value);
    }
  }

  $responses = array(
    100 => 'Continue',
    101 => 'Switching Protocols',
    200 => 'OK',
    201 => 'Created',
    202 => 'Accepted',
    203 => 'Non-Authoritative Information',
    204 => 'No Content',
    205 => 'Reset Content',
    206 => 'Partial Content',
    300 => 'Multiple Choices',
    301 => 'Moved Permanently',
    302 => 'Found',
    303 => 'See Other',
    304 => 'Not Modified',
    305 => 'Use Proxy',
    307 => 'Temporary Redirect',
    400 => 'Bad Request',
    401 => 'Unauthorized',
    402 => 'Payment Required',
    403 => 'Forbidden',
    404 => 'Not Found',
    405 => 'Method Not Allowed',
    406 => 'Not Acceptable',
    407 => 'Proxy Authentication Required',
    408 => 'Request Time-out',
    409 => 'Conflict',
    410 => 'Gone',
    411 => 'Length Required',
    412 => 'Precondition Failed',
    413 => 'Request Entity Too Large',
    414 => 'Request-URI Too Large',
    415 => 'Unsupported Media Type',
    416 => 'Requested range not satisfiable',
    417 => 'Expectation Failed',
    500 => 'Internal Server Error',
    501 => 'Not Implemented',
    502 => 'Bad Gateway',
    503 => 'Service Unavailable',
    504 => 'Gateway Time-out',
    505 => 'HTTP Version not supported',
  );
  // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  // base code in their class.
  if (!isset($responses[$code])) {
    $code = floor($code / 100) * 100;
  }
  $result->code = $code;

  switch ($code) {
    case 200: // OK
    case 206: // Partial Content
    case 304: // Not modified
      break;

    case 301: // Moved permanently
    case 302: // Moved temporarily
    case 307: // Moved temporarily
      $location = @parse_url($result->headers['location']);

      // If location isn't fully qualified URL (as per W3 RFC2616), build one.
      if (empty($location['scheme']) || empty($location['host'])) {
        // Get the important parts from the original request.
        $original_location = @parse_url($result->url);
        // Assume request is to self if none of this was setup correctly.
        $location['scheme'] = !empty($location['scheme']) ? $location['scheme'] : $original_location['scheme'];
        $location['host'] = !empty($location['host']) ? $location['host'] : !empty($original_location['host']) ? $original_location['host'] : $_SERVER['HTTP_HOST'];
        $location['port'] = !empty($location['port']) ? $location['port'] : !empty($original_location['port']) ? $original_location['port'] : '';
        $location = httprl_glue_url($location);
      }
      else {
        $location = $result->headers['location'];
      }

      // Set internal redirect states.
      $result->options['internal_states']['redirect_code_array'][] = $code;
      $result->options['internal_states']['redirect_url_array'][] = $location;
      if (!isset($result->options['internal_states']['original_url'])) {
        $result->options['internal_states']['original_url'] = $result->url;
      }

      // Error out if we hit the max redirect.
      if ($result->options['max_redirects'] <= 0) {
        $result->code = HTTPRL_REQUEST_ALLOWED_REDIRECTS_EXHAUSTED;
        $result->error = $t('Maximum allowed redirects exhausted.');
      }
      else {
        // Redirect to the new location.
        // TODO: Send cookies in the redirect request if domain/path match.
        $result->options['max_redirects']--;
        if (isset($result->options['headers']['Referer'])) {
          $result->options['headers']['Referer'] = $result->url;
        }
        // Remove the host from the header.
        unset($result->options['headers']['Host']);

        // Pass along running time.
        $result->options['internal_states']['running_time'] = $result->running_time;

        // Send new request.
        httprl_request($location, $result->options);
        // Kill this request.
        $result->options['internal_states']['kill'] = TRUE;
      }

      break;

    default:
      $result->error = $result->status_message;
  }
}

/**
 * Parse a range header into start and end byte ranges.
 *
 * @param $input
 *   String in the form of bytes=0-1024 or bytes=0-1024,2048-4096
 * @return array
 *   Keyed arrays containing start and end values for the byte ranges.
 *   Empty array if the string can not be parsed.
 */
function httprl_get_ranges($input) {
  $ranges = array();
  // Make sure the input string matches the correct format.
  $string = preg_match('/^bytes=((\d*-\d*,? ?)+)$/', $input, $matches) ? $matches[1] : FALSE;
  if (!empty($string)) {
    // Handle mutiple ranges
    foreach (explode(',', $string) as $range) {
      // Get the start and end byte values for this range.
      $values = explode('-', $range);
      if (count($values) != 2) {
        return FALSE;
      }
      $ranges[] = array('start' => $values[0], 'end' => $values[1]);
    }
  }
  return $ranges;
}

/**
 * Given an array of ranges, get the last byte we need to download.
 *
 * @param $ranges
 *   Multi dimentional array
 * @return int or NULL
 *   NULL: Get all values; int: last byte to download.
 */
function httprl_get_last_byte_from_range($ranges) {
  $max = 0;
  if (empty($ranges)) {
    return NULL;
  }
  foreach ($ranges as $range) {
    if (!is_numeric($range['start']) || !is_numeric($range['end'])) {
      return NULL;
    }
    $max = max($range['end']+1, $max);
  }
  return $max;
}

/**
 * Run post processing on the request if we are done reading.
 *
 * Decode transfer-encoding and content-encoding.
 * Reconstruct the internal redirect arrays.
 *
 * @param $result
 *   An object from httprl_send_request.
 */
function httprl_post_processing($id, &$responses, &$output, $time_left = NULL) {
  // Create the result reference.
  $result = &$responses[$id];

  // Close file.
  if (isset($result->fp)) {
    @fclose($result->fp);
  }

  // Set timeout.
  if (is_null($time_left)) {
    $time_left = $result->options['timeout'] - $result->running_time;
  }
  $result->options['timeout'] = $time_left;

  // Assemble redirects.
  httprl_reconstruct_redirects($result);

  // Decode chunked transfer-encoding and gzip/deflate content-encoding if we
  // have a successful read; code is greater than 0.
  if ($result->code > 0) {
    httprl_decode_data($result);
  }

  // If this is a background callback request, extract the data and return.
  if (isset($result->options['internal_states']['background_function_return']) && isset($result->headers['content-type']) && $result->headers['content-type'] == 'application/x-www-form-urlencoded') {
    httprl_extract_background_callback_data($result);
    unset($responses[$id]);
    return;
  }

  // See if a full bootstrap has been done.
  $full_bootstrap = httprl_drupal_full_bootstrap();

  // Allow other modules to alter the result.
  if ($full_bootstrap) {
    // Call hook_httprl_post_processing_alter().
    drupal_alter('httprl_post_processing', $result);
  }

  // Run callback so other modules can do stuff in the event loop.
  if (   $full_bootstrap
      && !empty($result->options['callback'])
      && is_array($result->options['callback'])
        ) {
    httprl_run_callback($result);
  }

  // Run background_callback.
  if (   !empty($result->options['background_callback'])
      && is_array($result->options['background_callback'])
        ) {
    httprl_queue_background_callback($result->options['background_callback'], $result);
  }

  // Allow a user defined function to alter all $responses.
  if ($full_bootstrap && !empty($result->options['alter_all_streams_function']) && function_exists($result->options['alter_all_streams_function'])) {
    $result->options['alter_all_streams_function']($id, $responses);
  }

  // Copy the result to the output array.
  if (isset($result->url)) {
    $output[$result->url] = $result;
  }
  unset($responses[$id]);
}

/**
 * Set the return and printed values & any pass by reference values from a
 * background callback operation.
 *
 * @param $result
 *   An object from httprl_send_request.
 */
function httprl_extract_background_callback_data(&$result) {
  // Extract data from string.
  $data = array();
  parse_str($result->data, $data);
  $data = unserialize(current($data));

  // Set return and printed values.
  if (isset($data['return'])) {
    $result->options['internal_states']['background_function_return'] = $data['return'];
  }
  if (isset($data['printed'])) {
    $result->options['internal_states']['background_function_printed'] = $data['printed'];
  }

  // Set any pass by reference values.
  httprl_recursive_array_reference_extract($result->options['internal_states']['background_function_args'], $data['args']);
}

/**
 * Replace data in place so pass by reference sill works.
 *
 * @param $array
 *   An array containing the references if any.
 * @param $data
 *   An array that has the new values to copy into $array.
 * @param $depth
 *   Only go 10 levels deep. Prevent infinite loops.
 */
function httprl_recursive_array_reference_extract(&$array, $data, $depth = 0) {
  $depth++;
  foreach ($array as $key => &$value) {
    if (isset($data[$key])) {
      if (is_array($data[$key]) && is_array($value) && $depth < 10) {
        $value = httprl_recursive_array_reference_extract($value, $data[$key], $depth);
      }
      else {
        $value = $data[$key];
      }
    }
    else {
      $value = NULL;
    }
  }
  // Copy new keys into the data structure.
  foreach ($data as $key => $value) {
    if (isset($array[$key])) {
      continue;
    }
    $array[$key] = $value;
  }
}

/**
 * Will run the given callback returning values and what might have been
 * printed by that function, as well as respecting any pass by reference values.
 *
 * @param $result
 *   An object from httprl_send_request.
 */
function httprl_run_callback(&$result) {
  // Get options.
  $callback_options = $result->options['callback'][0];
  // Merge in values by reference.
  $result->options['callback'][0] = &$result;

  // Capture anything printed out.
  if (array_key_exists('printed', $callback_options)) {
    ob_start();
  }
  // Call function.
  $callback_options['return'] = call_user_func_array($callback_options['function'], $result->options['callback']);
  if (array_key_exists('printed', $callback_options)) {
    $callback_options['printed'] = ob_get_contents();
    ob_end_clean();
  }

  // Add options back into the callback array.
  if (isset($result->options['callback'])) {
    array_unshift($result->options['callback'], $callback_options);
  }
}

/**
 * Will run the given callback returning values and what might have been
 * printed by that function, as well as respecting any pass by reference values.
 *
 * @param $args
 *   An array of arguments, first key value pair is used to control the
 *   callback function. The rest of the key value pairs will be arguments for
 *   the callback function.
 * @param $result
 *   (optional) An object from httprl_send_request. If this is set, this will
 *   be the first argument of the function.
 */
function httprl_queue_background_callback(&$args, &$result = NULL) {
  // Use a counter to prevent key collisions in httprl_send_request.
  static $counter;
  if (!isset($counter)) {
    $counter = 0;
  }
  $counter++;

  // Get options.
  $callback_options = $args[0];

  if (is_null($result)) {
    array_shift($args);
  }
  else {
    // Merge in this request by reference.
    $args[0] = &$result;
  }

  // Set blocking mode.
  if (isset($callback_options['return']) || isset($callback_options['printed'])) {
    $mode = TRUE;
  }
  else {
    $mode = FALSE;
  }
  // Make sure some array keys exist.
  if (!isset($callback_options['return'])) {
    $callback_options['return'] = '';
  }
  if (!isset($callback_options['function'])) {
    $callback_options['function'] = '';
  }

  // Get the maximum amount of time this could take.
  $times = array(HTTPRL_TIMEOUT, HTTPRL_GLOBAL_TIMEOUT);
  if (isset($callback_options['options']['timeout'])) {
    $times[] = $callback_options['options']['timeout'];
  }
  if (isset($callback_options['options']['global_timeout'])) {
    $times[] = $callback_options['options']['global_timeout'];
  }

  // Acquire lock for this run.
  $locked = FALSE;
  $lock_counter = 0;
  while (!$locked && $lock_counter < 20) {
    $id = 'httprl_' . hash('sha512', mt_rand() . time());
    // Set lock to maximum amount of time.
    $locked = lock_acquire($id, max($times));
    $lock_counter++;
  }

  // Make sure lock exists after this process is dead.
  if (empty($mode)) {
    // Remove from the global locks variable.
    global $locks;
    unset($locks[$id]);

    // Remove the lock_id reference in the database.
    if (httprl_variable_get('lock_inc', './includes/lock.inc') === './includes/lock.inc') {
      if (defined('VERSION') && substr(VERSION, 0, 1) >= 7) {
        db_update('semaphore')
          ->fields(array('value' => 'httprl'))
          ->condition('name', $id)
          ->condition('value', _lock_id())
          ->execute();
      }
      else {
        db_query("UPDATE {semaphore} SET value = '%s' WHERE name = '%s' AND value = '%s'", 'httprl', $id, _lock_id());
      }
    }
  }

  // Get URL to call function in background.
  if (empty($callback_options['url'])) {
    $url = httprl_build_url_self('httprl_async_function_callback?count=' . $counter);
  }
  else {
    $url = $callback_options['url'];
  }
  // Create data array and options for request.
  $options = array(
    'data' => array(
      'master_key' => hash('sha512', httprl_drupal_get_private_key()),
      'temp_key' => $id,
      'mode' => $mode,
      'function' => $callback_options['function'],
      'args' => serialize($args),
    ),
    'internal_states' => array(
      'background_function_return' => &$callback_options['return'],
      'background_function_args' => &$args,
    ),
    'blocking' => $mode,
    'method' => 'POST',
  );
  if (isset($callback_options['printed'])) {
    $options['internal_states']['background_function_printed'] = &$callback_options['printed'];
  }
  if (isset($callback_options['options']) && is_array($callback_options['options'])) {
    $options += $callback_options['options'];
  }
  // Send Request.
  return httprl_request($url, $options);
}

/**
 * Will decode chunked transfer-encoding and gzip/deflate content-encoding.
 *
 * @param $result
 *   An object from httprl_send_request.
 */
function httprl_decode_data(&$result) {
  if (isset($result->headers['transfer-encoding']) && $result->headers['transfer-encoding'] == 'chunked') {
    $stream_position = 0;
    $output = '';
    $data = $result->data;
    while ($stream_position < httprl_strlen($data)) {
      // Get the number of bytes to read for this chunk.
      $rawnum = substr($data, $stream_position, strpos(substr($data, $stream_position), "\r\n") + 2);
      $num = hexdec(trim($rawnum));
      // Get the position to read from.
      $stream_position += httprl_strlen($rawnum);
      // Extract the chunk.
      $chunk = substr($data, $stream_position, $num);
      // Decompress if compressed.
      if (isset($result->headers['content-encoding'])) {
        if ($result->headers['content-encoding'] == 'gzip') {
          $chunk = gzinflate(substr($chunk, 10));
        }
        elseif ($result->headers['content-encoding'] == 'deflate') {
          $chunk = gzinflate($chunk);
        }
      }
      // Glue the chunks together.
      $output .= $chunk;
      $stream_position += httprl_strlen($chunk);
    }
    $result->data = $output;
  }
  // Decompress if compressed.
  elseif (isset($result->headers['content-encoding'])) {
    if ($result->headers['content-encoding'] == 'gzip') {
      $result->data = gzinflate(substr($result->data, 10));
    }
    elseif ($result->headers['content-encoding'] == 'deflate') {
      $result->data = gzinflate($result->data);
    }
  }
}

/**
 * Reconstruct the internal redirect arrays.
 *
 * @param $result
 *   An object from httprl_send_request.
 */
function httprl_reconstruct_redirects(&$result) {
  // Return if original_url is not set.
  if (empty($result->options['internal_states']['original_url'])) {
    return;
  }
  // Set the original url.
  $result->url = $result->options['internal_states']['original_url'];

  // Set the redirect code.
  $result->redirect_code_array = $result->options['internal_states']['redirect_code_array'];
  $result->redirect_code = array_pop($result->options['internal_states']['redirect_code_array']);

  // Set the redirect url.
  $result->redirect_url_array = $result->options['internal_states']['redirect_url_array'];
  $result->redirect_url = array_pop($result->options['internal_states']['redirect_url_array']);

  // Cleanup.
  unset($result->options['internal_states']['original_url'], $result->options['internal_states']['redirect_code_array'], $result->options['internal_states']['redirect_url_array']);
  if (empty($result->options['internal_states'])) {
    unset($result->options['internal_states']);
  }
}

/**
 * Output text, close connection, continue processing in the background.
 *
 * @param $output
 *  string - Text to output to open connection.
 * @param $wait
 *  bool - Wait 1 second?
 * @param $content_type
 *  string - Content type header.
 * @param $length
 *  int - Content length.
 *
 * @return
 *   Returns TRUE if operation worked, FALSE if it failed.
 */
function httprl_background_processing($output, $wait = TRUE, $content_type = "text/html; charset=utf-8", $length = 0) {
  // Can't do background processing if headers are already sent.
  if (headers_sent()) {
    return FALSE;
  }

  // Prime php for background operations.
  // Remove any output buffers.
  @ob_end_clean();
  $loop = 0;
  while (ob_get_level() && $loop < 25) {
    @ob_end_clean();
    $loop++;
  }

  // Ignore user aborts.
  ignore_user_abort(TRUE);

  // Output headers & data.
  ob_start();
  header("HTTP/1.0 200 OK");
  header("Content-type: " . $content_type);
  header("Expires: Sun, 19 Nov 1978 05:00:00 GMT");
  header("Cache-Control: no-cache");
  header("Cache-Control: must-revalidate");
  header("Connection: close");
  header('Etag: "' . microtime(TRUE) . '"');
  print($output);
  $size = ob_get_length();
  header("Content-Length: " . $size);
  @ob_end_flush();
  @ob_flush();
  @flush();

  if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
  }

  // wait for 1 second
  if ($wait) {
    sleep(1);
  }

  // text returned and connection closed.
  // Do background processing. Time taken after should not effect page load times.
  return TRUE;
}

/**
 * Get the length of a string in bytes.
 *
 * @param $string
 *   get string length
 */
function httprl_strlen($string) {
  static $mb_strlen;
  if (!isset($mb_strlen)) {
    $mb_strlen = function_exists('mb_strlen');
  }
  if ($mb_strlen) {
    return mb_strlen($string, '8bit');
  }
  else {
    return strlen($string);
  }
}

/**
 * Alt to http_build_url().
 *
 * @see http://php.net/parse-url#85963
 *
 * @param $parsed
 *   array from parse_url()
 * @return string
 *   URI is returned.
 */
function httprl_glue_url($parsed) {
  if (!is_array($parsed)) {
    return FALSE;
  }

  $uri = isset($parsed['scheme']) ? $parsed['scheme'] . ':' . ((strtolower($parsed['scheme']) == 'mailto') ? '' : '//') : '';
  $uri .= isset($parsed['user']) ? $parsed['user'] . (isset($parsed['pass']) ? ':' . $parsed['pass'] : '') . '@' : '';
  $uri .= isset($parsed['host']) ? $parsed['host'] : '';
  $uri .= !empty($parsed['port']) ? ':' . $parsed['port'] : '';

  if (isset($parsed['path'])) {
    $uri .= (substr($parsed['path'], 0, 1) == '/') ? $parsed['path'] : ((!empty($uri) ? '/' : '' ) . $parsed['path']);
  }

  $uri .= isset($parsed['query']) ? '?' . $parsed['query'] : '';
  $uri .= isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';

  return $uri;
}

/**
 * Return the server schema (http or https).
 *
 * @return string
 *   http OR https.
 */
function httprl_get_server_schema() {
  return (   (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')
          || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
          || (isset($_SERVER['HTTP_HTTPS']) && $_SERVER['HTTP_HTTPS'] == 'on')
            ) ? 'https' : 'http';
}

/**
 * Send out a fast 403 and exit.
 */
function httprl_fast403() {
  global $base_path;

  // Set headers.
  if (!headers_sent()) {
    header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
    header('X-HTTPRL: Forbidden.');
  }

  // Print simple 403 page.
  print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n";
  print '<html>';
  print '<head><title>403 Forbidden</title></head>';
  print '<body><h1>Forbidden</h1>';
  print '<p>You are not authorized to access this page.</p>';
  print '<p><a href="' . $base_path . '">Home</a></p>';
  print '<!-- httprl_fast403 -->';
  print '</body></html>';

  // Exit Script.
  httprl_call_exit();
}

/**
 * Release a lock previously acquired by lock_acquire().
 *
 * This will release the named lock.
 *
 * @param $name
 *   The name of the lock.
 */
function httprl_lock_release($name) {
  if (httprl_variable_get('lock_inc', './includes/lock.inc') !== './includes/lock.inc') {
    lock_release($name);
  }
  else {
    global $locks;

    unset($locks[$name]);
    if (defined('VERSION') && substr(VERSION, 0, 1) >= 7) {
      db_delete('semaphore')
        ->condition('name', $name)
        ->execute();
    }
    else {
      db_query("DELETE FROM {semaphore} WHERE name = '%s'", $name);
    }
  }
}

/**
 * Pretty print data.
 *
 * @param $data
 *   Data In.
 * @return
 *   Human readable HTML version of the data.
 */
function httprl_pr($data) {
  // Get extra arguments passed in.
  $data = func_get_args();

  // If empty print out the dump of that variable.
  foreach ($data as $key => &$value) {
    if (strlen(print_r($value, TRUE)) == 0) {
      $value = strtoupper(var_export($value, TRUE));
    }
  }

  // Merge into base array if only one argument passed in.
  if (count($data) == 1) {
    $data = array_pop($data);
  }

  // Remove non UTF-8 Characters, escape HTML markup, remove extra new lines.
  $output = array_filter(explode("\n", htmlentities(iconv('utf-8', 'utf-8//IGNORE', print_r($data, TRUE)), ENT_QUOTES, 'UTF-8')));

  // Whitespace compression.
  foreach ($output as $key => $value) {
    if (str_replace('    ', '', $value) == "(") {
      $output[$key-1] .= ' (';
      unset($output[$key]);
    }
  }

  // Replace whitespace with html markup.
  $output = str_replace('    ', '&nbsp;&nbsp;&nbsp;&nbsp;', nl2br(implode("\n", $output))) . '<br />';
  return $output;
}

/**
 * Helper function for determining hosts excluded from needing a proxy.
 *
 * @return
 *   TRUE if a proxy should be used for this host.
 */
function _httprl_use_proxy($host) {
  $proxy_exceptions = httprl_variable_get('proxy_exceptions', array('localhost', '127.0.0.1'));
  return !in_array(strtolower($host), $proxy_exceptions, TRUE);
}

/**
 * Returns a persistent variable.
 *
 * This version ignores the $conf global and reads directly from the database.
 *
 * Case-sensitivity of the variable_* functions depends on the database
 * collation used. To avoid problems, always use lower case for persistent
 * variable names.
 *
 * @param $name
 *   The name of the variable to return.
 * @param $default
 *   The default value to use if this variable has never been set.
 * @return
 *   The value of the variable.
 *
 * @see variable_del(), variable_set()
 */
function httprl_variable_get($name, $default = NULL) {
  // Try global configuration variable first.
  global $conf;
  if (isset($conf[$name])) {
    return $conf[$name];
  }

  // Try database next if not at a full bootstrap level.
  if (function_exists('db_query') && !httprl_drupal_full_bootstrap()) {
    if (defined('VERSION') && substr(VERSION, 0, 1) >= 7) {
      $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable} WHERE name = :name', array(':name' => $name))->fetchAllKeyed());

      // Use the default if need be.
      return isset($variables[$name]) ? $variables[$name] : $default;
    }
    else {
      $result = db_query("SELECT value FROM {variable} WHERE name = '%s'", $name);
      if (!empty($result)) {
        $result = db_result($result);
        if (!empty($result)) {
          $value = unserialize($result);
        }
      }

      // Use the default if need be.
      return isset($value) ? $value : $default;
    }
  }
  else {
    // Return default if database is not available or if at a full bootstrap.
    return $default;
  }
}

/**
 * Run multiple functions or methods independently or chained.
 *
 * Example for running a Drupal 6 Database query.
 * @code
 * // Run 2 queries and get it's result.
 * $max = db_result(db_query('SELECT MAX(wid) FROM {watchdog}'));
 * $min = db_result(db_query('SELECT MIN(wid) FROM {watchdog}'));
 * echo $max . ' ' . $min;
 *
 * // Doing the same thing as above but with a set of arrays.
 * $max = '';
 * $min = '';
 * $args = array(
 *   array(
 *     'type' => 'function',
 *     'call' => 'db_query',
 *     'args' => array('SELECT MAX(wid) FROM {watchdog}'),
 *   ),
 *   array(
 *     'type' => 'function',
 *     'call' => 'db_result',
 *     'args' => array('last' => NULL),
 *     'return' => &$max,
 *   ),
 *   array(
 *     'type' => 'function',
 *     'call' => 'db_query',
 *     'args' => array('SELECT MIN(wid) FROM {watchdog}'),
 *   ),
 *   array(
 *     'type' => 'function',
 *     'call' => 'db_result',
 *     'args' => array('last' => NULL),
 *     'return' => &$min,
 *   ),
 * );
 * httprl_run_array($args);
 * echo $max . ' ' . $min;
 * @endcode
 *
 * Example for running a Drupal 7 Database query.
 * @code
 * // Run a query and get it's result.
 * $min = db_select('watchdog', 'w')
 *  ->fields('w', array('wid'))
 *  ->orderBy('wid', 'DESC')
 *  ->range(999, 1)
 *  ->execute()
 *  ->fetchField();
 * echo $min;
 *
 * // Doing the same thing as above but with a set of arrays.
 * $min = '';
 * $args = array(
 *   array(
 *     'type' => 'function',
 *     'call' => 'db_select',
 *     'args' => array('watchdog', 'w',),
 *    ),
 *   array(
 *     'type' => 'method',
 *     'call' => 'fields',
 *     'args' => array('w', array('wid')),
 *   ),
 *   array(
 *     'type' => 'method',
 *     'call' => 'orderBy',
 *     'args' => array('wid', 'DESC'),
 *   ),
 *   array(
 *     'type' => 'method',
 *     'call' => 'range',
 *     'args' => array(999, 1),
 *   ),
 *   array(
 *     'type' => 'method',
 *     'call' => 'execute',
 *     'args' => array(),
 *   ),
 *   array(
 *     'type' => 'method',
 *     'call' => 'fetchField',
 *     'args' => array(),
 *     'return' => &$min,
 *   ),
 * );
 * httprl_run_array($args);
 * echo $min;
 * @endcode
 *
 * @param $array
 *   2 dimensional array
 *   array(
 *     array(
 *       'type' => function or method
 *       'call' => function name or name of object method
 *       'args' => array(
 *          List of arguments to pass in. If you set the key to last, the return
 *          value of the last thing ran will be put in this place.
 *          'last' => NULL
 *        ),
 *       'return' => what was returned from this call.
 *       'printed' => what was printed from this call.
 *       'error' => any errors that might have occurred.
 *       'last' => set the last variable to anything.
 *     )
 *   )
 */
function httprl_run_array(&$array) {
  $last = NULL;
  foreach ($array as &$data) {
    // Skip if no type is set.
    if (!isset($data['type'])) {
      continue;
    }

    // Set the last variable if so desired.
    if (isset($data['last'])) {
      $last = $data['last'];
    }

    // Replace the last key with the last thing that has been returned.
    if (isset($data['args']) && array_key_exists('last', $data['args'])) {
      $data['args']['last'] = $last;
      $data['args'] = array_values($data['args']);
    }

    // Capture output if requested.
    if (array_key_exists('printed', $data)) {
      ob_start();
    }

    // Pass by reference trick for call_user_func_array().
    $args = array();
    if (isset($data['args']) && is_array($data['args'])) {
      foreach ($data['args'] as &$arg) {
        $args[] = &$arg;
      }
    }

    // Start to capture errors.
    $track_errors = ini_set('track_errors', '1');
    $php_errormsg = '';

    // Call a function or a method.
    switch ($data['type']) {
      case 'function':
        if (function_exists($data['call'])) {
          $last = call_user_func_array($data['call'], $args);
        }
        else {
          $php_errormsg = 'Recoverable Fatal error: Call to undefined function ' . $data['call'] . '()';
        }
      break;

      case 'method':
        if (method_exists($last, $data['call'])) {
          $last = call_user_func_array(array($last, $data['call']), $args);
        }
        else {
          $php_errormsg = 'Recoverable Fatal error: Call to undefined method ' . get_class($last) . '::' . $data['call'] . '()';
        }
        break;

    }

    // Set any errors if any where thrown.
    if (!empty($php_errormsg)) {
      $data['error'] = $php_errormsg;
      ini_set('track_errors', $track_errors);
      watchdog('httprl', 'Error thrown in httprl_run_array(). <br /> @error', array('@error' => $php_errormsg),  WATCHDOG_ERROR);
    }

    // End capture.
    if (array_key_exists('printed', $data)) {
      $data['printed'] = ob_get_contents();
      ob_end_clean();
    }

    // Set what was returned from each call.
    if (array_key_exists('return', $data)) {
      $data['return'] = $last;
    }
  }

  return array('args' => array($array));
}

/**
 * Run a single function.
 *
 * @param $function
 *   Name of function to run.
 * @param $input_args
 *   list of arguments to pass along to the function.
 */
function httprl_run_function($function, &$input_args) {
  // Pass by reference trick for call_user_func_array().
  $args = array();
  foreach ($input_args as &$arg) {
    $args[] = &$arg;
  }

  // Capture anything printed out.
  ob_start();

  // Start to capture errors.
  $track_errors = ini_set('track_errors', '1');
  $php_errormsg = '';

  // Run function.
  if (function_exists($function)) {
    $return = call_user_func_array($function, $args);
  }
  else {
    $php_errormsg = 'Recoverable Fatal error: Call to undefined function ' . $function . '()';
  }

  $printed = ob_get_contents();
  ob_end_clean();

  // Create data array.
  $data = array('return' => $return, 'args' => $args, 'printed' => $printed);

  // Set any errors if any where thrown.
  if (!empty($php_errormsg)) {
    $data['error'] = $php_errormsg;
    ini_set('track_errors', $track_errors);
    watchdog('httprl', 'Error thrown in httprl_run_function(). <br /> @error', array('@error' => $php_errormsg),  WATCHDOG_ERROR);
  }

  return $data;
}

function httprl_boot() {
  global $base_root;
  $full_url = $base_root . request_uri();

  // Return if this is not a httprl_async_function_callback request.
  if (   strpos($full_url, '/httprl_async_function_callback') === FALSE
      || $_SERVER['REQUEST_METHOD'] !== 'POST'
      || empty($_POST['master_key'])
      || empty($_POST['temp_key'])
      || strpos($_POST['temp_key'], 'httprl_') !== 0
      || !empty($_POST['function'])
        ) {
    return NULL;
  }

  // Load httprl.async.inc.
  if (defined('DRUPAL_ROOT')) {
    require_once DRUPAL_ROOT . '/' . dirname(drupal_get_filename('module', 'httprl')) . '/httprl.async.inc';
  }
  else {
    require_once './' . dirname(drupal_get_filename('module', 'httprl')) . '/httprl.async.inc';
  }
  httprl_async_page();
}

/**
 * Gets the private key variable.
 *
 * @return
 *   The private key.
 */
function httprl_drupal_get_private_key() {
  $full_bootstrap = httprl_drupal_full_bootstrap();

  $private_key = $full_bootstrap ? drupal_get_private_key() : httprl_variable_get('drupal_private_key', 0);
  return $private_key;
}

/**
 * Performs end-of-request tasks and/or call exit directly.
 */
function httprl_call_exit() {
  if (defined('VERSION') && substr(VERSION, 0, 1) >= 7 && drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL) {
    drupal_exit();
  }
  else {
    exit;
  }
}

/**
 * Sees if Drupal has been fully booted.
 *
 * @return Bool
 *   TRUE if DRUPAL_BOOTSTRAP_FULL.
 *   FALse if not DRUPAL_BOOTSTRAP_FULL.
 */
function httprl_drupal_full_bootstrap() {
  static $full_bootstrap;
  if (!isset($full_bootstrap)) {
    // See if a full bootstrap has been done given the Drupal version.
    if (defined('VERSION') && substr(VERSION, 0, 1) >= 7) {
      $level = drupal_bootstrap();
      $full_bootstrap = ($level == DRUPAL_BOOTSTRAP_FULL) ? TRUE : FALSE;
    }
    else {
      $full_bootstrap = isset($GLOBALS['multibyte']) ? TRUE : FALSE;
    }
  }
  return $full_bootstrap;
}

/**
 * Sets the global user to the given user ID.
 *
 * @param $uid
 *   Integer specifying the user ID to load.
 */
function httprl_set_user($uid) {
  global $user;
  $account = user_load($uid);
  if (!empty($account)) {
    $user = $account;
    return TRUE;
  }
}

/**
 * Sets the global $_GET['q'] parameter.
 *
 * @param $q
 *   Internal URL.
 */
function httprl_set_q($q) {
  $_GET['q'] = $q;
}