<?php
Header("Cache-Control: no-cache");
Header("Pragma: no-cache");
Header("Expires: Sat, Jan 01 2000 01:01:01 GMT");

function myglob($pat)
{
    if (function_exists("glob"))
        return glob($pat);
    $dir = dirname($pat);
    $slashpos = strrpos($pat, '/');
    if ($slashpos == 0)
        $reg = $pat;
    else
        $reg = substr($pat, $slashpos+1);
    $reg = quotemeta($reg);
    $reg = ereg_replace("\\\\\*", ".*", $reg);
    $reg = ereg_replace("\\\\\?", ".", $reg);
    $reg = "^$reg$";
    $list = array();
    if ($handle = opendir($dir))
    {
        while (false !== ($file = readdir($handle))) 
        { 
            if (ereg($reg, $file))
                $list[] = "$dir/$file";
        }
    }
    return $list;
}

function content()
{
    global $writable, $cfgerror;
    if (!$writable)
    {
        // Just for this error, make the screen as small as possible
        print "<table width=\"100\"><tr><td>";  
        content_start();
        header_start();
        header_left();
        print PROG_NAME . ":&nbsp;" . str_replace(" ", "&nbsp;", $cfgerror);
        header_left_right_end();
        header_end();
        content_end();
        print "</td></tr></table>";
        return;
    }
    global $PHP_SELF;
    content_start();
    header_start();
    header_left();
    echo PROG_NAME . ":&nbsp;Configure";
    header_left_right_end();
    print "<form action=\"$PHP_SELF\" method=\"post\">";
    header_end();
    body_compose_start();
    title_data('colspan="2"');
    ?>
    <div style="font-size: larger;">
    This is the AeroMail Configuration Page. To set up AeroMail for your 
    system, proceed as follows:
    <ol>
    <li>If you are installing AeroMail for the first time, either make the
    AeroMail directory writable by the web server's user, or create an empty,
    writable <tt>config.inc.php</tt>.
    <li>If you are upgrading from a previous version of AeroMail:
    <ul>
        <li>Copy the
        file <tt>config.inc.php</tt> or <tt>config.inc</tt> from your old 
        installation to AeroMail's directory. 
        <li>If the file is called <tt>config.inc</tt>, rename it to
        <tt>config.inc.php</tt>. 
        <li><b>Make sure you have a backup of <tt>config.inc.php</tt>.</b>
        <li>Make sure <tt>config.inc.php</tt> is writable by the web server's user.
    </ul>
    <li>Fill in the form below.
    <li>When you press the 'Configure' button, a new <tt>config.inc.php</tt>
    will be written. The changes will be reflected in the form immediately; if
    you made changes e.g. to the colours, this page will be coloured
    differently.
    <li>When you are done making changes, choose 'Go to AeroMail'.
    <li><b>If all is working properly, make sure you make the file 
    <tt>config.inc.php</tt> "read-only".</b>
    <li>For extra safety, remove <tt><?php print basename($PHP_SELF); ?></tt>
    from the AeroMail directory on your web server.
    </ol>
    </div>
    <h4 align="center"><a class="intf" href="index.php">Go to AeroMail</a></h4>
    <br>
    <?php
    title_data_end();

    $inline = 0;
    $h = 0;
    $f = fopen("config.inc.php.dist", "r");
    while (!feof($f))
    {
        $line = fgets($f, 1024);
        $line = chop($line);
        if (ereg("^//([-[:space:]]|$)", $line) or ereg("^[[:space:]]*$", $line))
        {
            if (!$inline)
            {
                title_start();
                title_data('colspan="2"');
                $inline = 1;
            }
            if (ereg("^[[:space:]]*$", $line))
            {
                print "<br>";
                continue;
            }
            $p = substr($line, 2);
            if (ereg("^[[:space:]]*$", $p))
            {
                print "<br><br>";
                continue;
            }
            if (ereg("^----*$", $p))
            {
                if (!$h)
                {
                    title_data_end();
                    title_end();
                    title_start();
                    title_left('colspan="2"');
                }
                else
                {
                    title_left_end();
                    title_end();
                    title_start();
                    title_data('colspan="2"');
                }
                
                $h = !$h;
            }
            elseif (ereg("=POSSIBLE_VALUES[[:blank:]]*(.*)[[:blank:]]*$", $p, $regs))
            {
                    $nextcontrol = $regs[1];
            }
            else
                print $p . "<br>";
        }
        elseif (ereg("define\('([^']+)', (.*));", $line, $regs))
        {
            if ($inline)
            {
                title_data_end();
                title_end();
                $inline = 0;
            }
            title_start();
            title_left('width="1%"');
            $var = $regs[1];
            $default = ereg_replace("^[[:blank:]]*\"(.*)\"[[:blank:]]*$", "\\1", $regs[2]);
            // Convert booleans from config.inc.php.dist
            if ($nextcontrol == "bool")
            {
                if ($default === "false")
                    $default = false;
                else
                    $default = true;
            }
            $v = $default;
            // First see if we have a set variable, from config.inc.php < 2.0
            // If we read an old config, we have forced some constants to 
            // make this page display, so we have to look at variables first.
            global $$var;
            if (isset($$var)) // Variable,
            {
                $current = $$var;
                // Redo this value, as 1.x used different logic
                if ($var == "SENT_MAIL")
                {
                    if (!is_string($current))
                        $current = "";
                }
                $v = $current;
            }
            // Now look at defined constant, from config.inc.php >= 2.0
            elseif (defined($var))
            {
                $current = constant($var);
                $v = $current;
            }
            else
                unset($current);
            
            print "<small>$regs[1]:</small>";
            title_left_end();
            title_data();
                
            if ($nextcontrol == "shortstring")
            {
                print "<input type=\"text\" size=\"30\" name=\"$regs[1]\" value=\"$v\">";
            }
            elseif ($nextcontrol == "string")
            {
                print "<input type=\"text\" size=\"80\" name=\"$regs[1]\" value=\"$v\">";
            }
            elseif ($nextcontrol == "longstring")
            {
                print "<textarea cols=\"60\" rows=\"2\" name=\"$regs[1]\">$v</textarea>";
            }
            elseif ($nextcontrol == "number")
            {
                print "<input type=\"text\" size=\"10\" name=\"$regs[1]\" value=\"$v\">";
            }
            elseif ($nextcontrol == "bool")
            {
                if ($v) // So old values of 1 are also accepted
                    $c = 'checked="checked"';
                else
                    $c = "";
                print "<input type=\"checkbox\" name=\"$regs[1]\" $c>";
            }
            elseif ($arr = explode(',', $nextcontrol) and count($arr) > 1)
            {
                print "<select name=\"$regs[1]\">";
                foreach ($arr as $opt)
                {
                    $opt = trim($opt);
                    print "<option value=\"$opt\" ";
                    if ($v == $opt) 
                        print 'selected="selected"';
                    print ">$opt</option>";
                }
                print "</select>";
            }
            elseif (ereg("^[[:blank:]]*<(.*)>[[:blank:]]*$", $nextcontrol, $r))
            {
                $v = ereg_replace("^[[:blank:]]*\"(.*)\"[[:blank:]]*$", "\\1", $v);
                
                $prefix = str_replace("\\", "/", getcwd()) . "/";
                $filepat = $prefix . $r[1];
                $arr = myglob($filepat);
                print "<select name=\"$regs[1]\">";
                foreach ($arr as $opt)
                {
                    $opt = substr($opt, strlen($prefix));
                    print "<option value=\"$opt\" ";
                    if ($v == $opt
                            // Cater for installations < 2.40
                            || "$v.php" == $opt) 
                        print 'selected="selected"';
                    print ">$opt</option>";
                }
                print "</select>";
            }
            else
                print "ERROR: Unknown control $nextcontrol";
            title_data_end();
            title_end();
        }
    }
    body_end();

    header_start();
    header_right();
    ?>
    <input type="submit" name="submit" value="Configure">
    </form>
    <?php

    header_left_right_end();
    header_end();
    content_end();
}

/* MAIN */
// First check whether the config file is writable.
$writable = true;
if (file_exists('config.inc.php'))
{
    $writable = is_writable("config.inc.php");
    if (!$writable)
        $cfgerror = "Configuration not allowed.";
}
else
{
    $writable = is_writable(".");
    if (!$writable)
        $cfgerror = "Configuration not possible (cannot create <tt>config.inc.php</tt>).";
}

// If the user submitted the form, rewrite the config file
if ($submit and $writable)
{
    $content = "";
    $f = fopen("config.inc.php.dist", "r");
    while (!feof($f))
    {
        $line = fgets($f, 1024);
        if (!$line)
            continue;
        $line = chop($line);
        $p = substr($line, 2);
        if (ereg("=POSSIBLE_VALUES[[:blank:]]*(.*)[[:blank:]]*$", $p, $regs))
        {
            $nextcontrol = $regs[1];
        }
        elseif (ereg("define\('([^']+)', (.*));", $line, $regs))
        {
            $var = $regs[1];
            $val = $$var;
            if (($nextcontrol == "shortstring")
                or ($nextcontrol == "string")
                or ($nextcontrol == "longstring"))

            {
                $line="define('$var', \"$val\");";
            }
            elseif ($nextcontrol == "number")
            {
                $line="define('$var', $val);";
            }
            elseif ($nextcontrol == "bool")
            {
                if ($val)
                    $line="define('$var', true);";
                else
                    $line="define('$var', false);";
            }
            elseif ($arr = explode(',', $nextcontrol) and count($arr) > 1)
            {
                $line="define('$var', \"$val\");";
            }
            elseif (ereg("^[[:blank:]]*<(.*)>[[:blank:]]*$", $nextcontrol, $r))
            {
                $line="define('$var', \"$val\");";
            }
            else
                print "ERROR: Unknown control $nextcontrol\n";
        }
        $content .= "$line\n";
    }
    fclose($f);
    $f = fopen("config.inc.php", "wb");
    if ($f)
    {
        fwrite($f, $content);
        fclose($f);
    }
}
if (file_exists('config.inc.php') and filesize('config.inc.php') > 5)
{
    $err = error_reporting(E_ERROR);
    include("config.inc.php");
    error_reporting($err);
}
// set the minimal necessary to display the page
if (!defined('PROG_NAME'))
    define('PROG_NAME', "AeroMail");
if (!defined('HTML_TEMPLATE'))
    define('HTML_TEMPLATE', "themes/default.template.inc.php");
if (!defined('THEME_FILE'))
    define('THEME_FILE', "themes/default.theme.inc.php");
if (!defined('LANGUAGE_FILE'))
    define('LANGUAGE_FILE', "lang/en.lang.inc.php");
// Cater for installations < 2.40
if (ereg("\.inc$", THEME_FILE))
    include(THEME_FILE . ".php");
else
    include(THEME_FILE);
if (ereg("\.inc$", LANGUAGE_FILE))
    include(LANGUAGE_FILE . ".php");
else
    include(LANGUAGE_FILE);
include('layout.inc.php');
define('VERSION', "AeroMail");

if (ereg("\.inc$", HTML_TEMPLATE))
    include(HTML_TEMPLATE . ".php");
else
    include(HTML_TEMPLATE);

?>
