* fix etag caching
[m6w6/ext-http] / http.c
1 /*
2 +----------------------------------------------------------------------+
3 | PECL :: http |
4 +----------------------------------------------------------------------+
5 | This source file is subject to version 3.0 of the PHP license, that |
6 | is bundled with this package in the file LICENSE, and is available |
7 | through the world-wide-web at http://www.php.net/license/3_0.txt. |
8 | If you did not receive a copy of the PHP license and are unable to |
9 | obtain it through the world-wide-web, please send a note to |
10 | license@php.net so we can mail you a copy immediately. |
11 +----------------------------------------------------------------------+
12 | Copyright (c) 2004-2005 Michael Wallner <mike@php.net> |
13 +----------------------------------------------------------------------+
14 */
15
16 /* $Id$ */
17
18 #define ZEND_INCLUDE_FULL_WINDOWS_HEADERS
19
20 #ifdef HAVE_CONFIG_H
21 # include "config.h"
22 #endif
23
24 #include "php.h"
25 #include "php_ini.h"
26 #include "snprintf.h"
27 #include "ext/standard/info.h"
28 #include "ext/session/php_session.h"
29 #include "ext/standard/php_string.h"
30 #include "ext/standard/php_smart_str.h"
31
32 #include "SAPI.h"
33
34 #include "php_http.h"
35 #include "php_http_api.h"
36
37 #ifdef ZEND_ENGINE_2
38 # include "ext/standard/php_http.h"
39 #endif
40
41 #ifdef HTTP_HAVE_CURL
42
43 # ifdef PHP_WIN32
44 # include <winsock2.h>
45 # include <sys/types.h>
46 # endif
47
48 # include <curl/curl.h>
49
50 /* {{{ ARG_INFO */
51 # ifdef ZEND_BEGIN_ARG_INFO
52 ZEND_BEGIN_ARG_INFO(http_request_info_ref_3, 0)
53 ZEND_ARG_PASS_INFO(0)
54 ZEND_ARG_PASS_INFO(0)
55 ZEND_ARG_PASS_INFO(1)
56 ZEND_END_ARG_INFO();
57
58 ZEND_BEGIN_ARG_INFO(http_request_info_ref_4, 0)
59 ZEND_ARG_PASS_INFO(0)
60 ZEND_ARG_PASS_INFO(0)
61 ZEND_ARG_PASS_INFO(0)
62 ZEND_ARG_PASS_INFO(1)
63 ZEND_END_ARG_INFO();
64 # else
65 static unsigned char http_request_info_ref_3[] = {3, BYREF_NONE, BYREF_NONE, BYREF_FORCE};
66 static unsigned char http_request_info_ref_4[] = {4, BYREF_NONE, BYREF_NONE, BYREF_NONE, BYREF_FORCE};
67 # endif
68 /* }}} ARG_INFO */
69
70 #endif /* HTTP_HAVE_CURL */
71
72 ZEND_DECLARE_MODULE_GLOBALS(http)
73
74 #ifdef COMPILE_DL_HTTP
75 ZEND_GET_MODULE(http)
76 #endif
77
78
79 /* {{{ http_functions[] */
80 function_entry http_functions[] = {
81 PHP_FE(http_date, NULL)
82 PHP_FE(http_absolute_uri, NULL)
83 PHP_FE(http_negotiate_language, NULL)
84 PHP_FE(http_negotiate_charset, NULL)
85 PHP_FE(http_redirect, NULL)
86 PHP_FE(http_send_status, NULL)
87 PHP_FE(http_send_last_modified, NULL)
88 PHP_FE(http_match_modified, NULL)
89 PHP_FE(http_match_etag, NULL)
90 PHP_FE(http_cache_last_modified, NULL)
91 PHP_FE(http_cache_etag, NULL)
92 PHP_FE(http_content_type, NULL)
93 PHP_FE(http_content_disposition, NULL)
94 PHP_FE(http_send_data, NULL)
95 PHP_FE(http_send_file, NULL)
96 PHP_FE(http_send_stream, NULL)
97 PHP_FE(http_chunked_decode, NULL)
98 PHP_FE(http_split_response, NULL)
99 PHP_FE(http_parse_headers, NULL)
100 PHP_FE(http_get_request_headers, NULL)
101 #ifdef HTTP_HAVE_CURL
102 PHP_FE(http_get, http_request_info_ref_3)
103 PHP_FE(http_head, http_request_info_ref_3)
104 PHP_FE(http_post_data, http_request_info_ref_4)
105 PHP_FE(http_post_array, http_request_info_ref_4)
106 #endif
107 PHP_FE(http_auth_basic, NULL)
108 PHP_FE(http_auth_basic_cb, NULL)
109 #ifndef ZEND_ENGINE_2
110 PHP_FE(http_build_query, NULL)
111 #endif
112 {NULL, NULL, NULL}
113 };
114 /* }}} */
115
116 /* {{{ http_module_entry */
117 zend_module_entry http_module_entry = {
118 #if ZEND_MODULE_API_NO >= 20010901
119 STANDARD_MODULE_HEADER,
120 #endif
121 "http",
122 http_functions,
123 PHP_MINIT(http),
124 NULL,
125 NULL,
126 PHP_RSHUTDOWN(http),
127 PHP_MINFO(http),
128 #if ZEND_MODULE_API_NO >= 20010901
129 PHP_EXT_HTTP_VERSION,
130 #endif
131 STANDARD_MODULE_PROPERTIES
132 };
133 /* }}} */
134
135 #define RETURN_SUCCESS(v) RETURN_BOOL(SUCCESS == (v))
136 #define HASH_ORNULL(z) ((z) ? Z_ARRVAL_P(z) : NULL)
137
138 /* {{{ proto string http_date([int timestamp])
139 *
140 * This function returns a valid HTTP date regarding RFC 822/1123
141 * looking like: "Wed, 22 Dec 2004 11:34:47 GMT"
142 *
143 */
144 PHP_FUNCTION(http_date)
145 {
146 long t = -1;
147
148 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &t) != SUCCESS) {
149 RETURN_FALSE;
150 }
151
152 if (t == -1) {
153 t = (long) time(NULL);
154 }
155
156 RETURN_STRING(http_date(t), 0);
157 }
158 /* }}} */
159
160 /* {{{ proto string http_absolute_uri(string url[, string proto])
161 *
162 * This function returns an absolute URI constructed from url.
163 * If the url is already abolute but a different proto was supplied,
164 * only the proto part of the URI will be updated. If url has no
165 * path specified, the path of the current REQUEST_URI will be taken.
166 * The host will be taken either from the Host HTTP header of the client
167 * the SERVER_NAME or just localhost if prior are not available.
168 *
169 * Some examples:
170 * <pre>
171 * url = "page.php" => http://www.example.com/current/path/page.php
172 * url = "/page.php" => http://www.example.com/page.php
173 * url = "/page.php", proto = "https" => https://www.example.com/page.php
174 * </pre>
175 *
176 */
177 PHP_FUNCTION(http_absolute_uri)
178 {
179 char *url = NULL, *proto = NULL;
180 int url_len = 0, proto_len = 0;
181
182 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &url, &url_len, &proto, &proto_len) != SUCCESS) {
183 RETURN_FALSE;
184 }
185
186 RETURN_STRING(http_absolute_uri(url, proto), 0);
187 }
188 /* }}} */
189
190 /* {{{ proto string http_negotiate_language(array supported[, string default = 'en-US'])
191 *
192 * This function negotiates the clients preferred language based on its
193 * Accept-Language HTTP header. It returns the negotiated language or
194 * the default language if none match.
195 *
196 * The qualifier is recognized and languages without qualifier are rated highest.
197 *
198 * The supported parameter is expected to be an array having
199 * the supported languages as array values.
200 *
201 * Example:
202 * <pre>
203 * <?php
204 * $langs = array(
205 * 'en-US',// default
206 * 'fr',
207 * 'fr-FR',
208 * 'de',
209 * 'de-DE',
210 * 'de-AT',
211 * 'de-CH',
212 * );
213 * include './langs/'. http_negotiate_language($langs) .'.php';
214 * ?>
215 * </pre>
216 *
217 */
218 PHP_FUNCTION(http_negotiate_language)
219 {
220 zval *supported;
221 char *def = NULL;
222 int def_len = 0;
223
224 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|s", &supported, &def, &def_len) != SUCCESS) {
225 RETURN_FALSE;
226 }
227
228 if (!def) {
229 def = "en-US";
230 }
231
232 RETURN_STRING(http_negotiate_language(supported, def), 0);
233 }
234 /* }}} */
235
236 /* {{{ proto string http_negotiate_charset(array supported[, string default = 'iso-8859-1'])
237 *
238 * This function negotiates the clients preferred charset based on its
239 * Accept-Charset HTTP header. It returns the negotiated charset or
240 * the default charset if none match.
241 *
242 * The qualifier is recognized and charset without qualifier are rated highest.
243 *
244 * The supported parameter is expected to be an array having
245 * the supported charsets as array values.
246 *
247 * Example:
248 * <pre>
249 * <?php
250 * $charsets = array(
251 * 'iso-8859-1', // default
252 * 'iso-8859-2',
253 * 'iso-8859-15',
254 * 'utf-8'
255 * );
256 * $pref = http_negotiate_charset($charsets);
257 * if (!strcmp($pref, 'iso-8859-1')) {
258 * iconv_set_encoding('internal_encoding', 'iso-8859-1');
259 * iconv_set_encoding('output_encoding', $pref);
260 * ob_start('ob_iconv_handler');
261 * }
262 * ?>
263 * </pre>
264 */
265 PHP_FUNCTION(http_negotiate_charset)
266 {
267 zval *supported;
268 char *def = NULL;
269 int def_len = 0;
270
271 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|s", &supported, &def, &def_len) != SUCCESS) {
272 RETURN_FALSE;
273 }
274
275 if (!def) {
276 def = "iso-8859-1";
277 }
278
279 RETURN_STRING(http_negotiate_charset(supported, def), 0);
280 }
281 /* }}} */
282
283 /* {{{ proto bool http_send_status(int status)
284 *
285 * Send HTTP status code.
286 *
287 */
288 PHP_FUNCTION(http_send_status)
289 {
290 int status = 0;
291
292 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &status) != SUCCESS) {
293 RETURN_FALSE;
294 }
295 if (status < 100 || status > 510) {
296 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid HTTP status code (100-510): %d", status);
297 RETURN_FALSE;
298 }
299
300 RETURN_SUCCESS(http_send_status(status));
301 }
302 /* }}} */
303
304 /* {{{ proto bool http_send_last_modified([int timestamp])
305 *
306 * This converts the given timestamp to a valid HTTP date and
307 * sends it as "Last-Modified" HTTP header. If timestamp is
308 * omitted, current time is sent.
309 *
310 */
311 PHP_FUNCTION(http_send_last_modified)
312 {
313 long t = -1;
314
315 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &t) != SUCCESS) {
316 RETURN_FALSE;
317 }
318
319 if (t == -1) {
320 t = (long) time(NULL);
321 }
322
323 RETURN_SUCCESS(http_send_last_modified(t));
324 }
325 /* }}} */
326
327 /* {{{ proto bool http_match_modified([int timestamp])
328 *
329 * Matches the given timestamp against the clients "If-Modified-Since" resp.
330 * "If-Unmodified-Since" HTTP headers.
331 *
332 */
333 PHP_FUNCTION(http_match_modified)
334 {
335 long t = -1;
336
337 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &t) != SUCCESS) {
338 RETURN_FALSE;
339 }
340
341 // current time if not supplied (senseless though)
342 if (t == -1) {
343 t = (long) time(NULL);
344 }
345
346 RETURN_BOOL(http_modified_match("HTTP_IF_MODIFIED_SINCE", t) || http_modified_match("HTTP_IF_UNMODIFIED_SINCE", t));
347 }
348 /* }}} */
349
350 /* {{{ proto bool http_match_etag(string etag)
351 *
352 * This matches the given ETag against the clients
353 * "If-Match" resp. "If-None-Match" HTTP headers.
354 *
355 */
356 PHP_FUNCTION(http_match_etag)
357 {
358 int etag_len;
359 char *etag;
360
361 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &etag, &etag_len) != SUCCESS) {
362 RETURN_FALSE;
363 }
364
365 RETURN_BOOL(http_etag_match("HTTP_IF_NONE_MATCH", etag) || http_etag_match("HTTP_IF_MATCH", etag));
366 }
367 /* }}} */
368
369 /* {{{ proto bool http_cache_last_modified([int timestamp_or_expires]])
370 *
371 * If timestamp_or_exires is greater than 0, it is handled as timestamp
372 * and will be sent as date of last modification. If it is 0 or omitted,
373 * the current time will be sent as Last-Modified date. If it's negative,
374 * it is handled as expiration time in seconds, which means that if the
375 * requested last modification date is not between the calculated timespan,
376 * the Last-Modified header is updated and the actual body will be sent.
377 *
378 */
379 PHP_FUNCTION(http_cache_last_modified)
380 {
381 long last_modified = 0, send_modified = 0, t;
382 zval *zlm;
383
384 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &last_modified) != SUCCESS) {
385 RETURN_FALSE;
386 }
387
388 t = (long) time(NULL);
389
390 /* 0 or omitted */
391 if (!last_modified) {
392 /* does the client have? (att: caching "forever") */
393 if (zlm = http_get_server_var("HTTP_IF_MODIFIED_SINCE")) {
394 last_modified = send_modified = http_parse_date(Z_STRVAL_P(zlm));
395 /* send current time */
396 } else {
397 send_modified = t;
398 }
399 /* negative value is supposed to be expiration time */
400 } else if (last_modified < 0) {
401 last_modified += t;
402 send_modified = t;
403 /* send supplied time explicitly */
404 } else {
405 send_modified = last_modified;
406 }
407
408 http_send_header("Cache-Control: private, must-revalidate, max-age=0");
409
410 if (http_modified_match("HTTP_IF_MODIFIED_SINCE", last_modified)) {
411 if (SUCCESS == http_send_status(304)) {
412 zend_bailout();
413 } else {
414 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not send 304 Not Modified");
415 RETURN_FALSE;
416 }
417 }
418 RETURN_SUCCESS(http_send_last_modified(send_modified));
419 }
420 /* }}} */
421
422 /* {{{ proto bool http_cache_etag([string etag])
423 *
424 * This function attempts to cache the HTTP body based on an ETag,
425 * either supplied or generated through calculation of the MD5
426 * checksum of the output (uses output buffering).
427 *
428 * If clients "If-None-Match" header matches the supplied/calculated
429 * ETag, the body is considered cached on the clients side and
430 * a "304 Not Modified" status code is issued.
431 *
432 */
433 PHP_FUNCTION(http_cache_etag)
434 {
435 char *etag;
436 int etag_len = 0;
437
438 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &etag, &etag_len) != SUCCESS) {
439 RETURN_FALSE;
440 }
441
442 php_end_ob_buffers(0 TSRMLS_CC);
443 http_send_header("Cache-Control: private, must-revalidate, max-age=0");
444
445 if (etag_len) {
446 RETURN_SUCCESS(http_send_etag(etag, etag_len));
447 }
448
449 /* if no etag is given and we didn't already
450 * start ob_etaghandler -- start it
451 */
452 if (!HTTP_G(etag_started)) {
453 php_ob_set_internal_handler(_http_ob_etaghandler, (uint) 4096, "etag output handler", 0 TSRMLS_CC);
454 HTTP_G(etag_started) = 1;
455 RETURN_BOOL(php_start_ob_buffer_named("etag output handler", (uint) 4096, 0 TSRMLS_CC));
456 }
457
458 if (http_etag_match("HTTP_IF_NONE_MATCH", etag)) {
459 if (SUCCESS == http_send_status(304)) {
460 zend_bailout();
461 } else {
462 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not send 304 Not Modified");
463 RETURN_FALSE;
464 }
465 }
466
467 }
468 /* }}} */
469
470 /* {{{ proto void http_redirect([string url[, array params[, bool session,[ bool permanent]]]])
471 *
472 * Redirect to a given url.
473 * The supplied url will be expanded with http_absolute_uri(), the params array will
474 * be treated with http_build_query() and the session identification will be appended
475 * if session is true.
476 *
477 * Depending on permanent the redirection will be issued with a permanent
478 * ("301 Moved Permanently") or a temporary ("302 Found") redirection
479 * status code.
480 *
481 * To be RFC compliant, "Redirecting to <a>URI</a>." will be displayed,
482 * if the client doesn't redirect immediatly.
483 */
484 PHP_FUNCTION(http_redirect)
485 {
486 int url_len;
487 zend_bool session = 0, permanent = 0;
488 zval *params = NULL;
489 smart_str qstr = {0};
490 char *url, *URI, LOC[HTTP_URI_MAXLEN + 9], RED[HTTP_URI_MAXLEN * 2 + 34];
491
492 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sa!/bb", &url, &url_len, &params, &session, &permanent) != SUCCESS) {
493 RETURN_FALSE;
494 }
495
496 /* append session info */
497 if (session && (PS(session_status) == php_session_active)) {
498 if (!params) {
499 MAKE_STD_ZVAL(params);
500 array_init(params);
501 }
502 if (add_assoc_string(params, PS(session_name), PS(id), 1) != SUCCESS) {
503 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not append session information");
504 }
505 }
506
507 /* treat params array with http_build_query() */
508 if (params) {
509 if (php_url_encode_hash_ex(Z_ARRVAL_P(params), &qstr, NULL,0,NULL,0,NULL,0,NULL TSRMLS_CC) != SUCCESS) {
510 if (qstr.c) {
511 efree(qstr.c);
512 }
513 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not encode query parameters");
514 RETURN_FALSE;
515 }
516 smart_str_0(&qstr);
517 }
518
519 URI = http_absolute_uri(url, NULL);
520 if (qstr.c) {
521 snprintf(LOC, HTTP_URI_MAXLEN + strlen("Location: "), "Location: %s?%s", URI, qstr.c);
522 sprintf(RED, "Redirecting to <a href=\"%s?%s\">%s?%s</a>.\n", URI, qstr.c, URI, qstr.c);
523 efree(qstr.c);
524 } else {
525 snprintf(LOC, HTTP_URI_MAXLEN + strlen("Location: "), "Location: %s", URI);
526 sprintf(RED, "Redirecting to <a href=\"%s\">%s</a>.\n", URI, URI);
527 }
528 efree(URI);
529
530 if ((SUCCESS == http_send_header(LOC)) && (SUCCESS == http_send_status((permanent ? 301 : 302)))) {
531 php_body_write(RED, strlen(RED) TSRMLS_CC);
532 RETURN_TRUE;
533 }
534 RETURN_FALSE;
535 }
536 /* }}} */
537
538 /* {{{ proto bool http_send_data(string data)
539 *
540 * Sends raw data with support for (multiple) range requests.
541 *
542 */
543 PHP_FUNCTION(http_send_data)
544 {
545 zval *zdata;
546
547 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &zdata) != SUCCESS) {
548 RETURN_FALSE;
549 }
550
551 convert_to_string_ex(&zdata);
552 http_send_header("Accept-Ranges: bytes");
553 RETURN_SUCCESS(http_send_data(zdata));
554 }
555 /* }}} */
556
557 /* {{{ proto bool http_send_file(string file)
558 *
559 * Sends a file with support for (multiple) range requests.
560 *
561 */
562 PHP_FUNCTION(http_send_file)
563 {
564 zval *zfile;
565
566 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &zfile) != SUCCESS) {
567 RETURN_FALSE;
568 }
569
570 convert_to_string_ex(&zfile);
571 http_send_header("Accept-Ranges: bytes");
572 RETURN_SUCCESS(http_send_file(zfile));
573 }
574 /* }}} */
575
576 /* {{{ proto bool http_send_stream(resource stream)
577 *
578 * Sends an already opened stream with support for (multiple) range requests.
579 *
580 */
581 PHP_FUNCTION(http_send_stream)
582 {
583 zval *zstream;
584 php_stream *file;
585
586 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zstream) != SUCCESS) {
587 RETURN_FALSE;
588 }
589
590 php_stream_from_zval(file, &zstream);
591 http_send_header("Accept-Ranges: bytes");
592 RETURN_SUCCESS(http_send_stream(file));
593 }
594 /* }}} */
595
596 /* {{{ proto bool http_content_type([string content_type = 'application/x-octetstream'])
597 *
598 * Sets the content type.
599 *
600 */
601 PHP_FUNCTION(http_content_type)
602 {
603 char *ct, *content_type;
604 int ct_len = 0;
605
606 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &ct, &ct_len) != SUCCESS) {
607 RETURN_FALSE;
608 }
609
610 if (!ct_len) {
611 RETURN_SUCCESS(http_send_header("Content-Type: application/x-octetstream"));
612 }
613
614 /* remember for multiple ranges */
615 if (HTTP_G(ctype)) {
616 efree(HTTP_G(ctype));
617 }
618 HTTP_G(ctype) = estrndup(ct, ct_len);
619
620 content_type = (char *) emalloc(strlen("Content-Type: ") + ct_len + 1);
621 sprintf(content_type, "Content-Type: %s", ct);
622
623 RETVAL_BOOL(SUCCESS == http_send_header(content_type));
624 efree(content_type);
625 }
626 /* }}} */
627
628 /* {{{ proto bool http_content_disposition(string filename[, bool inline = false])
629 *
630 * Set the Content Disposition. The Content-Disposition header is very useful
631 * if the data actually sent came from a file or something similar, that should
632 * be "saved" by the client/user (i.e. by browsers "Save as..." popup window).
633 *
634 */
635 PHP_FUNCTION(http_content_disposition)
636 {
637 char *filename, *header;
638 int f_len;
639 zend_bool send_inline = 0;
640
641 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &filename, &f_len, &send_inline) != SUCCESS) {
642 RETURN_FALSE;
643 }
644
645 if (send_inline) {
646 header = (char *) emalloc(strlen("Content-Disposition: inline; filename=\"\"") + f_len + 1);
647 sprintf(header, "Content-Disposition: inline; filename=\"%s\"", filename);
648 } else {
649 header = (char *) emalloc(strlen("Content-Disposition: attachment; filename=\"\"") + f_len + 1);
650 sprintf(header, "Content-Disposition: attachment; filename=\"%s\"", filename);
651 }
652
653 RETVAL_BOOL(SUCCESS == http_send_header(header));
654 efree(header);
655 }
656 /* }}} */
657
658 /* {{{ proto string http_chunked_decode(string encoded)
659 *
660 * This function decodes a string that was HTTP-chunked encoded.
661 * Returns false on failure.
662 */
663 PHP_FUNCTION(http_chunked_decode)
664 {
665 char *encoded = NULL, *decoded = NULL;
666 int encoded_len = 0, decoded_len = 0;
667
668 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &encoded, &encoded_len) != SUCCESS) {
669 RETURN_FALSE;
670 }
671
672 if (SUCCESS == http_chunked_decode(encoded, encoded_len, &decoded, &decoded_len)) {
673 RETURN_STRINGL(decoded, decoded_len, 0);
674 } else {
675 RETURN_FALSE;
676 }
677 }
678 /* }}} */
679
680 /* {{{ proto array http_split_response(string http_response)
681 *
682 * This function splits an HTTP response into an array with headers and the
683 * content body. The returned array may look simliar to the following example:
684 *
685 * <pre>
686 * <?php
687 * array(
688 * 0 => array(
689 * 'Status' => '200 Ok',
690 * 'Content-Type' => 'text/plain',
691 * 'Content-Language' => 'en-US'
692 * ),
693 * 1 => "Hello World!"
694 * );
695 * ?>
696 * </pre>
697 */
698 PHP_FUNCTION(http_split_response)
699 {
700 zval *zresponse, *zbody, *zheaders;
701
702 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &zresponse) != SUCCESS) {
703 RETURN_FALSE;
704 }
705
706 convert_to_string_ex(&zresponse);
707
708 MAKE_STD_ZVAL(zbody);
709 MAKE_STD_ZVAL(zheaders);
710 array_init(zheaders);
711
712 if (SUCCESS != http_split_response(zresponse, zheaders, zbody)) {
713 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not parse HTTP response");
714 RETURN_FALSE;
715 }
716
717 array_init(return_value);
718 add_index_zval(return_value, 0, zheaders);
719 add_index_zval(return_value, 1, zbody);
720 }
721 /* }}} */
722
723 /* {{{ proto array http_parse_headers(string header)
724 *
725 */
726 PHP_FUNCTION(http_parse_headers)
727 {
728 char *header, *rnrn;
729 int header_len;
730
731 if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &header, &header_len)) {
732 RETURN_FALSE;
733 }
734
735 array_init(return_value);
736
737 if (rnrn = strstr(header, HTTP_CRLF HTTP_CRLF)) {
738 header_len = rnrn - header + 2;
739 }
740 if (SUCCESS != http_parse_headers(header, header_len, return_value)) {
741 php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not parse HTTP header");
742 zval_dtor(return_value);
743 RETURN_FALSE;
744 }
745 }
746 /* }}}*/
747
748 /* {{{ proto array http_get_request_headers(void)
749 *
750 */
751 PHP_FUNCTION(http_get_request_headers)
752 {
753 if (ZEND_NUM_ARGS()) {
754 WRONG_PARAM_COUNT;
755 }
756
757 array_init(return_value);
758 http_get_request_headers(return_value);
759 }
760 /* }}} */
761
762 /* {{{ HAVE_CURL */
763 #ifdef HTTP_HAVE_CURL
764
765 /* {{{ proto string http_get(string url[, array options[, array &info]])
766 *
767 * Performs an HTTP GET request on the supplied url.
768 *
769 * The second parameter is expected to be an associative
770 * array where the following keys will be recognized:
771 * <pre>
772 * - redirect: int, whether and how many redirects to follow
773 * - unrestrictedauth: bool, whether to continue sending credentials on
774 * redirects to a different host
775 * - proxyhost: string, proxy host in "host[:port]" format
776 * - proxyport: int, use another proxy port as specified in proxyhost
777 * - proxyauth: string, proxy credentials in "user:pass" format
778 * - proxyauthtype: int, HTTP_AUTH_BASIC and/or HTTP_AUTH_NTLM
779 * - httpauth: string, http credentials in "user:pass" format
780 * - httpauthtype: int, HTTP_AUTH_BASIC, DIGEST and/or NTLM
781 * - compress: bool, whether to allow gzip/deflate content encoding
782 * (defaults to true)
783 * - port: int, use another port as specified in the url
784 * - referer: string, the referer to sends
785 * - useragent: string, the user agent to send
786 * (defaults to PECL::HTTP/version (PHP/version)))
787 * - headers: array, list of custom headers as associative array
788 * like array("header" => "value")
789 * - cookies: array, list of cookies as associative array
790 * like array("cookie" => "value")
791 * - cookiestore: string, path to a file where cookies are/will be stored
792 * </pre>
793 *
794 * The optional third parameter will be filled with some additional information
795 * in form af an associative array, if supplied, like the following example:
796 * <pre>
797 * <?php
798 * array (
799 * 'effective_url' => 'http://localhost',
800 * 'response_code' => 403,
801 * 'total_time' => 0.017,
802 * 'namelookup_time' => 0.013,
803 * 'connect_time' => 0.014,
804 * 'pretransfer_time' => 0.014,
805 * 'size_upload' => 0,
806 * 'size_download' => 202,
807 * 'speed_download' => 11882,
808 * 'speed_upload' => 0,
809 * 'header_size' => 145,
810 * 'request_size' => 62,
811 * 'ssl_verifyresult' => 0,
812 * 'filetime' => -1,
813 * 'content_length_download' => 202,
814 * 'content_length_upload' => 0,
815 * 'starttransfer_time' => 0.017,
816 * 'content_type' => 'text/html; charset=iso-8859-1',
817 * 'redirect_time' => 0,
818 * 'redirect_count' => 0,
819 * 'private' => '',
820 * 'http_connectcode' => 0,
821 * 'httpauth_avail' => 0,
822 * 'proxyauth_avail' => 0,
823 * )
824 * ?>
825 * </pre>
826 */
827 PHP_FUNCTION(http_get)
828 {
829 char *URL, *data = NULL;
830 size_t data_len = 0;
831 int URL_len;
832 zval *options = NULL, *info = NULL;
833
834 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|a/!z", &URL, &URL_len, &options, &info) != SUCCESS) {
835 RETURN_FALSE;
836 }
837
838 if (info) {
839 zval_dtor(info);
840 array_init(info);
841 }
842
843 if (SUCCESS == http_get(URL, HASH_ORNULL(options), HASH_ORNULL(info), &data, &data_len)) {
844 RETURN_STRINGL(data, data_len, 0);
845 } else {
846 RETURN_FALSE;
847 }
848 }
849 /* }}} */
850
851 /* {{{ proto string http_head(string url[, array options[, array &info]])
852 *
853 * Performs an HTTP HEAD request on the suppied url.
854 * Returns the HTTP response as string.
855 * See http_get() for a full list of available options.
856 */
857 PHP_FUNCTION(http_head)
858 {
859 char *URL, *data = NULL;
860 size_t data_len = 0;
861 int URL_len;
862 zval *options = NULL, *info = NULL;
863
864 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|a/!z", &URL, &URL_len, &options, &info) != SUCCESS) {
865 RETURN_FALSE;
866 }
867
868 if (info) {
869 zval_dtor(info);
870 array_init(info);
871 }
872
873 if (SUCCESS == http_head(URL, HASH_ORNULL(options), HASH_ORNULL(info), &data, &data_len)) {
874 RETURN_STRINGL(data, data_len, 0);
875 } else {
876 RETURN_FALSE;
877 }
878 }
879 /* }}} */
880
881 /* {{{ proto string http_post_data(string url, string data[, array options[, &info]])
882 *
883 * Performs an HTTP POST request, posting data.
884 * Returns the HTTP response as string.
885 * See http_get() for a full list of available options.
886 */
887 PHP_FUNCTION(http_post_data)
888 {
889 char *URL, *postdata, *data = NULL;
890 size_t data_len = 0;
891 int postdata_len, URL_len;
892 zval *options = NULL, *info = NULL;
893
894 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|a/!z", &URL, &URL_len, &postdata, &postdata_len, &options, &info) != SUCCESS) {
895 RETURN_FALSE;
896 }
897
898 if (info) {
899 zval_dtor(info);
900 array_init(info);
901 }
902
903 if (SUCCESS == http_post_data(URL, postdata, (size_t) postdata_len, HASH_ORNULL(options), HASH_ORNULL(info), &data, &data_len)) {
904 RETURN_STRINGL(data, data_len, 0);
905 } else {
906 RETURN_FALSE;
907 }
908 }
909 /* }}} */
910
911 /* {{{ proto string http_post_array(string url, array data[, array options[, array &info]])
912 *
913 * Performs an HTTP POST request, posting www-form-urlencoded array data.
914 * Returns the HTTP response as string.
915 * See http_get() for a full list of available options.
916 */
917 PHP_FUNCTION(http_post_array)
918 {
919 char *URL, *data = NULL;
920 size_t data_len = 0;
921 int URL_len;
922 zval *options = NULL, *info = NULL, *postdata;
923
924 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sa|a/!z", &URL, &URL_len, &postdata, &options, &info) != SUCCESS) {
925 RETURN_FALSE;
926 }
927
928 if (info) {
929 zval_dtor(info);
930 array_init(info);
931 }
932
933 if (SUCCESS == http_post_array(URL, Z_ARRVAL_P(postdata), HASH_ORNULL(options), HASH_ORNULL(info), &data, &data_len)) {
934 RETURN_STRINGL(data, data_len, 0);
935 } else {
936 RETURN_FALSE;
937 }
938 }
939 /* }}} */
940
941 #endif
942 /* }}} HAVE_CURL */
943
944
945 /* {{{ proto bool http_auth_basic(string user, string pass[, string realm = "Restricted"])
946 *
947 * Example:
948 * <pre>
949 * <?php
950 * if (!http_auth_basic('mike', 's3c|r3t')) {
951 * die('<h1>Authorization failed!</h1>');
952 * }
953 * ?>
954 * </pre>
955 */
956 PHP_FUNCTION(http_auth_basic)
957 {
958 char *realm = NULL, *user, *pass, *suser, *spass;
959 int r_len, u_len, p_len;
960
961 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|s", &user, &u_len, &pass, &p_len, &realm, &r_len) != SUCCESS) {
962 RETURN_FALSE;
963 }
964
965 if (!realm) {
966 realm = "Restricted";
967 }
968
969 if (SUCCESS != http_auth_credentials(&suser, &spass)) {
970 http_auth_header("Basic", realm);
971 RETURN_FALSE;
972 }
973
974 if (strcasecmp(suser, user)) {
975 http_auth_header("Basic", realm);
976 RETURN_FALSE;
977 }
978
979 if (strcmp(spass, pass)) {
980 http_auth_header("Basic", realm);
981 RETURN_FALSE;
982 }
983
984 RETURN_TRUE;
985 }
986 /* }}} */
987
988 /* {{{ proto bool http_auth_basic_cb(mixed callback[, string realm = "Restricted"])
989 *
990 * Example:
991 * <pre>
992 * <?php
993 * function auth_cb($user, $pass)
994 * {
995 * global $db;
996 * $query = 'SELECT pass FROM users WHERE user='. $db->quoteSmart($user);
997 * if (strlen($realpass = $db->getOne($query)) {
998 * return $pass === $realpass;
999 * }
1000 * return false;
1001 * }
1002 *
1003 * if (!http_auth_basic_cb('auth_cb')) {
1004 * die('<h1>Authorization failed</h1>');
1005 * }
1006 * ?>
1007 * </pre>
1008 */
1009 PHP_FUNCTION(http_auth_basic_cb)
1010 {
1011 zval *cb;
1012 char *realm = NULL, *user, *pass;
1013 int r_len;
1014
1015 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|s", &cb, &realm, &r_len) != SUCCESS) {
1016 RETURN_FALSE;
1017 }
1018
1019 if (!realm) {
1020 realm = "Restricted";
1021 }
1022
1023 if (SUCCESS != http_auth_credentials(&user, &pass)) {
1024 http_auth_header("Basic", realm);
1025 RETURN_FALSE;
1026 }
1027 {
1028 zval *zparams[2] = {NULL, NULL}, retval;
1029 int result = 0;
1030
1031 MAKE_STD_ZVAL(zparams[0]);
1032 MAKE_STD_ZVAL(zparams[1]);
1033 ZVAL_STRING(zparams[0], user, 0);
1034 ZVAL_STRING(zparams[1], pass, 0);
1035
1036 if (SUCCESS == call_user_function(EG(function_table), NULL, cb,
1037 &retval, 2, zparams TSRMLS_CC)) {
1038 result = Z_LVAL(retval);
1039 }
1040
1041 efree(user);
1042 efree(pass);
1043 efree(zparams[0]);
1044 efree(zparams[1]);
1045
1046 if (!result) {
1047 http_auth_header("Basic", realm);
1048 }
1049
1050 RETURN_BOOL(result);
1051 }
1052 }
1053 /* }}}*/
1054
1055
1056 /* {{{ php_http_init_globals(zend_http_globals *) */
1057 static void php_http_init_globals(zend_http_globals *http_globals)
1058 {
1059 http_globals->etag_started = 0;
1060 http_globals->ctype = NULL;
1061 http_globals->etag = NULL;
1062 http_globals->lmod = 0;
1063 #ifdef HTTP_HAVE_CURL
1064 http_globals->curlbuf.body.data = NULL;
1065 http_globals->curlbuf.body.used = 0;
1066 http_globals->curlbuf.body.free = 0;
1067 http_globals->curlbuf.hdrs.data = NULL;
1068 http_globals->curlbuf.hdrs.used = 0;
1069 http_globals->curlbuf.hdrs.free = 0;
1070 #endif
1071 http_globals->allowed_methods = NULL;
1072 }
1073 /* }}} */
1074
1075 /* {{{ static inline STATUS http_check_allowed_methods(char *, int) */
1076 #define http_check_allowed_methods(m, l) _http_check_allowed_methods((m), (l) TSRMLS_CC)
1077 static inline void _http_check_allowed_methods(char *methods, int length TSRMLS_DC)
1078 {
1079 if (length && SG(request_info).request_method && (!strstr(methods, SG(request_info).request_method))) {
1080 char *allow_header = emalloc(length + sizeof("Allow: "));
1081 sprintf(allow_header, "Allow: %s", methods);
1082 http_send_header(allow_header);
1083 efree(allow_header);
1084 http_send_status(405);
1085 zend_bailout();
1086 }
1087 }
1088 /* }}} */
1089
1090 /* {{{ PHP_INI */
1091 PHP_INI_MH(update_allowed_methods)
1092 {
1093 http_check_allowed_methods(new_value, new_value_length);
1094 return OnUpdateString(entry, new_value, new_value_length, mh_arg1, mh_arg2, mh_arg3, stage TSRMLS_CC);
1095 }
1096
1097 PHP_INI_BEGIN()
1098 STD_PHP_INI_ENTRY("http.allowed_methods", "OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT", PHP_INI_ALL, update_allowed_methods, allowed_methods, zend_http_globals, http_globals)
1099 PHP_INI_END()
1100 /* }}} */
1101
1102 /* {{{ PHP_MINIT_FUNCTION */
1103 PHP_MINIT_FUNCTION(http)
1104 {
1105 ZEND_INIT_MODULE_GLOBALS(http, php_http_init_globals, NULL);
1106 REGISTER_INI_ENTRIES();
1107 #ifdef HTTP_HAVE_CURL
1108 REGISTER_LONG_CONSTANT("HTTP_AUTH_BASIC", CURLAUTH_BASIC, CONST_CS | CONST_PERSISTENT);
1109 REGISTER_LONG_CONSTANT("HTTP_AUTH_DIGEST", CURLAUTH_DIGEST, CONST_CS | CONST_PERSISTENT);
1110 REGISTER_LONG_CONSTANT("HTTP_AUTH_NTLM", CURLAUTH_NTLM, CONST_CS | CONST_PERSISTENT);
1111 #endif
1112 return SUCCESS;
1113 }
1114 /* }}} */
1115
1116 /* {{{ PHP_MSHUTDOWN_FUNCTION */
1117 PHP_MSHUTDOWN_FUNCTION(http)
1118 {
1119 UNREGISTER_INI_ENTRIES();
1120 return SUCCESS;
1121 }
1122 /* }}} */
1123
1124 /* {{{ PHP_RINIT_FUNCTION */
1125 PHP_RINIT_FUNCTION(http)
1126 {
1127 char *allowed_methods = INI_STR("http.allowed_methods");
1128 http_check_allowed_methods(allowed_methods, strlen(allowed_methods));
1129 return SUCCESS;
1130 }
1131 /* }}} */
1132
1133 /* {{{ PHP_RSHUTDOWN_FUNCTION */
1134 PHP_RSHUTDOWN_FUNCTION(http)
1135 {
1136 HTTP_G(etag_started) = 0;
1137 HTTP_G(lmod) = 0;
1138
1139 if (HTTP_G(etag)) {
1140 efree(HTTP_G(etag));
1141 HTTP_G(etag) = NULL;
1142 }
1143
1144 if (HTTP_G(ctype)) {
1145 efree(HTTP_G(ctype));
1146 HTTP_G(ctype) = NULL;
1147 }
1148 #ifdef HTTP_HAVE_CURL
1149 if (HTTP_G(curlbuf).body.data) {
1150 efree(HTTP_G(curlbuf).body.data);
1151 HTTP_G(curlbuf).body.data = NULL;
1152 }
1153 if (HTTP_G(curlbuf).hdrs.data) {
1154 efree(HTTP_G(curlbuf).hdrs.data);
1155 HTTP_G(curlbuf).hdrs.data = NULL;
1156 }
1157 #endif
1158 return SUCCESS;
1159 }
1160 /* }}} */
1161
1162 /* {{{ PHP_MINFO_FUNCTION */
1163 PHP_MINFO_FUNCTION(http)
1164 {
1165 php_info_print_table_start();
1166 php_info_print_table_header(2, "Extended HTTP support", "enabled");
1167 php_info_print_table_row(2, "Version:", PHP_EXT_HTTP_VERSION);
1168 php_info_print_table_row(2, "cURL convenience functions:",
1169 #ifdef HTTP_HAVE_CURL
1170 "enabled"
1171 #else
1172 "disabled"
1173 #endif
1174 );
1175 php_info_print_table_end();
1176
1177 DISPLAY_INI_ENTRIES();
1178 }
1179 /* }}} */
1180
1181 /*
1182 * Local variables:
1183 * tab-width: 4
1184 * c-basic-offset: 4
1185 * End:
1186 * vim600: noet sw=4 ts=4 fdm=marker
1187 * vim<600: noet sw=4 ts=4
1188 */
1189