<?
/*
 * 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/tables/components.php - version 1.01
*/

$nAdminOnlyPg = 1;

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

// bring in other required files
require("../../inc/config.php");
require("../inc/lang.php");
require("../inc/plugins.php");
require("../inc/pluginutil.php");
require("../inc/pageutil.php");
require("../inc/calendar.php");

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

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

// Clean out components that exist in database but not found in "comp" folder
////nCleanDiscardedComps();

// Get plugin inclusion points for list, and insert them in header
$nPluginListInclARRAY = nGetListPluginInclusions("Components");

// Setup header
$nColumnARRAY = array();
//$nColumnARRAY["#Checkbox#"] = array("","","","vertical-align:middle;","{ \"sWidth\":\"31\", \"bSortable\":false }");
$nColumnARRAY[ _("Component Name") ] = array("","","","","");
$nColumnARRAY[ _("Base File") ] = array("","","","","");
$nColumnARRAY[ _("Page Limit") ] = array("","","","","");
$nColumnARRAY[ _("Active?") ] = array("","","","","");
$nColumnARRAY[ _("Usage") ] = array("","","","","");
$nColumnARRAY[ _("Actions") ] = array("","","","","{ \"bSortable\":false }");

// Insert plugin inclusion points for list in header
$nColumnARRAY = nInsertPluginHdrIncl($nPluginListInclARRAY,$nColumnARRAY);
$nHeaderDataTableJS = nBuildHeaderDataTableJS($nColumnARRAY);
?>
<script>
	$(function() {
	    // Initialize tables (if more than one per page, give it a second class for customization)
	    $('.dataTable').dataTable({
	        "sPaginationType": "full_numbers",
	        "bJQueryUI": true,
			"bStateSave": true,
			"aaSorting": [[ 0, "asc" ]],
			"aoColumns": [
				<?=$nHeaderDataTableJS;?>
			],
			"iDisplayLength": 20,
			"aLengthMenu": [[20, 50, 100, 200, -1], [20, 50, 100, 200, "All"]],
			"fnDrawCallback":function(){
				// Hide toolbar if showing less records than page-able
				if(this.fnSettings().fnRecordsTotal() <= this.fnSettings()._iDisplayLength){
					$('.dataTables_wrapper div.fg-toolbar').hide();
					$('.dataTables_wrapper').addClass("topBorder bottomBorder");
				} else {
					$('.dataTables_wrapper div.fg-toolbar').show();
				}
			}
	    });
	});
</script>

<form action="javascript:;" method="post" name="nListForm" id="nListForm" style="margin:0px;">
	<?=nGetComponents()?>
</form>

<?
function nGetComponents(){
	global $DBName,$Link,$nParam,$nPluginListInclARRAY,$nColumnARRAY;
	
	$Query = "SELECT * FROM nComponent";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link); $nNumRec = mysql_num_rows($Result);
	
	$nTable = "";
	$nCurrentRecord = 1;
	
	if($nNumRec){
		// insert header and main listing table
		$nHeaderCode = nBuildHeaderHTML($nColumnARRAY);
		$nTable.="<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"dataTable\">";
		$nTable.="<thead><tr class=\"listHdr\">$nHeaderCode</tr></thead>";
		
		while($Row = mysql_fetch_array($Result)){
			// Get data
			$nID = $Row["nID"];
			$nName = $Row["nName"];
			$nDesc = $Row["nDesc"];
			$nTypeLimit = $Row["nTypeLimit"];
			$nCompFile = $Row["nCompFile"];
			$nActive = $Row["nActive"];
			
			// Format data
			$nEditText = _("Edit");
			$nEnableText = _("Enable");
			$nDisableText = _("Disable");
			$nDisabledText = _("Disabled");
			$nEditItemText = _("Edit Component");
			$nToggleItemText = _("Toggle Component");
			if(!$nTypeLimit){ $nTypeLimitText = "<em>"._("none")."</em>"; } else { $nTypeLimitText = "$nTypeLimit"; }
			$nDesc = strip_tags($nDesc);
			$nPageUsage = nGetPageCount($nID);
			$nPageText = _("pages");
			if($nActive){
				$nActive = _("Active");
				//$nEditCODE = "<a class=\"modal edit\" href=\"dialog/component_files_edit.php?id=$nID\" title=\"$nEditItemText\">$nEditText</a>";
				$nEnableCODE = "<a class=\"modal delete\" href=\"dialog/component_toggle.php?id=$nID\" title=\"$nToggleItemText\">$nDisableText</a>";
			} else {
				$nActive="<span style=\"color:#AA0000;\">$nDisabledText</span>";
				//$nEditCODE = "<a class=\"modal edit\" href=\"dialog/component_files_edit.php?id=$nID\" title=\$nEditItemText\">$nEditText</a>";
				$nEnableCODE = "<a class=\"modal approve\" href=\"dialog/component_toggle.php?id=$nID\" title=\"$nToggleItemText\">$nEnableText</a>";
			}
			if(!$nName){ $nName="<span class=\"caption\"><em>&lt;"._("unnamed")."&gt;</em></span>"; }
			
			// Setup row (data, width, align, class, style)
			$nColumnARRAY = array();
			//$nColumnARRAY["#Checkbox#"] = array("<input type=\"checkbox\" name=\"item_$nCurrentRecord\" value=\"$nID\" onClick=\"updateItemText();\">","","","","");
			$nColumnARRAY[ _("Component Name") ] = array("<span rel=\"tooltips\" data-original-title=\"$nDesc\">$nName</span>","","","","");
			$nColumnARRAY[ _("Base File") ] = array("$nCompFile","","","","");
			$nColumnARRAY[ _("Page Limit") ] = array("$nTypeLimitText","","","","");
			$nColumnARRAY[ _("Active?") ] = array("$nActive","","","","");
			$nColumnARRAY[ _("Usage") ] = array("$nPageUsage $nPageText","","","","");
			$nColumnARRAY[ _("Actions") ] = array("$nEnableCODE","","","","");
			
			// Get plugin inclusion points for list, and insert them in row
			$nColumnARRAY = nInsertPluginRowIncl($nPluginListInclARRAY,$nColumnARRAY,$nID);
			$nRowCode = nBuildRowHTML($nColumnARRAY);
			
			// Insert row
			$nTable.="<tr id=\"row$nID\">$nRowCode</tr>";
			$nCurrentRecord++;
		}
		// Insert footer
		//$nTable.= "</table>".nGetActionFooter()."<BR><BR>";
	} else {
		$nTable.= "<div style=\"text-align:center; padding:50px 0;\"><em>"._("No data available to display.")."</em></div>";
	}
	return $nTable;
}
function nGetActionFooter(){
	$nFooter = "<div style=\"padding:8px;\">\n";
	$nFooter.= "	<strong>With <strong id=\"itemAmount\">0</strong> items selected:</strong> \n";
	$nFooter.= "	<input type=\"button\" name=\"nRemove\" id=\"nRemove\" value=\" Remove \" onClick=\"editList('usr','remove');\" disabled> \n";
	$nFooter.= "	<input type=\"button\" name=\"nEdit\" id=\"nEdit\" value=\" Edit \" onClick=\"editList('usr','edit');\" disabled>\n";
	$nFooter.= "</div>\n";
	return $nFooter;
}

function nGetPageCount($nCompID){
	global $DBName,$Link;
	if($nCompID===""){ return 0; }
	$nNumRecords = 0;
	$nSQL = "SELECT nPageID FROM xComponentPage WHERE nComponentID='$nCompID' GROUP BY nPageID";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	$nNumRecords = mysql_num_rows($Result);
	return $nNumRecords;
}

// 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 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 = nGetCompIDFromTemplateFile($nFileName);
					//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);
						}
					} else {
						// If component already exists, just update the description and name (just in case default language is different or component had a recent update)
						$nName = addslashes(stripslashes($nName));
						$nDescription = addslashes(stripslashes($nDescription));
						$Query = "UPDATE nComponent SET nName='$nName', nDesc='$nDescription' WHERE nID='$nCompID'";
						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 nGetCompIDFromTemplateFile($nCompTmplFile){
	global $DBName, $Link;
	if(!$nCompTmplFile){ return; }
	$nID = "";
	$Query = "SELECT nID FROM nComponent WHERE nCompFile='$nCompTmplFile'";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	while ($Row = mysql_fetch_array($Result)) {
		$nID = $Row["nID"];
	}
	return $nID;
}
function nCleanDiscardedComps(){
	global $DBName,$Link;
	global $nCompPath;
	$dir_handle = @opendir($nCompPath) or die("Unable to open Component path: $nCompPath");
	$Query = "SELECT nPluginID FROM nPlugins";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	$nCurrentRecord = 0;
	while ($Row = mysql_fetch_array($Result)) {
		$nPluginID = $Row["nPluginID"];
		$nMasterFilePath = "$nCompPath$nPluginID/$nPluginID.php";
		if(!is_dir("$nCompPath$nPluginID/") || !file_exists("$nMasterFilePath")){
			nDeletePlugin($nPluginID);
		}
	}
	closedir($dir_handle);
	return;
}
function nDeletePlugin($nPluginID){
	global $DBName,$Link;
	global $nCompPath;
	if(!$nPluginID){ return; }
	$nMasterPluginPath = "$nCompPath$nPluginID/";
	// Remove folder
	if(is_dir("$nMasterPluginPath")){ nRecursiveDelete("$nMasterPluginPath"); }
	// Remove record
	$Query = "DELETE FROM nPlugins WHERE nPluginID='$nPluginID' LIMIT 1";
	mysql_select_db($DBName);
	mysql_query($Query, $Link);
	// Remove all associated databases
	mysql_select_db($DBName);
	$Query = "SHOW TABLES FROM $DBName";
	$result = mysql_query($Query);
	while ($Row = mysql_fetch_row($result)) {
	    $nTableName = $Row[0];
		$pos = strpos($nTableName, $nPluginID);
		if($pos !== false){
			// Remove record
			$Query = "DROP TABLE IF EXISTS $nTableName";
			mysql_select_db($DBName);
			mysql_query($Query, $Link);
		}
	}
	// REMOVE all associated navigation items
	$Query = "DELETE FROM nPluginNav WHERE nPluginID='$nPluginID'";
	mysql_select_db($DBName);
	mysql_query($Query, $Link);
	// REMOVE all associated inclusion points
	$Query = "DELETE FROM nPluginInclusionPoint WHERE nPluginID='$nPluginID'";
	mysql_select_db($DBName);
	mysql_query($Query, $Link);
}
function nRecursiveDelete($str){
	if(is_file($str)){
		return @unlink($str);
	} elseif(is_dir($str)){
		$scan = glob(rtrim($str,'/').'/*');
		foreach($scan as $index=>$path){
			nRecursiveDelete($path);
		}
		return @rmdir($str);
	}
}
?>
<?
// disconnect from mysql
mysql_close($Link);
?>