-
Notifications
You must be signed in to change notification settings - Fork 52
/
browse.php
1587 lines (1095 loc) · 44.2 KB
/
browse.php
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
<?php
/*******************************************************************
* Glype is copyright and trademark 2007-2012 UpsideOut, Inc. d/b/a Glype
* and/or its licensors, successors and assigners. All rights reserved.
*
* Use of Glype is subject to the terms of the Software License Agreement.
* http://www.glype.com/license.php
*******************************************************************
* This file is the main component of the glype proxy application.
* It decodes values contained within the current URI to determine a
* resource to download and pass onto the user.
******************************************************************/
/*****************************************************************
* Initialise
******************************************************************/
require 'includes/init.php';
if (count($adminDetails)===0) {
header("HTTP/1.1 302 Found"); header("Location: admin.php"); exit;
}
# Debug mode - stores extra information in the cURL wrapper object and prints it
# out. It produces an ugly mess but still a quick tool for debugging.
define('DEBUG_MODE', 0);
define('CURL_LOG', 0);
# Log cURLs activity to file
# Change filename below if desired. Ensure file exists and is writable.
if ( CURL_LOG && ( $fh = @fopen('curl.txt', 'w')) ) {
$toSet[CURLOPT_STDERR] = $fh;
$toSet[CURLOPT_VERBOSE] = true;
}
/*****************************************************************
* PHP sends some headers by default. Stop them.
******************************************************************/
# Clear the default mime-type
header('Content-Type:');
# And remove the caching headers
header('Cache-Control:');
header('Last-Modified:');
/*****************************************************************
* Find URI of resource to load
* NB: flag and bitfield already extracted in /includes/init.php
******************************************************************/
switch ( true ) {
# Try query string for URL
case ! empty($_GET['u']) && ( $toLoad = deproxyURL($_GET['u'], true) ):
break;
# Try path info
case ! empty($_SERVER['PATH_INFO']) && ( $toLoad = deproxyURL($_SERVER['PATH_INFO'], true) ):
break;
# Found no valid URL, return to index
default:
redirect();
}
# Validate the URL
if ( ! preg_match('#^((https?)://(?:([a-z0-9-.]+:[a-z0-9-.]+)@)?([a-z0-9-.]+)(?::([0-9]+))?)(?:/|$)((?:[^?/]*/)*)([^?]*)(?:\?([^\#]*))?(?:\#.*)?$#i', $toLoad, $tmp) ) {
# Invalid, show error
error('invalid_url', htmlentities($toLoad));
}
# Rename parts to more useful names
$URL = array(
'scheme_host' => $tmp[1],
'scheme' => $tmp[2],
'auth' => $tmp[3],
'host' => strtolower($tmp[4]),
'domain' => preg_match('#(?:^|\.)([a-z0-9-]+\.(?:[a-z.]{5,6}|[a-z]{2,}))$#', $tmp[4], $domain) ? $domain[1] : $tmp[4], # Attempt to split off the subdomain (if any)
'port' => $tmp[5],
'path' => '/' . $tmp[6],
'filename' => $tmp[7],
'extension' => pathinfo($tmp[7], PATHINFO_EXTENSION),
'query' => isset($tmp[8]) ? $tmp[8] : ''
);
# Apply encoding on full URL. In theory all parts of the URL need various special
# characters encoding but this needs to be done by the author of the webpage.
# We can make a guess at what needs encoding but some servers will complain when
# receiving the encoded character instead of unencoded and vice versa. We want
# to edit the URL as little as possible so we're only encoding spaces, as this
# seems to 'fix' the majority of cases.
$URL['href'] = str_replace(' ', '%20', $toLoad);
# Protect LAN from access through proxy (protected addresses copied from PHProxy)
if ( preg_match('#^(?:127\.|192\.168\.|10\.|172\.(?:1[6-9]|2[0-9]|3[01])\.|localhost)#i', $URL['host']) ) {
error('banned_site', $URL['host']);
}
# Add any supplied authentication information to our auth array
if ( $URL['auth'] ) {
$_SESSION['authenticate'][$URL['scheme_host']] = $URL['auth'];
}
/*****************************************************************
* Protect us from hotlinking
******************************************************************/
# Protect only if option is enabled and we don't have a verified session
if ( $CONFIG['stop_hotlinking'] && empty($_SESSION['no_hotlink']) ) {
# Assume hotlinking to start with, then check against allowed domains
$tmp = true;
# Ensure we have valid referrer information to check
if ( ! empty($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'http') === 0 ) {
# Examine all the allowed domains (including our current domain)
foreach ( array_merge( (array) GLYPE_URL, $CONFIG['hotlink_domains'] ) as $domain ) {
# Do a case-insensitive comparison
if ( stripos($_SERVER['HTTP_REFERER'], $domain) !== false ) {
# This referrer is OK
$tmp = false;
break;
}
}
}
# Redirect to index if this is still identified as hotlinking
if ( $tmp ) {
error('no_hotlink');
}
}
# If we're still here, the referrer must be OK so set the session for next time
$_SESSION['no_hotlink'] = true;
/*****************************************************************
* Are we allowed to visit this site? Check whitelist/blacklist
******************************************************************/
# Whitelist - deny IF NOT on list
if ( ! empty($CONFIG['whitelist']) ) {
$tmp = false;
# Loop through
foreach ( $CONFIG['whitelist'] as $domain ) {
# Check for match
if ( strpos($URL['host'], $domain) !== false ) {
# Must be a permitted site
$tmp = true;
}
}
# Unless $tmp is flagged true, this is an illegal site
if ( ! $tmp ) {
error('banned_site', $URL['host']);
}
}
# Blacklist
if ( ! empty($CONFIG['blacklist']) ) {
# Loop through
foreach ( $CONFIG['blacklist'] as $domain ) {
# Check for match
if ( strpos($URL['host'], $domain) !== false ) {
# If matched, site is banned
error('banned_site', $URL['host']);
}
}
}
/*****************************************************************
* Show SSL warning
* This warns users if they access a secure site when the proxy is NOT
* on a secure connection and the $CONFIG['ssl_warning'] option is on.
******************************************************************/
if ( $URL['scheme'] == 'https' && $CONFIG['ssl_warning'] && empty($_SESSION['ssl_warned']) && ! HTTPS ) {
# Remember this page so we can return after agreeing to the warning
$_SESSION['return'] = currentURL();
# Don't cache the warning page
sendNoCache();
# Show the page
echo loadTemplate('sslwarning.page');
# All done!
exit;
}
/*****************************************************************
* Plugins
* Load any site-specific plugin.
******************************************************************/
$plugins = explode(',', $CONFIG['plugins']);
if ($foundPlugin = in_array($URL['domain'], $plugins)) {
include(GLYPE_ROOT.'/plugins/'.$URL['domain'].'.php');
}
/*****************************************************************
* Close session to allow simultaneous transfers
* PHP automatically prevents multiple instances of the script running
* simultaneously to avoid concurrency issues with the session.
* This may be beneficial on high traffic servers but we have the option
* to close the session and thus allow simultaneous transfers.
******************************************************************/
if ( ! $CONFIG['queue_transfers'] ) {
session_write_close();
}
/*****************************************************************
* * * * * * * * * * Prepare the REQUEST * * * * * * * * * * * *
******************************************************************/
/*****************************************************************
* Set cURL transfer options
* These options are merely passed to cURL and our script has no further
* impact or dependence of them. See the libcurl documentation and
* http://php.net/curl_setopt for more details.
*
* The following options are required for the proxy to function or
* inherit values from our config. In short: they shouldn't need changing.
******************************************************************/
# Time to wait for connection
$toSet[CURLOPT_CONNECTTIMEOUT] = $CONFIG['connection_timeout'];
# Time to allow for entire transfer
$toSet[CURLOPT_TIMEOUT] = $CONFIG['transfer_timeout'];
# Show SSL without verifying - we almost definitely don't have an up to date CA cert
# bundle so we can't verify the certificate. See http://curl.haxx.se/docs/sslcerts.html
$toSet[CURLOPT_SSL_VERIFYPEER] = false;
$toSet[CURLOPT_SSL_VERIFYHOST] = false;
# Send an empty Expect header (avoids 100 responses)
$toSet[CURLOPT_HTTPHEADER][] = 'Expect:';
# Can we use "If-Modified-Since" to save a transfer? Server can return 304 Not Modified
if ( isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ) {
# How to treat the time condition : if un/modified since
$toSet[CURLOPT_TIMECONDITION] = CURL_TIMECOND_IFMODSINCE;
# The time value. Requires a timestamp so we can't just forward it raw
$toSet[CURLOPT_TIMEVALUE] = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
}
# Resume a transfer?
if ( $CONFIG['resume_transfers'] && isset($_SERVER['HTTP_RANGE']) ) {
# And give cURL the right part
$toSet[CURLOPT_RANGE] = substr($_SERVER['HTTP_RANGE'], 6);
}
# cURL has a max filesize option but it's not listed in the PHP manual so check it's available
if ( $CONFIG['max_filesize'] && defined('CURLOPT_MAXFILESIZE') ) {
# Use the cURL option - should be faster than our implementation
$toSet[CURLOPT_MAXFILESIZE] = $CONFIG['max_filesize'];
}
/*****************************************************************
* Performance options
* The values below are NOT the result of benchmarking tests. For
* optimum performance, you may want to try adjusting these values.
******************************************************************/
# DNS cache expiry time (seconds)
$toSet[CURLOPT_DNS_CACHE_TIMEOUT] = 600;
# Speed limits - aborts transfer if we're going too slowly
#$toSet[CURLOPT_LOW_SPEED_LIMIT] = 5; # speed limit in bytes per second
#$toSet[CURLOPT_LOW_SPEED_TIME] = 20; # seconds spent under the speed limit before aborting
# Number of max connections (no idea what this should be)
# $toSet[CURLOPT_MAXCONNECTS] = 100;
# Accept encoding in any format (allows compressed pages to be downloaded)
# Any bandwidth savings are likely to be minimal so better to save on load by
# downloading pages uncompressed. Use blank string for any compression or
# 'identity' to explicitly ask for uncompressed.
# $toSet[CURLOPT_ENCODING] = '';
# Undocumented in PHP manual (added 5.2.1) but allows uploads to some sites
# (e.g. imageshack) when without this option, an error occurs. Less efficient
# so probably best not to set this unless you need it.
# $toSet[CURLOPT_TCP_NODELAY] = true;
/*****************************************************************
* "Accept" headers
* No point sending back a file that the browser won't understand.
* Forward all the "Accept" headers. For each, check if it exists
* and if yes, add to the custom headers array.
* NB: These may cause problems if the target server provides different
* content for the same URI based on these headers and we cache the response.
******************************************************************/
# Language (geotargeting will find the location of the server -
# forwarding this header can help avoid incorrect localisation)
if ( isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ) {
$toSet[CURLOPT_HTTPHEADER][] = 'Accept-Language: ' . $_SERVER['HTTP_ACCEPT_LANGUAGE'];
}
# Accepted filetypes
if ( isset($_SERVER['HTTP_ACCEPT']) ) {
$toSet[CURLOPT_HTTPHEADER][] = 'Accept: ' . $_SERVER['HTTP_ACCEPT'];
}
# Accepted charsets
if ( isset($_SERVER['HTTP_ACCEPT_CHARSET']) ) {
$toSet[CURLOPT_HTTPHEADER][] = 'Accept-Charset: ' . $_SERVER['HTTP_ACCEPT_CHARSET'];
}
/*****************************************************************
* Browser options
* Allows customization of a "virtual" browser via /extras/edit-browser.php
******************************************************************/
# Send user agent
if ( $_SESSION['custom_browser']['user_agent'] ) {
$toSet[CURLOPT_USERAGENT] = $_SESSION['custom_browser']['user_agent'];
}
# Set referrer
if ( $_SESSION['custom_browser']['referrer'] == 'real' ) {
# Automatically determine referrer
if ( isset($_SERVER['HTTP_REFERER']) && $flag != 'norefer' && strpos($tmp = deproxyURL($_SERVER['HTTP_REFERER']), GLYPE_URL) === false ) {
$toSet[CURLOPT_REFERER] = $tmp;
}
} else if ( $_SESSION['custom_browser']['referrer'] ) {
# Send custom referrer
$toSet[CURLOPT_REFERER] = $_SESSION['custom_browser']['referrer'];
}
# Clear the norefer flag
if ( $flag == 'norefer' ) {
$flag = '';
}
/*****************************************************************
* Authentication
******************************************************************/
# Check for stored credentials for this site
if ( isset($_SESSION['authenticate'][$URL['scheme_host']]) ) {
# Found credentials so use them!
$toSet[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC;
$toSet[CURLOPT_USERPWD] = $_SESSION['authenticate'][$URL['scheme_host']];
}
/*****************************************************************
* Cookies
* Find the relevant cookies for this request. All cookies get sent
* to the proxy, but we only want to forward the ones that were set
* for the current domain.
*
* Cookie storage methods:
* (1) Server-side - cookies stored server-side and handled
* (mostly) internally by cURL
* (2) Encoded - cookies forwarded to client but encoded
* (3) Normal - cookies forwarded without encoding
******************************************************************/
# Are cookies allowed?
if ( $options['allowCookies'] ) {
# Option (1): cookies stored server-side
if ( $CONFIG['cookies_on_server'] ) {
# Check cookie folder exists or try to create it
if ( $s = checkTmpDir($CONFIG['cookies_folder'], 'Deny from all') ) {
# Set cURL to use this as the cookie jar
$toSet[CURLOPT_COOKIEFILE] = $toSet[CURLOPT_COOKIEJAR] = $CONFIG['cookies_folder'] . session_id();
}
} else if ( isset($_COOKIE[COOKIE_PREFIX]) ) {
# Encoded or unencoded?
if ( $CONFIG['encode_cookies'] ) {
# Option (2): encoded cookies stored client-side
foreach ( $_COOKIE[COOKIE_PREFIX] as $attributes => $value ) {
# Decode cookie to [domain,path,name]
$attributes = explode(' ', base64_decode($attributes));
# Check successful decoding and skip if failed
if ( ! isset($attributes[2]) ) {
continue;
}
# Extract parts
list($domain, $path, $name) = $attributes;
# Check for a domain match and skip if no match
if ( stripos($URL['host'], $domain) === false ) {
continue;
}
# Check for match and skip to next path if fail
if ( stripos($URL['path'], $path) !== 0 ) {
continue;
}
# Multiple cookies of the same name are permitted if different paths
# so use path AND name as the key in the temp array
$key = $path . $name;
# Check for existing cookie with same domain, same path and same name
if ( isset($toSend[$key]) && $toSend[$key]['path'] == $path && $toSend[$key]['domain'] > strlen($domain) ) {
# Conflicting cookies so ignore the one with the less complete tail match
# (i.e. the current one)
continue;
}
# Domain and path OK, decode cookie value
$value = base64_decode($value);
# Only send secure cookies on https connection - secure cookies marked by !SEC suffix
# so remove the suffix
$value = str_replace('!SEC', '', $value, $tmp);
# And if secure cookie but not https site, do not send
if ( $tmp && $URL['scheme'] != 'https' ) {
continue;
}
# Everything checked and verified, add to $toSend for further processing later
$toSend[$key] = array('path_size' => strlen($path), 'path' => $path, 'domain' => strlen($domain), 'send' => $name . '=' . $value);
}
} else {
# Option (3): unencoded cookies stored client-side
foreach ( $_COOKIE[COOKIE_PREFIX] as $domain => $paths ) {
# $domain holds the domain (surprisingly) and $path is an array
# of keys (paths) and more arrays (each child array of $path = one cookie)
# e.g. Array('domain.com' => Array('/' => Array('cookie_name' => 'value')))
# First check for domain match and skip to next domain if no match
if ( stripos($URL['host'], $domain) === false ) {
continue;
}
# If conflicting cookies with same name and same path,
# send the one with the more complete tail match. To do this we
# need to know how long each match is/was so record domain length.
$domainSize = strlen($domain);
# Now look at all the available paths
foreach ( $paths as $path => $cookies ) {
# Check for match and skip to next path if fail
if ( stripos($URL['path'], $path) !== 0 ) {
continue;
}
# In final header, cookies are ordered with most specific path
# matches first so include the length of match in temp array
$pathSize = strlen($path);
# All cookies in $cookies array should be sent
foreach ( $cookies as $name => $value ) {
# Multiple cookies of the same name are permitted if different paths
# so use path AND name as the key in the temp array
$key = $path . $name;
# Check for existing cookie with same domain, same path and same name
if ( isset($toSend[$key]) && $toSend[$key]['path'] == $path && $toSend[$key]['domain'] > $domainSize ) {
# Conflicting cookies so ignore the one with the less complete tail match
# (i.e. the current one)
continue;
}
# Only send secure cookies on https connection - secure cookies marked by !SEC suffix
# so remove the suffix
$value = str_replace('!SEC', '', $value, $tmp);
# And if secure cookie but not https site, do not send
if ( $tmp && $URL['scheme'] != 'https' ) {
continue;
}
# Add to $toSend for further processing later
$toSend[$key] = array('path_size' => $pathSize, 'path' => $path, 'domain' => $domainSize, 'send' => $name . '=' . $value);
}
}
}
}
# Ensure we have found cookies
if ( ! empty($toSend) ) {
# Order by path specificity (as per Netscape spec)
function compareArrays($a, $b) {
return ( $a['path_size'] > $b['path_size'] ) ? -1 : 1;
}
# Apply the sort to order by path_size descending
uasort($toSend, 'compareArrays');
# Go through the ordered array and generate the Cookie: header
$tmp = '';
foreach ( $toSend as $cookie ) {
$tmp .= $cookie['send'] . '; ';
}
# Give the string to cURL
$toSet[CURLOPT_COOKIE] = $tmp;
}
# And clear the toSend array
unset($toSend);
}
}
/*****************************************************************
* Post
* Forward the post data. Usually very simple but complicated by
* multipart forms because in those cases, the raw post is not available.
******************************************************************/
if ( ! empty($_POST) ) {
# Attempt to get raw POST from the input wrapper
if ( ! ($tmp = file_get_contents('php://input')) ) {
# Raw data not available (probably multipart/form-data).
# cURL will do a multipart post if we pass an array as the
# POSTFIELDS value but this array can only be one deep.
# Recursively flatten array to one level deep and rename keys
# as firstLayer[second][etc]. Also apply the input decode to all
# array keys.
function flattenArray($array, $prefix='') {
# Start with empty array
$stack = array();
# Loop through the array to flatten
foreach ( $array as $key => $value ) {
# Decode the input name
$key = inputDecode($key);
# Determine what the new key should be - add the current key to
# the prefix and surround in []
$newKey = $prefix ? $prefix . '[' . $key . ']' : $key;
if ( is_array($value) ) {
# If it's an array, recurse and merge the returned array
$stack = array_merge($stack, flattenArray($value, $newKey));
} else {
# Otherwise just add it to the current stack
$stack[$newKey] = clean($value);
}
}
# Return flattened
return $stack;
}
$tmp = flattenArray($_POST);
# Add any file uploads?
if ( ! empty($_FILES) ) {
# Loop through and add the files
foreach ( $_FILES as $name => $file ) {
# Is this an array?
if ( is_array($file['tmp_name']) ) {
# Flatten it - file arrays are in the slightly odd format of
# $_FILES['layer1']['tmp_name']['layer2']['layer3,etc.'] so add
# layer1 onto the start.
$flattened = flattenArray(array($name => $file['tmp_name']));
# And add all files to the post
foreach ( $flattened as $key => $value ) {
$tmp[$key] = '@' . $value;
}
} else {
# Not another array. Check if the file uploaded successfully?
if ( ! empty($file['error']) || empty($file['tmp_name']) ) {
continue;
}
# Add to array with @ - tells cURL to upload this file
$tmp[$name] = '@' . $file['tmp_name'];
}
# To do: rename the temp file to it's real name before
# uploading it to the target? Otherwise, the target receives
# the temp name instead of the original desired name
# but doing this may be a security risk.
}
}
}
# Convert back to GET if required
if ( isset($_POST['convertGET']) ) {
# Remove convertGET from POST array and update our location
$URL['href'] .= ( empty($URL['query']) ? '?' : '&' ) . str_replace('convertGET=1', '', $tmp);
} else {
# Genuine POST so set the cURL post value
$toSet[CURLOPT_POST] = 1;
$toSet[CURLOPT_POSTFIELDS] = $tmp;
}
}
/*****************************************************************
* Apply pre-request code from plugins
******************************************************************/
if ( $foundPlugin && function_exists('preRequest') ) {
preRequest();
}
/*****************************************************************
* Make the request
* This request object uses custom header/body reading functions
* so we can start processing responses on the fly - e.g. we don't
* need to wait till the whole file has downloaded before deciding
* if it needs parsing or can be sent out unchanged.
******************************************************************/
class Request {
# Response status code
public $status = 0;
# Headers received and read by our callback
public $headers = array();
# Returned data (if saved)
public $return;
# Reason for aborting transfer (or empty to continue downloading)
public $abort;
# The error (if any) returned by curl_error()
public $error;
# Type of resource downloaded [html, js, css] or empty if no parsing needed
public $parseType;
# Automatically detect(ed) content type?
public $sniff = false;
# Forward cookies or not
private $forwardCookies = false;
# Limit filesize?
private $limitFilesize = 0;
# Speed limit (bytes per second)
private $speedLimit = 0;
# URL array split into pieces
private $URL;
# = $options from the global scope
private $browsingOptions;
# Options to pass to cURL
private $curlOptions;
# Constructor - takes the parameters and saves them
public function __construct($curlOptions) {
global $options, $CONFIG;
# Set our reading callbacks
$curlOptions[CURLOPT_HEADERFUNCTION] = array(&$this, 'readHeader');
$curlOptions[CURLOPT_WRITEFUNCTION] = array(&$this, 'readBody');
# Determine whether or not to forward cookies
if ( $options['allowCookies'] && ! $CONFIG['cookies_on_server'] ) {
$this->forwardCookies = $CONFIG['encode_cookies'] ? 'encode' : 'normal';
}
# Determine a filesize limit
if ( $CONFIG['max_filesize'] ) {
$this->limitFilesize = $CONFIG['max_filesize'];
}
# Determine speed limit
if ( $CONFIG['download_speed_limit'] ) {
$this->speedLimit = $CONFIG['download_speed_limit'];
}
# Set options
$this->browsingOptions = $options;
$this->curlOptions = $curlOptions;
# Extend the PHP timeout
if ( ! SAFE_MODE ) {
set_time_limit($CONFIG['transfer_timeout']);
}
# Record debug information
if ( DEBUG_MODE ) {
$this->cookiesSent = isset($curlOptions[CURLOPT_COOKIE]) ? $curlOptions[CURLOPT_COOKIE] : ( isset($curlOptions[CURLOPT_COOKIEFILE]) ? 'using cookie jar' : 'none');
$this->postSent = isset($curlOptions[CURLOPT_POSTFIELDS]) ? $curlOptions[CURLOPT_POSTFIELDS] : '';
}
}
# Make the request and return the downloaded file if parsing is needed
public function go($URL) {
# Save options
$this->URL = $URL;
# Get a cURL handle
$ch = curl_init($this->URL['href']);
# Set the options
curl_setopt_array($ch, $this->curlOptions);
# Make the request
curl_exec($ch);
# Save any errors (but not if we caused the error by aborting!)
if ( ! $this->abort ) {
$this->error = curl_error($ch);
}
# And close the curl handle
curl_close($ch);
# And return the document (will be empty if no parsing needed,
# because everything else is outputted immediately)
return $this->return;
}
/*****************************************************************
* * * * * * * * * * Manage the RESPONSE * * * * * * * * * * * *
******************************************************************/
/*****************************************************************
* Read headers - receives headers line by line (cURL callback)
******************************************************************/
public function readHeader($handle, $header) {
# Extract the status code (can occur more than once if 100 continue)
if ( $this->status == 0 || ( $this->status == 100 && ! strpos($header, ':') ) ) {
$this->status = substr($header, 9, 3);
}
# Attempt to extract header name and value
$parts = explode(':', $header, 2);
# Did it split successfully? (i.e. was there a ":" in the header?)
if ( isset($parts[1]) ) {
# Header names are case insensitive
$headerType = strtolower($parts[0]);
# And header values will have trailing newlines and prevailing spaces
$headerValue = trim($parts[1]);
# Set any cookies
if ( $headerType == 'set-cookie' && $this->forwardCookies ) {
$this->setCookie($headerValue);
}
# Everything else, store as associative array
$this->headers[$headerType] = $headerValue;
# Do we want to forward this header? First list the headers we want:
$toForward = array('last-modified',
'content-disposition',
'content-type',
'content-range',
'content-language',
'expires',
'cache-control',
'pragma');
# And check for a match before forwarding the header.
if ( in_array($headerType, $toForward) ) {
header($header);
}
} else {
# Either first header or last 'header' (more precisely, the 2 newlines
# that indicate end of headers)
# No ":", so save whole header. Also check for end of headers.
if ( ( $this->headers[] = trim($header) ) == false ) {
# Must be end of headers so process them before reading body
$this->processHeaders();
# And has that processing given us any reason to abort?
if ( $this->abort ) {
return -1;
}
}
}
# cURL needs us to return length of data read
return strlen($header);
}
/*****************************************************************
* Process headers after all received and before body is read
******************************************************************/
private function processHeaders() {
# Ensure we only run this function once
static $runOnce;
# Check for flag and if found, stop running function
if ( isset($runOnce) ) {
return;
}
# Set flag for next time
$runOnce = true;
# Send the appropriate status code
header(' ', true, $this->status);
# Find out if we want to abort the transfer
switch ( true ) {
# Redirection
case isset($this->headers['location']):
$this->abort = 'redirect';
return;
# 304 Not Modified
case $this->status == 304:
$this->abort = 'not_modified';
return;
# 401 Auth required
case $this->status == 401:
$this->abort = 'auth_required';
return;
# Error code (>=400)
case $this->status >= 400:
$this->abort = 'http_status_error';
return;
# Check for a content-length above the filesize limit
case isset($this->headers['content-length']) && $this->limitFilesize && $this->headers['content-length'] > $this->limitFilesize:
$this->abort = 'filesize_limit';
return;
}
# Still here? No need to abort so next we determine parsing mechanism to use (if any)
if ( isset($this->headers['content-type']) ) {
# Define content-type to parser type relations
$types = array('text/javascript' => 'javascript',
'application/javascript' => 'javascript',
'application/x-javascript' => 'javascript',
'application/xhtml+xml' => 'html',
'text/html' => 'html',
'text/css' => 'css');
# Extract mimetype from charset (if exists)
list($mime) = explode(';', $this->headers['content-type'], 2);
# Remove whitespace
$mime = trim($mime);
# Look for that mimetype in our array to find the parsing mechanism needed
if ( isset($types[$mime]) ) {
$this->parseType = $types[$mime];
}
} else {
# Tell our read body function to 'sniff' the data to determine type
$this->sniff = true;
}
# If no content-disposition sent, send one with the correct filename
if ( ! isset($this->headers['content-disposition']) && $this->URL['filename'] ) {
header('Content-Disposition: filename="' . $this->URL['filename'] . '"');