<?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/dialog/component_add.php - version 1.01
*/

$nSecureMe=1;

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

// bring in other required files
require("../inc/langutil.php");
require("../../inc/config.php");
require("../inc/lang.php");
require("../../inc/tmplutil.php");

// config
$nRefreshCall = "refreshParentsCompAdd();";

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

$nCompPath = "../../comp/";

// Get all new components and import them into the database
nImportNewComps();

// AJAX Specific vars
$nPassThru = "";
$nDivToUpdate = "editModal";
$nPageInDiv = "dialog/component_add.php";

// Get additional data
if($nRecID){
	$nSQL = "SELECT nType,nTitle FROM nPage WHERE nID=$nRecID LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nType = $Row["nType"];
		$nTitle = $Row["nTitle"];
	}
}
?>

<div id="<?php echo $nDivToUpdate;?>">
<?php
include("../inc/form_class.php");

$nFormName = "FormCompAdd";
$nForm1 = new Form();
$nForm1->DEBUG = false;
$nForm1->Name = $nFormName;
$nForm1->Action = $_SERVER['PHP_SELF'];
$nForm1->CancelText = _("Cancel");
$nForm1->CancelRedirect = "$.colorbox.close()";
$nForm1->CancelRedirectIsJS = true;
$nForm1->SubmitText = _("Add Component");
$nForm1->AddToDBTable = "xComponentPage";

$nForm1->DBLink = $Link;
$nForm1->nUseADODB = false;
// AJAX settings
$nForm1->SubmitIsJS = true;
$nForm1->SubmitToJS = "return submitForm('$nDivToUpdate','$nPageInDiv$nPassThru','$nFormName');return false;";
// 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();

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

$nFormField = new FormField("select","nComponentID",_("Component Type:"));
$nFormField->onBlur = "nShowCompGuide('comp_'+this.value);";
$nFormField->DataARRAY = nGetComponentARRAY();
if($nRecID){
	$nFormField->SelectedARRAY = array("$nRecID" => "selected");
} else {
	$nFormField->SelectedARRAY = array("0" => "selected"); // default
}
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("select","nColumnID",_("Add This To:"));
$nFormField->DataARRAY = nGetColumnARRAY();
if(isset($nColumnID)){
	$nFormField->SelectedARRAY = array("$nColumnID" => "selected");
} else {
	$nFormField->SelectedARRAY = array("1" => "selected"); // default
}
$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){
	$nPageID = $_POST["nPageID"];
	$nCompID = $_POST["nComponentID"];
	
	// log system event
	$nSystemEventDesc = "New component [nCompID:$nCompID] added to page [nPageID:$nPageID]";
	$Query = "INSERT INTO nSystemEventLog (nEventTime,nEventDesc,nEditorUser) VALUES ('".date("Y-m-d H:i:s")."','$nSystemEventDesc','$ValidUser')";
	mysql_select_db($DBName); mysql_query($Query, $Link);
	
	// Go directly to Edit Component Content screen
	echo "<script>$nRefreshCall</script>";
	echo "<script>openEditCompDialog(".$nForm1->InsertID.");</script>";
	//echo "<script>$.colorbox({href:\"dialog/component_edit.php?id=".$nForm1->InsertID."\",overlayClose:false,maxWidth:850});</script>";
	echo "<script>$.colorbox.close();</script>";
	exit();
} else {
	echo $nFormToDisplay;
	echo "<script>$.colorbox.resize();</script>";
}
?>
	
	<BR>
	<div id="compBox" style="border:1px solid #EEE;padding:10px;">
		<?php echo nGetCompGuide();?>
	</div>
<script>
nShowCompGuide = function(nCompToShow){
	$("#compBox>div").hide(); // hide all children
	$("#"+nCompToShow).fadeIn(); // fade in info
	$.colorbox.resize();
}
refreshParentsCompAdd = function(){
	try{ refreshPageComps(); } catch(e){ }
	try{ refreshMobileComps(); } catch(e){ }
}
</script>
	
</div>
<?php
function nGetColumnARRAY(){
	global $nOpenerTag,$nCloserTag,$nTagParamDelim,$nTagSubParamDelim,$nThemePath,$nAllowMobile;
	global $nRecID;
	if(!$nRecID){ return; }
	$nDataARRAY = array();
	$nCurrentTheme = nGetActiveThemePath();
	$nTmplLayoutPath = "../../tmpl/{$nCurrentTheme}layouts/";
	// Set template file
	$nType = nGetPageType($nRecID);
	switch($nType){
		case "Homepage": $nFileName = "home.html"; break;
		case "Content": $nFileName = "content.html"; break;
		case "Search": $nFileName = "search.html"; break;
		case "Template": $nFileName = "content.html"; break;
		case "Link": $nFileName = ""; break;
		default: $nFileName = strtolower($nType).".html"; break;
	}
	$nFullTmplLayoutPathARRAY[] = "$nTmplLayoutPath$nFileName";
	// Add mobile template
	if($nAllowMobile){
		$nFileName = "mobile.html";
		$nFullTmplLayoutPathARRAY[] = "$nTmplLayoutPath$nFileName";
	}
	foreach($nFullTmplLayoutPathARRAY AS $nFullTmplLayoutPath){
		if(file_exists($nFullTmplLayoutPath) && is_file($nFullTmplLayoutPath)){ $nTemplateCode = file_get_contents($nFullTmplLayoutPath); } else {
			exit("<div align=\"center\" style=\"padding:20px;\">A layout for this template does not exist: $nFullTmplLayoutPath.<BR><BR>Please check your system configuration or switch to a different template.</div>");
		}
		// Parse layout template
		if($nTemplateCode){
			do{
				$nOpenerPos = strpos($nTemplateCode,$nOpenerTag);
				$nCloserPos = strpos($nTemplateCode,$nCloserTag,$nOpenerPos);
				if($nOpenerPos!==false && $nCloserPos!==false){
					$nInnerTag = substr($nTemplateCode,($nOpenerPos+strlen($nOpenerTag)),($nCloserPos-strlen($nCloserTag)-$nOpenerPos));
					$nReplacement = "";
					$nInnerTagARRAY = explode($nTagParamDelim,$nInnerTag);
					$nTemplateItem = $nInnerTagARRAY[0];
					unset($nInnerTagARRAY[0]);
					switch($nTemplateItem){
						case "compColumnComps":
							$nColumnID = nGetParam("COLID",$nInnerTagARRAY);
							$nTitle = nGetParam("TITLE",$nInnerTagARRAY);
							$nDataARRAY[$nColumnID] = "$nTitle";
							break;
					}
					$nTemplateCode = str_replace(($nOpenerTag.$nInnerTag.$nCloserTag),$nReplacement,$nTemplateCode);
				}
			} while($nOpenerPos!==false);
		}
	}
	return $nDataARRAY;
}

// to capture calls and prevent errors from included comp, but not needed to run now
//function addField($nFldID="",$nTitle="",$nCaption="",$nDefVal="",$nCustFuncMan="",$nCustFuncSite=""){
	//return;
//}

function nGetActiveThemePath(){
	global $DBName,$Link;
	$nSettingsARRAY = array();
	$nSQL = "SELECT * FROM nSettings WHERE nSetting='activeTemplate'";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	while($Row = mysql_fetch_array($Result)){
		$nActiveTmplPath = $Row["nValue"];
	}
	return $nActiveTmplPath;
}

function nImportNewComps(){
	global $DBName,$Link;
	global $nCompPath,$nDefaultLang;
	$nTable = "";
	// Get all files in Components directory
	$dir_handle = @opendir($nCompPath) or die("Unable to open Component path: $nCompPath");
	while ($file = readdir($dir_handle)) {
		if($file == "." || $file == ".." || $file == "index.php" )
			continue;
		if(!is_dir("$nCompPath$file")){
			// reset imported vars
			$nName = ""; $nDescription = ""; $nPageTypeLimit = ""; $nTemplateFile = "";
			$nFileName="$file";
			$nFilePath="$nCompPath$file";
			if(file_exists("$nFilePath")){
				// Pull in component settings file
				// include($nFilePath);
				$nConnFile = fopen($nFilePath,"r");
				if($nConnFile){
					$nFileCode = fread($nConnFile,filesize($nFilePath));
					fclose($nConnFile);
				} else { return 0; }
				$nFileCode = str_replace("\r\n","\n",$nFileCode);
				$nFileCodeARRAY = explode("\n",$nFileCode);
				if(isset($nFileCodeARRAY[2]) && strpos($nFileCodeARRAY[2],"nName")){ eval($nFileCodeARRAY[2]); }
				if(isset($nFileCodeARRAY[3]) && strpos($nFileCodeARRAY[3],"nDescription")){ eval($nFileCodeARRAY[3]); }
				if(isset($nFileCodeARRAY[4]) && strpos($nFileCodeARRAY[4],"nPageTypeLimit")){ eval($nFileCodeARRAY[4]); }
				if(isset($nFileCodeARRAY[5]) && strpos($nFileCodeARRAY[5],"nTemplateFile")){ eval($nFileCodeARRAY[5]); }
				if($nName){
					$nCompID = nGetCompIDFromName($nName);
					//print "id exists for $nName: $nCompID<BR>";
					if($nTemplateFile && !$nCompID){ // if comp doesn't already exist in DB (no ID exists), add it
						$nName = nTruncateString(trim($nName),50);
						$nDescription = addslashes(nTruncateString(trim($nDescription),255));
						$nPageTypeLimit = addslashes(nTruncateString(trim($nPageTypeLimit),50));
						$nTemplateFile = nTruncateString(trim($nTemplateFile),255);
						$nTemplateFilePath="$nCompPath$nTemplateFile";
						$nLangPath = "$nDefaultLang/";
						$nTemplateOverridePath = "$nCompPath$nLangPath$nTemplateFile";
						//print "template file ($nTemplateFilePath) exists? ".file_exists("$nTemplateFilePath")."<BR>";
						//print "template override file ($nTemplateOverridePath) exists? ".file_exists("$nTemplateOverridePath")."<BR>";
						// Add plugin to database un-activated if all tests passed
						if($nName && (file_exists("$nTemplateFilePath") || file_exists("$nTemplateOverridePath"))){
							//print "saving to db<BR>";
							$Query = "INSERT INTO nComponent VALUES ('0','$nName','$nDescription','1','$nPageTypeLimit','$nFileName')";
							mysql_select_db($DBName);
							mysql_query($Query, $Link);
						}
					}
				}
			}
		}
	}
	closedir($dir_handle);
	return $nTable;
}

function nTruncateString($nStr,$nMax){
  if(strlen($nStr)>$nMax) {
    $leave = $max - strlen($rep);
    return substr($nStr,0,$nMax);
  }
  return $nStr;
}
function nGetCompIDFromName($nCompName){
	global $DBName, $Link;
	if(!$nCompName){ return; }
	$nID = "";
	$Query = "SELECT nID FROM nComponent WHERE nName='$nCompName'";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	while ($Row = mysql_fetch_array($Result)) {
		$nID = $Row["nID"];
	}
	return $nID;
}

function nGetNextContentNum(){
	global $DBName,$Link;
	$nSQL = "SELECT Max(nID) AS nID FROM nContent";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nID = $Row["nID"] + 1;
	}
	return $nID;
}

function nGetComponentARRAY(){
	global $DBName,$Link,$nType;
	global $nRecID;
	$nDataARRAY = array();
	$nSQL = "SELECT * FROM nComponent WHERE nActive=1 ORDER BY nName";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	while($Row = mysql_fetch_array($Result)){
		$nID = $Row["nCompFile"];
		$nName = $Row["nName"];
		$nTypeLimit = $Row["nTypeLimit"];
		if($nTypeLimit){
			if($nType==$nTypeLimit){ $nDataARRAY["$nID"] = "$nName"; }
		} else {
			$nDataARRAY["$nID"] = "$nName";
		}
	}
	return $nDataARRAY;
}

function nGetCompGuide(){
	global $DBName,$Link;
	$nFirstRow = true;
	$nTable = "";
	$nSQL = "SELECT * FROM nComponent ORDER BY nName";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	while($Row = mysql_fetch_array($Result)){
		$nID = $Row["nID"];
		$nName = $Row["nName"];
		$nDesc = $Row["nDesc"];
		if($nFirstRow){
			$nTable.="<div id=\"comp_$nID\"><strong>$nName</strong><BR>$nDesc</div>";
			$nFirstRow = false;
		} else {
			$nTable.="<div id=\"comp_$nID\" style=\"display:none;\"><strong>$nName</strong><BR>$nDesc</div>";
		}
	}
	return $nTable;
}
?>
<?php require("../../inc/db_close.php"); ?>
