<?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_duplicate.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();";

// pull in all active languages (used to create multiple fields, when needed)
$nActiveLangARRAY = nGetLangActiveARRAY("../../lang/");

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

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

// Get additional data
if($nRecID){
	$nSQL = "SELECT * FROM xComponentPage WHERE nID=$nRecID";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nContentID = $Row["nContentID"];
		$nCompID = $Row["nComponentID"];
		$nPageID = $Row["nPageID"];
		$nColumnID = $Row["nColumnID"];
		$nXCompOrderID = $Row["nOrderID"];
		$nCompTitle = nGetComponentName($nCompID);
	}
}
?>

<div id="<?php echo $nDivToUpdate;?>">

<?php
include("../inc/form_class.php");

$nFormName = "FormCompEdit";
$nForm1 = new Form();
//$nForm1->DEBUG = true;
$nForm1->Name = $nFormName;
$nForm1->Action = $_SERVER['PHP_SELF'];
$nForm1->CancelText = "Cancel";
$nForm1->CancelRedirect = "$.colorbox.close()";
$nForm1->CancelRedirectIsJS = true;
$nForm1->SubmitText = "Duplicate";
//$nForm1->AddToDBTable = "xComponentPage";
$nForm1->DontProcess = "id";
$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","id");
$nFormField->Value = $nRecID;
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("hidden","nComponentID");
$nFormField->Value = $nCompID;
$nFormGroup1->AddField($nFormField);

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

$nFormField = new FormField("hidden","nContentID");
$nFormField->Value = $nContentID;
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("hidden","nXCompOrderID");
$nFormField->Value = $nXCompOrderID;
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("checkbox","nDupToPageID",_("Duplicate this component to page:"));
$nFormField->DataARRAY = nGetPageARRAY();
if($nPageID){
	// $nFormField->SelectedARRAY = array("$nPageID" => "selected");
} else {
	$nFormField->SelectedARRAY = array("0" => "selected"); // default
}
$nFormField->RowSize = "Half";
$nFormField->RowStyle = "width:90%; height:200px; padding:5px; overflow:auto; border:1px solid #ccc";
$nFormField->Style = "margin:0 3px 6px 10px;";
$nFormField = $nForm1->AddValidation("required",$nFormField);
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("radio","nDupType",_("Duplicate Type:"));
$nFormField->Caption = _("Choose whether this duplicate is a separate COPY or a CLONE<BR>(e.g. update it here and it updates on both pages).");
$nFormField->DataARRAY = array(
	"COPY" => "Copy",
	"CLONE" => "Clone");
$nFormField->SelectedARRAY = array("COPY" => "checked");
$nFormField->RowSize = "Half";
$nFormField = $nForm1->AddValidation("required",$nFormField);
$nFormGroup1->AddField($nFormField);

$nFormField = new FormField("select","nColumnID",_("Duplicate this to:"));
$nFormField->DataARRAY = nGetColumnARRAY();
if($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){
	// pull in pages to duplicate to
	$nPageIDARRAY = array();
	foreach($_POST AS $key => $val){
		$nKeyARRAY = explode("_",$key);
		if($nKeyARRAY[0]=="nDupToPageID" && $nKeyARRAY[1]){ $nPageIDARRAY[] = $nKeyARRAY[1]; }
	}
	$nRecID = $_POST["id"]; // component record to duplicate
	$nComponentID = $_POST["nComponentID"];
	$nColumnID = $_POST["nColumnID"];
	$nContentID = $_POST["nContentID"];
	$nXCompOrderID = $_POST["nXCompOrderID"];
	$nDuplicateType = $_POST["nDupType"];
	foreach($nPageIDARRAY AS $nPageID){
		switch($nDuplicateType){
			case "COPY":
				// Get existing component content data
				$nSQL = "SELECT * FROM nContent WHERE nID='$nContentID' LIMIT 1";
				mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
				if($Row = mysql_fetch_array($Result)){
					$nText = $Row["nText"];
					$nTextarea = $Row["nTextarea"];
					$nImgID = $Row["nImgID"];
					$nLinkID = $Row["nLinkID"];
					$nOrderID = $Row["nOrderID"];
				}
				// Create new row in nContent for this component copy
				$Query = "INSERT INTO nContent (nText,nTextarea,nImgID,nLinkID) VALUES ('$nText','$nTextarea',$nImgID,$nLinkID)";
				mysql_select_db($DBName);
				mysql_query($Query, $Link);
				$nNewContentID = mysql_insert_id(); // gets ID of last created row
				// Create new component
				$Query = "INSERT INTO xComponentPage (nComponentID,nPageID,nColumnID,nContentID,nOrderID) VALUES ('$nComponentID',$nPageID,$nColumnID,$nNewContentID,$nXCompOrderID)";
				mysql_select_db($DBName);
				mysql_query($Query, $Link);
				
				// Copy to additional language fields (default language already saved)
				if($nContentID && count($nActiveLangARRAY)){
					foreach($nActiveLangARRAY as $nLangCode => $nLangName) {
						$nType = "comp";
						$nContentARRAY = nGetSimpleContentARRAY($nContentID,$nLangCode,$nType);
						// if default language is not used, get translation from additional fields
						foreach($nContentARRAY AS $nOrderID => $nContentItemARRAY){
							$nText = addslashes($nContentItemARRAY["nText"]);
							$nTextarea = addslashes($nContentItemARRAY["nTextarea"]);
							$nImgID = $nContentItemARRAY["nImgID"];
							$nLinkID = $nContentItemARRAY["nLinkID"];
							// now save new content
							if($nNewContentID){
								$Query = "INSERT INTO nTranslate (nLang,nItemID,nType,nText,nTextarea,nLinkID,nImgID,nOrderID) VALUES ('$nLangCode','$nNewContentID','$nType','$nText','$nTextarea','$nLinkID','$nImgID','$nOrderID')";
								mysql_select_db($DBName);
								mysql_query($Query, $Link);
							}
						}
					}
				}
				break;
			case "CLONE":
				// Create new component
				$Query = "INSERT INTO xComponentPage (nComponentID,nPageID,nColumnID,nContentID) VALUES ('$nComponentID',$nPageID,$nColumnID,$nContentID)";
				mysql_select_db($DBName);
				mysql_query($Query, $Link);
				break;
		}
	}
	if(count($nPageIDARRAY)>1){
		echo "<div align=\"center\" id=\"buttonBox\"><BR>";
			echo "<strong>"._("Component succesfully duplicated on multiple pages!")."</strong><BR><BR>";
			echo "<input type=\"button\" class=\"button blue\" name=\"nClose\" value=\""._("Close")."\" onClick=\"$.colorbox.close();\" class=\"formCancel\"> ";
		echo "</div>";
		echo "<script>$nRefreshCall $.colorbox.resize();</script>";
	} else {
		echo "<div align=\"center\" id=\"buttonBox\"><BR>";
			echo "<strong>"._("Component has been succesfully duplicated!")."</strong><BR><BR>";
			echo _("What do you want to do next?")."<BR><BR>";
			// If the page you duplicated to isn't the same as the one you're working on...
			if($nPageIDARRAY[0]!=$nPageID){ echo "<input type=\"button\" class=\"button blue\" name=\"nEdit\" value=\""._("Go to Duplicate")."\" onClick=\"document.location.href='page_edit.php?id=".$nPageIDARRAY[0]."'\" class=\"formSubmit\"> "; }
			echo "<input type=\"button\" class=\"button\" name=\"nClose\" value=\""._("Close")."\" onClick=\"$.colorbox.close();\" class=\"formCancel\"> ";
		echo "</div>";
		echo "<script>$nRefreshCall $.colorbox.resize();</script>";
	}
} else {
	echo $nFormToDisplay;
	echo "<script>$.colorbox.resize();</script>";
}
?>
</div>
<script>
refreshParentsCompAdd = function(){
	try{ refreshPageComps(); } catch(e){ }
	try{ refreshMobileComps(); } catch(e){ }
}
</script>
<?php
function nGetColumnARRAY(){
	global $nOpenerTag,$nCloserTag,$nTagParamDelim,$nTagSubParamDelim,$nThemePath,$nAllowMobile;
	global $nPageID;
	if(!$nPageID){ return; }
	$nDataARRAY = array();
	$nCurrentTheme = nGetActiveThemePath();
	$nTmplLayoutPath = "../../tmpl/{$nCurrentTheme}layouts/";
	// Set template file
	$nType = nGetPageType($nPageID);
	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 nGetSimpleContentARRAY($nContentID,$nTranslateLang="",$nType="comp"){
	global $DBName,$Link,$nDefaultLang,$nSFLang;
	if(!$nContentID || !is_numeric($nContentID)){ return; }
	if(!$nTranslateLang){ $nTranslateLang = $nSFLang; }
	$nContentARRAY = array();
	$Query = "SELECT * FROM nTranslate WHERE nItemID='$nContentID' AND nLang='$nTranslateLang' AND nType='$nType'";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	while($Row = mysql_fetch_array($Result)) {
		$nOrderID = $Row["nOrderID"];
		$nContentCompARRAY = array();
		$nContentCompARRAY["nText"] = stripslashes($Row["nText"]);
		$nContentCompARRAY["nTextarea"] = stripslashes($Row["nTextarea"]);
		$nContentCompARRAY["nLinkID"] = stripslashes($Row["nLinkID"]);
		$nContentCompARRAY["nImgID"] = $Row["nImgID"];
		// Add to main array
		$nContentARRAY[$nOrderID] = $nContentCompARRAY;
	}
	return $nContentARRAY;
}

function nGetPageARRAY(){
	global $DBName,$Link;
	global $nRecID;
	$nDataARRAY = array();
	$nSQL = "SELECT nID,nNavTitle FROM nPage WHERE nType!='Link' ORDER BY nType,nSectionID,nOrderID";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	while($Row = mysql_fetch_array($Result)){
		$nID = $Row["nID"];
		$nNavTitle = $Row["nNavTitle"];
		$nDataARRAY["nDupToPageID_$nID"] = "$nNavTitle<BR>";
	}
	return $nDataARRAY;
}

function nGetNextCompNum(){
	global $DBName,$Link;
	$nSQL = "SELECT Max(nID) AS nID FROM xComponentPage";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nID = $Row["nID"] + 1;
	}
	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;
}
// returns array of active front-end languages in alpha order, default will be first item in list 
function nGetLangActiveARRAY(){
	global $nDefaultLang;
	$nDefaultLangARRAY = array();
	$nLangARRAY = 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($nFileCode == $nDefaultLang){
				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);
	return $nLangARRAY;
}
?>
<?php require("../../inc/db_close.php"); ?>
