<?php
/*
 * This file is part of a larger software package. Please read the License file 
 * in the root of this installation for terms of usage and distribution.
 * 
 * @author The Web Pro Miami, Inc. <info@thewebpro.com>
 * @copyright The Web Pro Miami, Inc. <info@thewebpro.com>, http://www.thewebpro.com/
 * 
 * CORE: manage/edit/site_settings.php - version 1.0
*/

require("../inc/stop_cache.php");

$nAdminOnlyPg = 1;

// Secure and connect
require("../../inc/dbconnect.php");
require("../inc/secure_page.php");

require("../../inc/config.php");
require("../inc/lang.php");
require("../inc/langutil.php");
include("../inc/calendar.php");
include("../inc/rc4.php");


// Get passed-in vars
$nRecID = (isset($_GET['id']) ? $_GET['id'] : NULL);
if(!$nRecID){ $nRecID = (isset($_POST['id']) ? $_POST['id'] : NULL); }
$nEditMode = (isset($_GET['editMode']) ? $_GET['editMode'] : NULL);
if(!$nEditMode){ $nEditMode = (isset($_POST['editMode']) ? $_POST['editMode'] : NULL); }

// AJAX Specific vars
$nPassThru = "?id=$nRecID";
$nDivToUpdate = "settingsTable"; // must be same as parent edit page
$nPageInDiv = "edit/site_settings.php";

// Get info
$nSettingsARRAY = array();
$nSQL = "SELECT * FROM nSettings";
mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
while($Row = mysql_fetch_array($Result)){
	$nSetting = $Row["nSetting"];
	$nValue = $Row["nValue"];
	$nSettingsARRAY[$nSetting] = $nValue;
}
// Languages
$nAllLanguagesARRAY = nGetAllLanguagesARRAY("nLang_");
$nActiveLangText = implode(", ",nGetLangActiveARRAY());
$nDefLanguage = $nSettingsARRAY["defLanguage"];
if(!$nDefLanguage){ nAddSetting("defLanguage","en"); $nDefLanguage = "en"; } else { $nDefLanguageText = nGetLangName($nDefLanguage); }

$nPermalinks = $nSettingsARRAY["permalinks"];
if($nPermalinks){ $nPermalinksText = _("Yes"); } else { $nPermalinksText = _("No"); }

$nAllowMobile = $nSettingsARRAY["allowMobile"];
if($nAllowMobile){ $nAllowMobileText = _("Yes"); } else { $nAllowMobileText = _("No"); }

$nSiteEnabled = $nSettingsARRAY["siteEnabled"];
$nSiteRedirect = $nSettingsARRAY["siteRedirect"];
if($nSiteEnabled){
	$nSiteEnabledText = "<img src=\"assets/images/icons/green_ico.png\" alt=\"\" width=\"23\" height=\"23\" border=\"0\" style=\"margin-bottom:-6px;\"> "._("Online");
} else {
	$nSiteEnabledText = "<img src=\"assets/images/icons/red_ico.png\" alt=\"\" width=\"23\" height=\"23\" border=\"0\" style=\"margin-bottom:-6px;\"> "._("Disabled and forwading to")." <em>$nSiteRedirect</em>";
}
?>

<?php if(!$nEditMode){ ?>

<div id="editBox">
	<div id="editBoxStatic" class="form no-border">
		<table border="0" cellspacing="0" cellpadding="0">
		  <tr>
			<td valign="top" style="padding-right:20px;"><strong><?php echo _("Site status:"); ?></strong></td>
			<td valign="top"><?php echo $nSiteEnabledText;?></td>
		  </tr>
		  <tr>
			<td valign="top" style="padding-right:20px;"><strong><?php echo _("Available languages:"); ?></strong></td>
			<td valign="top"><?php echo $nActiveLangText;?> <span class="caption">(<?php echo _("Default language:"); ?> <?php echo $nDefLanguageText;?>)</span></td>
		  </tr>
		  <tr>
			<td valign="top" style="padding-right:20px;"><strong><?php echo _("Offer Mobile version?"); ?></strong></td>
			<td valign="top"><?php echo $nAllowMobileText;?></td>
		  </tr>
		  <tr>
			<td valign="top" style="padding-right:20px;"><strong><?php echo _("Use Permalinks?"); ?></strong></td>
			<td valign="top"><?php echo $nPermalinksText;?></td>
		  </tr>
		</table>

		<div class="clearfix center" id="buttonBox">
			<input type="button" name="nEdit" value="<?php echo _("Edit"); ?>" class="button blue" onClick="loadContentToID('#<?php echo $nDivToUpdate?>','<?php echo $nPageInDiv.$nPassThru?>&editMode=1');">
		</div>
	</div>
</div>
<?php } ?>

<?php if($nEditMode){ ?>
<div id="editBox">
<?php
include("../inc/form_class.php");

$nFormName = "FormUserEdit";
$nForm1 = new Form();
//$nForm1->DEBUG = true;
$nForm1->Name = $nFormName;
$nForm1->Action = $_SERVER['PHP_SELF'];
$nForm1->SubmitText = _("Update");
$nForm1->CancelText = _("Cancel");
$nForm1->CancelRedirect = "loadContentToID('#$nDivToUpdate','$nPageInDiv$nPassThru');";
$nForm1->CancelRedirectIsJS = true;
// AJAX settings
$nForm1->SubmitToJS = "return submitForm('$nDivToUpdate','$nPageInDiv$nPassThru',this.name);return false;";
$nForm1->DontProcess = "siteRedirect,editMode,nAvailLang,defLanguage";
// Form styling
$nForm1->FormClass = "form no-border";
$nForm1->CleanMarkup = true;
$nForm1->SubmitClass = "button blue";
$nForm1->CancelClass = "button";
$nForm1->ButtonTemplate = "<div class=\"clearfix grey-highlight\"><div class=\"input no-label\">[#Buttons#]</div></div>\n";
$nForm1->FieldTemplate = "<div id=\"[#RowID#]\" class=\"clearfix\" style=\"[#RowStyle#]\">[#Label#]<div class=\"input\" style=\"[#ItemStyle#]\">[#BeforeField#][#Field#][#AfterField#]<span class=\"info\">[#Caption#]</span></div></div>\n";
$nForm1->GroupTemplate = "<div id=\"[#ID#]\" style=\"[#Style#]\" class=\"[#Class#]\">\n[#Name#][#FieldCode#]\n</div>\n";


// Create groups
$nFormGroup1 = new FormGroup();
$nFormGroup1->Name = _("Defaults");

// Create fields
$nFormField = new FormField("hidden","editMode");
$nFormField->Value = "1";
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("radio","siteEnabled",_("Site Status:"));
$nOnlineText = _("Online");
$nOfflineText = _("Offline");
$nFormField->DataARRAY = array(
	"1" => "<img src='assets/images/icons/green_ico.png' alt='' width='23' height='23' border='0' style='margin-bottom:-6px;'> $nOnlineText<BR>",
	"0" => "<img src='assets/images/icons/red_ico.png' alt='' width='23' height='23' border='0' style='margin-bottom:-6px;'> $nOfflineText<BR>");
if($nSiteEnabled!==""){ $nFormField->SelectedARRAY = array("$nSiteEnabled" => "selected"); }
$nFormField = $nForm1->AddValidation("required",$nFormField);
$nFormField->Class = "xlarge";
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("text","siteRedirect",_("If offline, forward requests to:"));
$nFormField->Value = $nSiteRedirect;
$nFormField->RowStyle = "clear:both;float:none;";
$nFormField = $nForm1->AddValidation("maxlength",$nFormField,255);
$nFormField->Class = "xlarge";
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("checkbox","nAvailLang",_("Available languages on your site:"));
$nFormField->DataARRAY = $nAllLanguagesARRAY;
$nFormField->SelectedARRAY = nGetLangActiveARRAY("nLang_");
$nFormField->RowSize = "Half";
$nFormField = $nForm1->AddValidation("required",$nFormField);
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("select","defLanguage",_("Default language:"));
$nFormField->DataARRAY = nGetLangActiveARRAY();
$nFormField->SelectedARRAY = array($nDefLanguage => "1");
$nFormField->RowSize = "Half";
$nFormField = $nForm1->AddValidation("required",$nFormField);
$nFormField->Class = "medium";
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("select","allowMobile",_("Offer Mobile version of site?"));
$nFormField->Rel = "tooltips";
$nFormField->Title = _("Shows a mobile version to visitors with iPhone, Android, Palm and iPod. Mobile template required.");
$nFormField->DataARRAY = array(
	"1" => _("Yes"),
	"0" => _("No"));
if($nAllowMobile!==""){ $nFormField->SelectedARRAY = array("$nAllowMobile" => "selected"); }
$nFormField = $nForm1->AddValidation("required",$nFormField);
$nFormField->Class = "medium";
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("select","permalinks","Use Permalinks?");
$nFormField->Rel = "tooltips";
$nFormField->Title = _("Permalinks allow you to have more memorable, aesthetically pleasing and search-friendly web URLs for your website. Your server must support .htaccess and mod_rewrite fo Permalinks to work.");
$nUsePermalinksText = _("Yes, use Permalinks (recommended)");
$nUseNormalLinksText = _("No, use normal URLs");
$nFormField->DataARRAY = array(
	"1" => "$nUsePermalinksText <span class=\"caption\">(ex: http://www.website.com/10/my_new_page.html)</span>",
	"0" => "$nUseNormalLinksText <span class=\"caption\">(ex: http://www.website.com/content.php?id=10)</span>");
if($nPermalinks!==""){ $nFormField->SelectedARRAY = array("$nPermalinks" => "selected"); }
$nFormField = $nForm1->AddValidation("required",$nFormField);
$nFormGroup1->AddField($nFormField);

// Finalize and display form
$nForm1->AddGroup($nFormGroup1);
$nFormToDisplay = $nForm1->GetForm();

// AJAX redirect if form submitted w/o error, otherwise display form (again, if necessary)
if($nForm1->HasProcessed){
	// Save all settings
	$nSiteEnabled = $_POST["siteEnabled"];
	$Query = "UPDATE nSettings SET nValue='$nSiteEnabled' WHERE nSetting='siteEnabled' LIMIT 1";
	mysql_select_db($DBName);
	mysql_query($Query, $Link);
	
	$nSiteRedirect = $_POST["siteRedirect"];
	$Query = "UPDATE nSettings SET nValue='$nSiteRedirect' WHERE nSetting='siteRedirect' LIMIT 1";
	mysql_select_db($DBName);
	mysql_query($Query, $Link);
	
	$nAllowMobile = $_POST["allowMobile"];
	$Query = "UPDATE nSettings SET nValue='$nAllowMobile' WHERE nSetting='allowMobile' LIMIT 1";
	mysql_select_db($DBName);
	mysql_query($Query, $Link);
	
	//// BEGIN Permalinks processing
	$nPermalinks = $_POST["permalinks"];
	$Query = "UPDATE nSettings SET nValue='$nPermalinks' WHERE nSetting='permalinks' LIMIT 1";
	mysql_select_db($DBName);
	mysql_query($Query, $Link);
	// Setup Htaccess file based on permalink choice
	$nOnPath = "../../.htaccess";
	$nOffPath = "../../htaccess.txt";
	if($nPermalinks){
		if(file_exists($nOffPath)){ copy($nOffPath,$nOnPath); unlink($nOffPath); }
	} else {
		if(file_exists($nOnPath)){ copy($nOnPath,$nOffPath); unlink($nOnPath); }
	}
	//// END Permalinks processing
	
	//// BEGIN Languages processing
	$nDefLanguage = $_POST["defLanguage"];
	$Query = "UPDATE nSettings SET nValue='$nDefLanguage' WHERE nSetting='defLanguage' LIMIT 1";
	mysql_select_db($DBName);
	mysql_query($Query, $Link);
	// pull in submitted data
	$nActiveLangARRAY = array();
	foreach($_POST as $key => $val) {
		$nLangARRAY = explode("_",$key);
		// don't process unneeded data
		if($nLangARRAY[0]=="nLang" && $nLangARRAY[1]){
			if($val){ $nActiveLangARRAY[] = $nLangARRAY[1]; }
		}
	}
	// Remove any previous languages
	$nPath = "../../lang/def/";
	$nFinalPath = "../../lang/";
	if($nFinalPath){ $nDeletedFileCount = nDeleteAllFiles($nFinalPath); }
	// Copy each ACTIVE file from 'default' language folder to 'active' folder
	foreach($nActiveLangARRAY as $nFileCode) {
		$nFilePath = $nPath.$nFileCode.".php";
		$nFinalFilePath = $nFinalPath.$nFileCode.".php";
		if(file_exists($nFilePath)){ copy($nFilePath,$nFinalFilePath); }
	}
	//// END Languages processing
	echo "<script>loadContentToID('#$nDivToUpdate','$nPageInDiv$nPassThru');</script>";
} else {
	echo $nFormToDisplay;
}
?>
</div>
<?php } ?>
<?php
// returns list of active storefront languages in alpha order, default will be first item in list 
function nGetAllLanguagesARRAY($nPreText = ""){
	global $nDefLanguage;
	$nTable = "";
	$nDataARRAY = array();
	$nDefaultLangARRAY = array();
	$nLangARRAY = array();
	$nLangActiveARRAY = nGetLangActiveARRAY();
	// Get all files in directory
	$path = "../../lang/def/";    
	$dir_handle = @opendir($path) or die("Unable to open $path");    
	while ($file = readdir($dir_handle)) {
		if($file == "." || $file == ".." || $file == "index.php" )
			continue;
		$nFileCode = str_replace(".php","",$file);
		if(!is_dir("$path$file/")){
			if(file_exists("$path$file")){ require("$path$file"); }
			if($nFileCode == $nDefLanguage){
				if($nLang){ $nDefaultLangARRAY["$nFileCode"] = $nLang; } // default language
			} else {
				if($nLang){ $nLangARRAY["$nFileCode"] = $nLang; }
			}
		}
	}
	closedir($dir_handle);
	// sorting, and add default to top of list
	krsort($nLangARRAY);
	foreach($nDefaultLangARRAY as $nLangCode => $nLangName) {
		$nLangARRAY["$nLangCode"] = $nLangName;
	}
	$nLangARRAY = array_reverse($nLangARRAY,true);
	// create HTML
	foreach($nLangARRAY as $nLangCode => $nLangName){
		if(in_array($nLangCode,$nLangActiveARRAY)){ $nChecked="checked"; } else { $nChecked=""; }
		$nTable.="<input type=\"checkbox\" name=\"$nLangCode\" value=\"1\" $nChecked> $nLangName<BR><BR>";
		
		$nDataARRAY["$nPreText$nLangCode"] = "$nLangName<BR>";
	}
	return $nDataARRAY;
}
function nGetLangName($nLangCode){
	if(!$nLangCode){ return; }
	// Get lang file
	$path = "../../lang/def/$nLangCode.php";
	if(file_exists("$path")){ require("$path"); }
	return $nLang;
}
function nGetLangActiveARRAY($nPreText = ""){
	$nDataARRAY = array();
	// Get all files in directory
	$path = "../../lang/";    
	$dir_handle = @opendir($path) or die("Unable to open $path");    
	while ($file = readdir($dir_handle)) {
		if($file == "." || $file == ".." || $file == "index.php" )
			continue;
		$nFileCode = str_replace(".php","",$file);
		if(!is_dir("$path$file/")){
			if(file_exists("$path$file")){ require("$path$file"); }
			if($nLang){ $nDataARRAY["$nPreText$nFileCode"] = $nLang; }
		}
	}
	closedir($dir_handle);
	return $nDataARRAY;
}
function nDeleteAllFiles($path){
	$nDeletedFiles = 0;
	// Get all folders/files in directory
	$dir_handle = @opendir($path) or die("Unable to open $path");    
	while ($file = readdir($dir_handle)) {
		if(is_dir("$path$file/")){ continue; }
		if($file != "." && $file != ".."){
			// Delete individual file
			unlink($path.$file);
			$nDeletedFiles++;
		}
	}
	closedir($dir_handle);
	return $nDeletedFiles;
}
function nAddSetting($nSettingCode,$nSettingValue=""){
	global $DBName,$Link;
	if(!$nSettingCode){ return; }
	$nSQL = "INSERT INTO nSettings (nSetting,nValue) VALUES ('$nSettingCode','$nSettingValue')";
	mysql_select_db($DBName);
	mysql_query($nSQL, $Link);
}
?>
<?php require("../../inc/db_close.php"); ?>
