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