<?php
/* $Id: index.php,v 1.147 2003/12/10 14:21:18 k-fish Exp $ */

$myEnv['module'] = "settings";
$myEnv['output'] = "html";
$myEnv['stdsmenu'] = false;
$myEnv['translation'] = true;

require_once("../../config.inc.php");
require_once(INCLUDEPATH . "container.inc.php");

// switch off the default strip_tags modifier, this is not
// the best solution.
$smarty->default_modifiers = array();

/* SAVE POSTED SETTINGS */
if (isset($_POST["savesettings"]) && isset($_POST["module"]) && isset($_POST["option"])) {

    /* this was added last, so comments are below */
    unset($settings);
    include(ROOTPATH."/modules/".$_SESSION["MGW"]->modules[$_POST["module"]]["modulename"]."/inc/settings.inc.php");
    if (isset($settings[$_POST["module"]][$_POST["option"]]) and is_array($settings[$_POST["module"]][$_POST["option"]])) {
        $options = $settings[$_POST["module"]][$_POST["option"]];
        
        /* special case for usersettings, uses getUserData(columnname) to retrieve data */
        if (in_array("usersettings", $options) and isset($options["usersettings"]) and $options["usersettings"]) { 
            $pw1 = $_POST["pw1"][0];
            $pw2 = $_POST["pw2"][0];
            if (isset($pw2) && $pw1 == $pw2 && !strlen($pw1) < 6){
                $md5pw = "pw='".md5($pw1)."',";
            } else {
                $md5pw = "";
            }

	    $birthdayts = $_POST["birthdayYear"]."-".$_POST["birthdayMonth"]."-".$_POST["birthdayDay"]." 00:00:00";
	    $birthday = $conn->DBTimeStamp($birthdayts);
        
            /* do we need a redirect (was the language changed?) */
            if (isset($_SESSION["MGW"]->language) && $_SESSION["MGW"]->language != $_POST["lang"][0]) $redirect = true;

            $sql = "UPDATE mgw_users SET lastname=".$conn->QMagic($_POST["lastname"][0]).", firstname=".$conn->QMagic($_POST["firstname"][0]).", birthday=$birthday, sex=".$conn->QMagic($_POST["sex"][0]).", privstreet=".$conn->QMagic($_POST["privstreet"][0]).", privcode=".$conn->QMagic($_POST["privcode"][0]).", privcity=".$conn->QMagic($_POST["privcity"][0]).", privregio=".$conn->QMagic($_POST["privregio"][0]).", privcountry=".$conn->QMagic($_POST["privcountry"][0]).", privmobil=".$conn->QMagic($_POST["privmobil"][0]).", privtel=".$conn->QMagic($_POST["privtel"][0]).", privemail=".$conn->QMagic($_POST["privemail"][0]).", privhobby=".$conn->QMagic($_POST["privhobby"][0]).", mobil=".$conn->QMagic($_POST["mobil"][0]).", telephone=".$conn->QMagic($_POST["telephone"][0]).", email=".$conn->QMagic($_POST["email"][0]).", $md5pw lang=".$conn->QMagic($_POST["lang"][0]).", lu_user=".$_SESSION["MGW"]->userid.", lu_date=NOW() WHERE id=".$_SESSION["MGW"]->userid;
            if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
            $_SESSION["MGW"]->spkz = $_POST["lang"][0];
            $_SESSION["MGW"]->language = $_POST["lang"][0];
        
            $sql = "SELECT charset FROM mgw_languages WHERE langcode=". $conn->QMagic($_POST["lang"][0]);
            if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
            $row = $res->FetchRow();
            $_SESSION["MGW"]->charset = $row['charset'];
        } else { 
            /* for each group of options, save the settings */
            foreach ($options as $key => $option) {
                if ($key=="admin" or $key=="title" or (isset($option["hide"]) && $option["hide"])) continue;
                
                /* no data check */
                if (!isset($_POST[$key])) {
                    $data=array();
                } else {
                    $data=$_POST[$key];
                }

                /* handle files differently */
                if ($option["method"]=="file") {
                    if($_FILES[$key]['name'] != ""){
                        $tmp = $_SESSION["MGW"]->modules[$_POST["module"]]["cache"];
                        foreach ($tmp as $dataDir) {
                        	if ($dataDir=="data") break;
                        }
                        if (isset($dataDir)) {
                            $dataDir = ROOTPATH."/modules/".$_SESSION["MGW"]->modules[$_POST["module"]]["modulename"]."/".$dataDir;
                            
                            $tmp = pathinfo($_FILES[$key]['name']);
                            $newName = time().".".$tmp["extension"];
                            move_uploaded_file($_FILES[$key]['tmp_name'], $dataDir."/".$newName);
                            
                            $data = $newName;
                        }
                    }
                }
              
                /* if there are not multiple dimensions for actual setting, do not save them in array */
                /* added multipul checkbox fix: !isset($_POST[$key."_multi"]) */
                if (isset($data) and is_array($data) and !isset($_POST[$key."_multi"]) and count($data)<2) {
                    reset($data);
                    $data = current($data);
                }
              
                /* update in database and $_SESSION[mgw]->settings */
                updateSettingsInDB($key, $data);
                
                /* set date formats */
                $_SESSION["MGW"]->settings["datefmt"] = getDateFormate($_SESSION["MGW"]->settings["set_datefmt"],$_SESSION["MGW"]->settings["set_dmysep"]);
                $_SESSION["MGW"]->settings["timefmt"] = getDateFormate($_SESSION["MGW"]->settings["set_timefmt"],$_SESSION["MGW"]->settings["set_hourminsep"]);
            }
        }
        /* redirect if needed*/
        if (isset($redirect) && $redirect) header("Location: index.php?".SID);
    }
}

/* create an array to store the module settings options */
$moduleSettings = array();

/* show a specific option screen or the settings list? */
if (!isset($_GET["module"]) and !isset($_GET["option"])) {
    /* SHOW THE MENU LIST */
    /* for each active module that has a settings.inc.php file add the settings to the moduleSettings array */
    foreach ($_SESSION["MGW"]->modules as $module) {
        if ((queryRights2_bool('root_modules_'.$module['modulename'].'_accessmodule') && $module["active"]=="1") || $module["module_type"]=="1") { // core modules always!

            /* check existance before including */
            if (file_exists(ROOTPATH."/modules/".$module["modulename"]."/inc/settings.inc.php")) {
                /* clear the settings array so we start clean */
                unset($settings);
                include(ROOTPATH."/modules/".$module["modulename"]."/inc/settings.inc.php");
                /* the inculded file should have defined it settings in an array called settings
                 * while doing this it has the opitunity to the query the database etc
                 */
                if (isset($settings[$module["modulename"]]) and is_array($settings[$module["modulename"]])) {
                    /* manually add it to the moduleSettings array we just created because we do
                     * not trust the programmers of the modules to do everything right. This way
                     * we have more control over the array and can gracefully recover from any 
                     * mistakes ... we hope :p
                     *
                     * here we only save the settings list option because the entire settings could
                     * take up a lot of memory we don't really need
                     *
                     * we put the module and option name including there translation in the array 
                     * becuase i couldn't find a way to do it with smarty
                     */
                    $moduleSettings[$module["modulename"]] = array();
                    $moduleSettings[$module["modulename"]]["name"] = Lang::getLanguageString($module["modulename"]);
                    $moduleSettings[$module["modulename"]]["options"] = array();
                    foreach ($settings[$module["modulename"]] as $optionName => $option) {
                        /* admin setting */
                        if (in_array("admin",$option) and (isset($option["admin"]) && $option["admin"])) {
                            /* check rights */
                            if ($_SESSION["MGW"]->username=="admin") {
                                $tmp = array(trim(Lang::getLanguageString($optionName))." (".Lang::getLanguageString("admin_only").")",$optionName,true);
                                array_push($moduleSettings[$module["modulename"]]["options"], $tmp);
                            }
                        } else {
                            $tmp = array(trim(Lang::getLanguageString($optionName)),$optionName,false);
                            array_push($moduleSettings[$module["modulename"]]["options"], $tmp);
                        }
                        
                    }
                    
                    /* clear the settings array to save memory 
                     * unset doens't clear mem, just removes the reference so i hope setting it to
                     * an empty array wil ... correct me if i am wrong
                     */
                    $settings = array();
                    unset($settings);
                }
            }
        }
    }
    $smarty->assign("moduleSettings",$moduleSettings);
} else {
    /* SHOW THE OPTIONS */
    if (file_exists(ROOTPATH."/modules/".$_SESSION["MGW"]->modules[$_GET["module"]]["modulename"]."/inc/settings.inc.php")) {
        /* clear the settings array so we start clean */
        unset($settings);
        include(ROOTPATH."/modules/".$_GET["module"]."/inc/settings.inc.php");
        /* the inculded file should have defined it settings in an array called settings
         * while doing this it has the opitunity to the query the database etc
         *
         * maybe modify this later so modules only retrieve extra data when we are
         * building the actual options screen
         */
        if (isset($settings[$_GET["module"]][$_GET["option"]]) and is_array($settings[$_GET["module"]][$_GET["option"]])) {
            $options = $settings[$_GET["module"]][$_GET["option"]];

            /* special case for usersettings, uses getUserData(columnname) to retrieve data */
            if (in_array("usersettings", $options) and isset($options["usersettings"]) and $options["usersettings"]) { 
                $user_settings = true; 
            } else { 
                $user_settings = false; 
            }
                        
            /* for each group of option, create an array smarty can handle */
            $moduleSettings = array();
            foreach ($options as $key => $option) {
                /* skip the admin bool */
                if ($key=="admin" or $key=="usersettings" or $key=="translate") continue;
                if ($key=="title") {
                    $settings_title = $option;
                    continue;
                }
                
                /* skip hidden settings */
                if (isset($option["hide"]) and $option["hide"]) {
                    continue;
                }
                
                $tmpSettings = array();
                /* get the name of the option 
                 * if the name is not defined we assume the is a language setting
                 * for the key of this option. any way the programmer will see that
                 * a language option needs to be definied
                 *
                 * i would advise not to use name, but to define the language option 
                 * the same as the option key (the key MUST be the same as the DB.configtag)
                 */
                if (isset($option["name"])) {
                    if (isset($options["translate"]) && $options["translate"]==false) {
                        $tmpSettings["optionName"] = trim($option["name"]);
                    } else {
                        $tmpSettings["optionName"] = trim(Lang::getLanguageString($option["name"]));
                    }
                } else {
                    $tmpSettings["optionName"] = trim(Lang::getLanguageString($key));
                }
                
                /* the option my have a note to advise the user what to do with this option 
                 * this was adde because the contacts module had this ... there is no translation
                 * mechanism for this a.t.m.
                 */
                if (isset($option["note"])) { 
                    $tmpSettings["optionNote"] = Lang::getLanguageString($option["note"]);
                } else {
                    $tmpSettings["optionNote"] = "&nbsp;";
                }

                /* now we handle each type of option seperately (each type of option is has
                 * it's own smarty template. I choose not to use the mSelectBox class because
                 * it returns HTML and i believe all HTML should be left to the templater)
                 *
                 * The following option types are availible (TODO!):
                 * - simple text box (strings) <- DEFAULT IF NO METHOD IS DEFINED
                 * - simple text box (ints, these are type check and converted to int before insertion) ...(TODO!)
                 * - simple select box (values & names)
                 * - simple checkbox(es) (optional values & names)
                 * - simple textarea (text) ...(TODO!)
                 * - ...(TODO!)
                 */
                $tmp = array();
                $switch = $option["method"];

                $sql = "SELECT COUNT(userid) AS number FROM mgw_config WHERE configtagname=".$conn->QMagic($key)." AND userid=0";
                if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
                if ($row = $res->FetchRow() and $row["number"]>0) { $default=false; } else { $default=true; }

				if ($default and isset($option["default"]) and isset($option["type"]) and $option["type"]!="" and !is_array($option["default"])) {
				  $selections = 0;
				  $dimensions = 0;
				  $value_int = 0;
				  $value_str = "";
				  $value_txt = "";
				  $description = "";
						  
				  if (isset($option["description"])) { $description = $option["description"]; }
				  if ($option["type"]=="int" and is_numeric($option["default"])) { $value_int=$option["default"]; }
				  if ($option["type"]=="txt") { $value_txt=$option["default"]; }
				  if ($option["type"]=="str") { $value_str=$option["default"]; }

				  if (isset($option["selections"]) and is_numeric($option["selections"]) and $option["selections"] > 0) { $selections=$option["selections"]; }
				  if (isset($option["dimensions"]) and is_numeric($option["dimensions"]) and $option["dimensions"] > 0) { $dimensions=$option["dimensions"]; }
				  
				  $sql = "INSERT INTO mgw_config (userid,configtagname,serialnr,value_str,value_int,value_txt,lu_user,lu_date) VALUES (0,".$conn->QMagic($key).",1,".$conn->QMagic($value_str).",".$value_int.",".$conn->QMagic($value_txt).",1,NOW())";
                  if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

                  $sql = "SELECT COUNT(configtagname) AS number FROM mgw_configtags WHERE configtagname=".$conn->QMagic($key);
                  if(!$res2 = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
                  if ($row2 = $res2->FetchRow() and $row2["number"]>0) { $default2=false; } else { $default2=true; }

				  if ($default2) {
				    $sql = "INSERT INTO mgw_configtags (configtagname,modulename,description,multipleselections,multipledimensions,valuetype,lu_user,lu_date) VALUES (".$conn->QMagic($key).",".$conn->QMagic($_GET["module"]).",".$conn->QMagic($description).",".(int)$selections.",".(int)$dimensions.",".$conn->QMagic($option["type"]).",1,NOW())";
                  if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
				}
				}
				if ($default and isset($option["default"]) and isset($option["type"]) and $option["type"]!="" and is_array($option["default"]) and count($option["default"])>0) {
				  $selections = 0;
				  $dimensions = 0;
				  $value_int = 0;
				  $value_str = "";
				  $value_txt = "";
				  $description = array();
						  
				  if (isset($option["description"])) { $description = $option["description"]; }
				  if ($option["type"]=="int") { $value_int=$option["default"]; }
				  if ($option["type"]=="txt") { $value_txt=$option["default"]; }
				  if ($option["type"]=="str") { $value_str=$option["default"]; }

				  if (isset($option["selections"]) and is_numeric($option["selections"]) and $option["selections"] > 0) { $selections=$option["selections"]; }
				  if (isset($option["dimensions"]) and is_numeric($option["dimensions"]) and $option["dimensions"] > 0) { $dimensions=$option["dimensions"]; }
				  
                  $sql = "SELECT COUNT(configtagname) AS number FROM mgw_configtags WHERE configtagname=".$conn->QMagic($key);
                  if(!$res2 = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
                  if ($row2 = $res2->FetchRow() and $row2["number"]>0) { $default2=false; } else { $default2=true; }

				  if ($default2) {
				    $sql = "INSERT INTO mgw_configtags (configtagname,modulename,description,multipleselections,multipledimensions,valuetype,lu_user,lu_date) VALUES (".$conn->QMagic($key).",".$conn->QMagic($_GET["module"]).",".$conn->QMagic($description).",".(int)$selections.",".(int)$dimensions.",".$conn->QMagic($option["type"]).",1,NOW())";
                  if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
				  }

				  $i = 0;
				  if ($option["type"]=="int") {
				    foreach ($value_int as $value_int2) {
					  $i++;
				      $sql = "INSERT INTO mgw_config (userid,configtagname,serialnr,value_str,value_int,value_txt,lu_user,lu_date) VALUES (0,".$conn->QMagic($key).",".$i.",".$conn->QMagic($value_str).",".$value_int2.",".$conn->QMagic($value_txt).",1,NOW())";
                      if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
					}
				  }
				  if ($option["type"]=="str") {
				    foreach ($value_str as $value_str2) {
					  $i++;
				      $sql = "INSERT INTO mgw_config (userid,configtagname,serialnr,value_str,value_int,value_txt,lu_user,lu_date) VALUES (0,".$conn->QMagic($key).",".$i.",".$conn->QMagic($value_str2).",".$value_int.",".$conn->QMagic($value_txt).",1,NOW())";
                      if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
					}
				  }
				  if ($option["type"]=="txt") {
				    foreach ($value_txt as $value_txt2) {
					  $i++;
				      $sql = "INSERT INTO mgw_config (userid,configtagname,serialnr,value_str,value_int,value_txt,lu_user,lu_date) VALUES (0,".$conn->QMagic($key).",".$i.",".$conn->QMagic($value_str).",".$value_int.",".$conn->QMagic($value_txt2).",1,NOW())";
                      if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
					}
				  }

				}

                switch ($switch) {
                    case "checkbox":
                        /* for checkboxes we create an array of names and values */
                        
                        /* determain which checkboxes are checked */
                        /* if there are no user values, we user the default values */
                        $sql = "SELECT COUNT(userid) AS number FROM mgw_config WHERE configtagname=".$conn->QMagic($key)." AND userid=".$_SESSION["MGW"]->userid;
                        if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
                        if ($row = $res->FetchRow() and $row["number"]>0) { $default=false; } else { $default=true; }

                        if (isset($option["choices"]) and is_array($option["choices"])) {
                            /* possible multiple checkboxes with name and values */ 
                            $i = 0;
                            foreach ($option["choices"] as $choice) {
                                /* make an array with the option name,value and whether or not the value is checked */
                                /* only translate if a valid translation is found */
                                if (trim(Lang::getLanguageString($choice["name"]))=="* ".$choice["name"]." *") {
                                    $tmp[$i]["name"] = $choice["name"];
                                } else {
                                    $tmp[$i]["name"] = trim(Lang::getLanguageString($choice["name"]));
                                }
                                $tmp[$i]["value"] = $choice["value"];   
                                
                                /* determain if a checkbox should be checked */
                                if (isset($_SESSION["MGW"]->settings[$key]) and is_array($_SESSION["MGW"]->settings[$key]) and in_array($choice["value"], $_SESSION["MGW"]->settings[$key])) {
                                    $tmp[$i]["check"] = " checked";
                                } elseif ((!isset($_SESSION["MGW"]->settings[$key]) or !is_array($_SESSION["MGW"]->settings[$key])) and isset($_SESSION["MGW"]->settings[$key]) and $_SESSION["MGW"]->settings[$key]) {
                                    $tmp[$i]["check"] = " checked";
                                } else {
                                    $tmp[$i]["check"] = "";
                                }
                                
                                /* inc the checkbox counter (for multiple checkboxes) */
                                $i++;
                            }
                            /* multipul checkbox fix */
                       		$tmpSettings["optionMethod"] = "multicheckbox";
                            
                            /* horizontal layout for multipul checkboxes layout */
                            (isset($option["layout"]) and $option["layout"]=="h")?($tmpSettings["layout"]=1):($tmpSettings["layout"]=0);
                        } else {
                            /* single checkbox with no name or value */
                            /* this value is checked whenever a reference to the configtagname 
                             * is present in $_SESSION["MGW"]->settings for this user and there is a non-empty, 
                             * non-zero value
                             */
                            if (isset($_SESSION["MGW"]->settings[$key]) and is_array($_SESSION["MGW"]->settings[$key]) and (in_array($choice["value"], $_SESSION["MGW"]->settings[$key]) or $_SESSION["MGW"]->settings[$key])) {
                                array_push($tmp, array("name"=>"","value"=>"1","check"=>" checked"));
                            } elseif ((!isset($_SESSION["MGW"]->settings[$key]) or !is_array($_SESSION["MGW"]->settings[$key])) and (isset($_SESSION["MGW"]->settings[$key]) and $_SESSION["MGW"]->settings[$key])) {
                                array_push($tmp, array("name"=>"","value"=>"1","check"=>" checked"));
                            } else {
                                array_push($tmp, array("name"=>"","value"=>"1","check"=>""));
                            }
                            
                            /* multipul checkbox fix */
                       		$tmpSettings["optionMethod"] = "checkbox";
                        }
                        /* add these settings options to the smarty array */
                        $tmpSettings["optionChoices"] = $tmp;
                        break;
                    case "text":
                        /* for text boxes int and string. no difference here, only on inserting */
                        /* text inputs only a value */
                        $tmpSettings["optionMethod"] = "text";
                        
                        /* get the maxsize if specified */
                        if (isset($option["size"]) and is_numeric($option["size"])) {
                            $tmpSettings["optionChoices"]["size"] = (int)$option["size"];
                        } else {
                            $tmpSettings["optionChoices"]["size"] = "50";
                        }
                        
                        /* get the width */
                        if (isset($option["width"]) and is_numeric($option["width"])) {
                            $tmpSettings["optionChoices"]["width"] = (int)$option["width"];
                        } 
                        
                        /* get the value if it is an array*/
                        if ($user_settings) {
                            $tmpSettings["optionChoices"]["value"] = getUserData($key);
                        } elseif (isset($_SESSION["MGW"]->settings[$key]) and is_array($_SESSION["MGW"]->settings[$key])) { 
                            $tmpSettings["optionChoices"]["value"] = $_SESSION["MGW"]->settings[$key][0];
                        /* get the value if it is not an array */
                        } elseif (isset($_SESSION["MGW"]->settings[$key])) { 
                            $tmpSettings["optionChoices"]["value"] = $_SESSION["MGW"]->settings[$key];
                        /* there is no value defined yet */ 
                        } else {
                            $tmpSettings["optionChoices"]["value"] = "";
                        }
                        break;
                    case "select":
                        /* choices must be defined, if not we do nothing for this option. also the */
                        if (isset($option["choices"]) and is_array($option["choices"])) {
                            $tmpSettings["optionMethod"] = "select";
                            
                            /* possible multiple selects */ 
                            $i = 0;
                            foreach ($option["choices"] as $select) {
                                /* only translate name if a valid translation is found */
                                if (trim(Lang::getLanguageString($select["name"]))=="* ".$select["name"]." *") {
                                    $tmp[$i]["name"] = $select["name"];
                                } else {
                                    $tmp[$i]["name"] = trim(Lang::getLanguageString($select["name"]));
                                }
                                /* the values must be defined and it must be an array */
                                if (isset($select["value"]) and is_array($select["value"])) {
                                    /* if the value does not need to be tranlated the array is ok, otherwise
                                     * we translate all the values (VALUES MUST BE INDEX 1, INDEX 0 is key/name)
                                     */
                                    $tmp[$i]["value"] = $select["value"];
                                    if (isset($option["translate"]) and $option["translate"]==true) {
                                        /* translate each value */
                                        for ($j=0; $j<count($tmp[$i]["value"]); $j++) {
                                            $tmp[$i]["value"][$j][1] = trim(Lang::getLanguageString($tmp[$i]["value"][$j][1]));
                                        }
                                    }
                                    
                                    /* get the selected value */
                                    $tmp[$i]["active"] = "";
                                    if ($user_settings) {
                                        $tmp[$i]["active"] = getUserData($key); 
                                    } elseif (!isset($tmp[$i]["value"]) or !is_array($tmp[$i]["value"])) {
                                        if ($_SESSION["MGW"]->settings[$key]==$tmp[$i]["value"]) {
                                            $tmp[$i]["active"] = $_SESSION["MGW"]->settings[$key];  
                                        }
                                    } elseif (isset($tmp[$i]["value"]) and is_array($tmp[$i]["value"])) {
                                        if (!is_array($_SESSION["MGW"]->settings[$key])) {
                                            for ($j=0; $j<count($tmp[$i]["value"]); $j++) {
                                                if ($_SESSION["MGW"]->settings[$key]==$tmp[$i]["value"][$j][0]) {
                                                    $tmp[$i]["active"] = $tmp[$i]["value"][$j][0];
                                                }
                                            }
                                        } else {
                                            for ($j=0; $j<count($tmp[$i]["value"]); $j++) {
                                                if (isset($_SESSION["MGW"]->settings[$key][$i]) and $_SESSION["MGW"]->settings[$key][$i]==$tmp[$i]["value"][$j][0]) {
                                                    $tmp[$i]["active"] = $tmp[$i]["value"][$j][0];
                                                }
                                            }
                                        }
                                    } 
                                } else {
                                    $tmp[$i]["value"] = array();
                                    $tmp[$i]["active"] = "";
                                }
                                /* inc the checkbox counter (for multiple checkboxes) */
                                $i++;
                            }
                            $tmpSettings["optionChoices"] = $tmp;
                        }
                        break;
                    case "radio":
                        $tmpSettings["optionMethod"] = "radio";
                        
                        if (isset($option["choices"]) and is_array($option["choices"])) {
                            /* multiple radio buttons with name and values */ 
                            $i = 0;
                            foreach ($option["choices"] as $choice) {
                                /* make an array with the option name,value and whether or not the value is checked */
                                /* only translate if a valid translation is found */
                                if (trim(Lang::getLanguageString($choice["name"]))=="* ".$choice["name"]." *") {
                                    $tmp[$i]["name"] = $choice["name"];
                                } else {
                                    $tmp[$i]["name"] = trim(Lang::getLanguageString($choice["name"]));
                                }
                                $tmp[$i]["value"] = $choice["value"];   
                                
                                /* determain if a checkbox should be checked */
                                if (isset($_SESSION["MGW"]->settings[$key]) and is_array($_SESSION["MGW"]->settings[$key]) and in_array($choice["value"], $_SESSION["MGW"]->settings[$key])) {
                                    $tmp[$i]["check"] = " checked";
                                } elseif ((!isset($_SESSION["MGW"]->settings[$key]) or !is_array($_SESSION["MGW"]->settings[$key])) and isset($_SESSION["MGW"]->settings[$key]) and isset($choice["value"]) and $_SESSION["MGW"]->settings[$key]==$choice["value"]) {
                                    $tmp[$i]["check"] = " checked";
                                } else {
                                    $tmp[$i]["check"] = "";
                                }
                                
                                /* inc the checkbox counter (for multiple checkboxes) */
                                $i++;
                            }
                            $tmpSettings["optionChoices"] = $tmp;
                        }
                        break;
                    case "textarea":
                        $tmpSettings["optionMethod"] = "textarea";
                        
                        /* get the maxsize if specified */
                        if (isset($option["size"]) and is_numeric($option["size"])) {
                            $tmpSettings["optionChoices"]["size"] = (int)$option["size"];
                        } else {
                            $tmpSettings["optionChoices"]["size"] = "200";
                        }
                        
                        /* get the width */
                        if (isset($option["width"]) and is_numeric($option["width"])) {
                            $tmpSettings["optionChoices"]["width"] = (int)$option["width"];
                        }
                        /* get the height */
                        if (isset($option["height"]) and is_numeric($option["height"])) {
                            $tmpSettings["optionChoices"]["height"] = (int)$option["height"];
                        }
                        
                        /* get the value if it is an array*/
                        if (isset($_SESSION["MGW"]->settings[$key]) and is_array($_SESSION["MGW"]->settings[$key])) { 
                            $tmpSettings["optionChoices"]["value"] = $_SESSION["MGW"]->settings[$key][0];
                        /* get the value if it is not an array */
                        } elseif (isset($_SESSION["MGW"]->settings[$key])) { 
                            $tmpSettings["optionChoices"]["value"] = $_SESSION["MGW"]->settings[$key];
                        /* there is no value defined yet */ 
                        } else {
                            $tmpSettings["optionChoices"]["value"] = "";
                        }
                        break;
                    case "file":
                        $tmpSettings["optionMethod"] = "file";
                        
                        /* get the value if it is an array*/
                        if (isset($_SESSION["MGW"]->settings[$key])) {
                            $data = unserialize($_SESSION["MGW"]->settings[$key]);
                            $tmpSettings["optionChoices"]["value"] = stripslashes($data[2]);
                            $tmpSettings["optionChoices"]["type"] = $data[1];
                        } else {
                            $tmpSettings["optionChoices"]["value"] = "";
                        }
                        break;
                    case "password":
                        /* we don't write values for password fields */
                        $tmpSettings["optionMethod"] = "password";
                        
                        /* get the maxsize if specified */
                        if (isset($option["size"]) and is_numeric($option["size"])) {
                            $tmpSettings["optionChoices"]["size"] = (int)$option["size"];
                        } else {
                            $tmpSettings["optionChoices"]["size"] = "20";
                        }
                        break;
                    case "date":
                        $tmpSettings["optionMethod"] = "date";

                        if (isset($option["start"]) and is_numeric($option["start"])) {
			    $tmpSettings["optionChoices"]["start"] = $option["start"];
                        } else {
                            $tmpSettings["optionChoices"]["start"] = "-5";
                        }
                        if (isset($option["end"]) and is_numeric($option["end"])) {
			    $tmpSettings["optionChoices"]["end"] = $option["end"];
                        } else {
                            $tmpSettings["optionChoices"]["end"] = "+5";
                        }

			if ($user_settings){
			    $tmpSettings["optionChoices"]["value"] = $conn->UnixDate(getUserData($key));
			}
                        elseif(isset($_SESSION["MGW"]->settings[$key])){
                            $tmpSettings["optionChoices"]["value"] = $conn->UnixDate($_SESSION["MGW"]->settings[$key][0]);
			}
                        else{
                            $tmpSettings["optionChoices"]["value"] = time();
			}

                        break;
                    default:
                        /* text inputs as default */
                        $tmpSettings["optionMethod"] = "text";
                        $tmpSettings["optionChoices"]["size"] = "50";
                        
                        /* get the value if it is an array*/
                        if (isset($_SESSION["MGW"]->settings[$key]) and is_array($_SESSION["MGW"]->settings[$key])) { 
                            $tmpSettings["optionChoices"]["value"] = $_SESSION["MGW"]->settings[$key][0];
                        /* get the value if it is not an array */
                        } elseif (isset($_SESSION["MGW"]->settings[$key])) { 
                            $tmpSettings["optionChoices"]["value"] = $_SESSION["MGW"]->settings[$key];
                        /* there is no value defined yet */ 
                        } else {
                            $tmpSettings["optionChoices"]["value"] = "";
                        }
                }
                
                /* push onto the smarty array */
                $moduleSettings[$key] = $tmpSettings;
                
                /* handle spacers */
                if (isset($option["spacer"])) {
                    $tmpSettings = array();
                    $spacer_id = uniqid("spacer");
                    if (is_numeric($option["spacer"])) {
                        $tmpSettings = $option["spacer"];
                        $moduleSettings[$spacer_id] = $tmpSettings;
                    }
                }
            }
            
            /* assign our settings to smarty */
            $smarty->assign("moduleSettings",$moduleSettings); 
            
            /* assign the title of the settings screen */
            if (!isset($settings_title)) {
                $smarty->assign("module",Lang::getLanguageString("edit_".$_GET["module"]));
            } else {
                $smarty->assign("module",Lang::getLanguageString($settings_title));
            }
            $smarty->assign("modulename",$_GET["module"]);
            $smarty->assign("optionname",$_GET["option"]);
            
            $smarty->assign("js","");
            $smarty->assign("suname","contactsave");
            $smarty->display('settings_options.tpl');
            
            exit();
        } else {
            /* erm ... so how did we get here in the first place? */
        }
    }
}

$smarty->display('settings_menu.tpl');

/*
echo("<pre>");
print_r($_SESSION["MGW"]->settings);
echo("</pre>");
*/

?>
