/* @(#)form.c 1.4 95/09/16 */

/*
 * Copyright (c) 1994, 1995 by Wayne C. Gramlich.  All rights reserved.
 *
 * Permission to use, copy, modify, distribute, and sell this software
 * for any purpose is hereby granted without fee provided that the above
 * copyright notice and this permission are retained.  The author makes
 * no representations about the suitability of this software for any purpose.
 * It is provided "as is" without express or implied warranty.
 */

/* LINTLIBRARY */

#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#include "chr_extern.h"
#include "error_extern.h"
#include "str_extern.h"
#include "text_extern.h"

static Str get_env_var(char *);

/*
 * form_post_read(errors)
 *	This routine will return the text that is sent over via a
 *	form post method.  If any errors occur, {errors} is updated
 *	to explain why and (Text)0 is returned.
 */
Text
form_post_read(
    Errors errors)
{
    Str content_length;
    Str content_type;
    Str message;
    Str request_method;
    unsigned size;
    Text submit_text;

    message = (Str)0;
    request_method = get_env_var("REQUEST_METHOD");
    assert(request_method != (Str)0);
    if (!str_equal(request_method, (Str)"POST")) {
	message =  str_printf("Please use `POST' METHOD (not `%s') "
	  "to access this script.\n", request_method);
    }
    content_type = get_env_var("CONTENT_TYPE");
    assert(content_type != (Str)0);
    if (!str_equal(content_type, (Str)"application/x-www-form-urlencoded")) {
	message = str_printf("Content type error (is `%s')!\n", content_type);
    }
    content_length = get_env_var("CONTENT_LENGTH");
    assert(content_length != (Str)0);
    if (message != (Str)0) {
	errors_append(errors, message);
	return text_create((Str)"", 0);
    }
    size = atoi((char *)content_length);
    submit_text = text_read_exact(stdin, size, errors);
    return submit_text;
}

/*
 * form_get_value(text, name, errors)
 *	This routine will return the value associated with form field
 *	name {name} from {text}.  Any errors are reported on {errors}
 *	and (Str)"" is returned.
 */
Str
form_get_value(
    Text text,
    Str name,
    Errors errors)
{
    Str n;
    Str value;

    n = text_get_word(text, '=');
    if (!str_equal(n, name)) {
	errors_append(errors, (Str)"Form parsing errors!");
	return (Str)"";
    }
    value = text_get_word(text, '&');
    return value;
}

/*
 * get_env_var(name)
 *	This routine will get the environment variable named {name} or
 *	assert.
 */
static Str
get_env_var(
    char *name)
{
    Str value;

    value = (Str)getenv(name);
    assert(value != (Str)0);
    return value;
}

