+/* {{{ char *http_guess_content_type(char *magic_file, long magic_mode, void *data, size_t size, http_send_mode mode) */
+PHP_HTTP_API char *_http_guess_content_type(const char *magicfile, long magicmode, void *data_ptr, size_t data_len, http_send_mode data_mode TSRMLS_DC)
+{
+ char *ct = NULL;
+
+#ifdef HTTP_HAVE_MAGIC
+ struct magic_set *magic;
+
+ HTTP_CHECK_OPEN_BASEDIR(magicfile, return NULL);
+
+ /* magic_load() fails if MAGIC_MIME is set because it
+ cowardly adds .mime to the file name */
+ magic = magic_open(magicmode &~ MAGIC_MIME);
+
+ if (!magic) {
+ http_error_ex(HE_WARNING, HTTP_E_INVALID_PARAM, "Invalid magic mode: %ld", magicmode);
+ } else if (-1 == magic_load(magic, magicfile)) {
+ http_error_ex(HE_WARNING, HTTP_E_RUNTIME, "Failed to load magic database '%s' (%s)", magicfile, magic_error(magic));
+ } else {
+ const char *ctype = NULL;
+
+ magic_setflags(magic, magicmode);
+
+ switch (data_mode)
+ {
+ case SEND_RSRC:
+ {
+ char *buffer;
+ size_t b_len;
+
+ b_len = php_stream_copy_to_mem(data_ptr, &buffer, 65536, 0);
+ ctype = magic_buffer(magic, buffer, b_len);
+ efree(buffer);
+ }
+ break;
+
+ case SEND_DATA:
+ ctype = magic_buffer(magic, data_ptr, data_len);
+ break;
+
+ default:
+ HTTP_CHECK_OPEN_BASEDIR(data_ptr, magic_close(magic); return NULL);
+ ctype = magic_file(magic, data_ptr);
+ break;
+ }
+
+ if (ctype) {
+ ct = estrdup(ctype);
+ } else {
+ http_error_ex(HE_WARNING, HTTP_E_RUNTIME, "Failed to guess Content-Type: %s", magic_error(magic));
+ }
+ }
+ if (magic) {
+ magic_close(magic);
+ }
+#else
+ http_error(HE_WARNING, HTTP_E_RUNTIME, "Cannot guess Content-Type; libmagic not available");
+#endif
+
+ return ct;
+}
+/* }}} */
+