<?
/*
 * 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/plugins.php - version 1.0
*/

$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");

$nPluginPath = "../../plugins/";
$nDEBUG = false;

// Get all new plugins and import them into the database
nImportNewPlugins();

// Clean out plugins that exist in database but not found in Plugins folder
nCleanDiscardedPlugins();

// Incoming messsages
$nMessage = (isset($_GET["msg"]) ? $_GET["msg"] : NULL);
$nMsgType = (isset($_GET["t"]) ? $_GET["t"] : NULL);
switch($nMsgType){
	case "neg": $nMsgClass="bgRed"; break;
	case "mod": $nMsgClass="bgBlue"; break;
	default: $nMsgClass="bgGreen";
}

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

// Setup header
$nColumnARRAY = array();
//$nColumnARRAY["#Checkbox#"] = array("","","","vertical-align:middle;","{ \"sWidth\":\"31\", \"bSortable\":false }");
$nColumnARRAY[ _("Plugin Name") ] = array("","","","","");
$nColumnARRAY[ _("Version") ] = array("","","","","");
$nColumnARRAY[ _("Author") ] = array("","","","","");
$nColumnARRAY[ _("Available Components") ] = array("","","","","");
$nColumnARRAY[ _("Active?") ] = 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;">
	<?=nGetPlugins()?>
</form>

<?
function nGetPlugins(){
	global $DBName,$Link,$nParam,$nPluginListInclARRAY,$nColumnARRAY;
	
	$Query = "SELECT * FROM nPlugins";
	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"];
			$nPluginID = $Row["nPluginID"];
			$nPluginName = $Row["nName"];
			$nPluginDesc = $Row["nDesc"];
			$nPluginAuthor = $Row["nAuthor"];
			$nPluginURL = $Row["nURL"];
			$nPluginAuthorURL = $Row["nAuthorURL"];
			$nPluginVersion = $Row["nVersion"];
			$nPluginActive = $Row["nActive"];
			
			// Format data
			$nEditText = _("Edit");
			$nEnableText = _("Enable");
			$nDisableText = _("Disable");
			$nDisabledText = _("Disabled");
			$nEditItemText = _("Edit Component");
			$nToggleItemText = _("Toggle Component");
			
			if($nPluginAuthor && $nPluginAuthorURL){ $nPluginAuthor="<a href=\"http://$nPluginAuthorURL\" target=\"_blank\">$nPluginAuthor</a>"; }
			$nAuthorTextARRAY = array();
			if($nPluginAuthor){ $nAuthorTextARRAY[] = "$nPluginAuthor"; }
			if($nPluginURL){ $nAuthorTextARRAY[] = "(<a href=\"http://$nPluginURL\" target=\"_blank\">"._("plugin website")."</a>)"; }
			$nAuthorText = implode(" ",$nAuthorTextARRAY);
			if($nAuthorText){ $nAuthorText="$nAuthorText<BR>"; }
			if($nPluginActive){
				if(nPluginHasSettings($nPluginID)){ $nSettingsLink = "<a href=\"plugin_settings.php?id=$nID\">"._("Settings")."</a>"; }
				$nDeactivateLink = "<a href=\"plugins.php?dact=$nID\" style=\"color:#777;\">"._("Deactivate")."</a>";
				$nEditLinks = "$nSettingsLink - $nDeactivateLink";
				$nComponentsARRAY = nGetAvailComponentsARRAY($nPluginID);
				$nComponents = implode(", ",$nComponentsARRAY);
				$nActive = _("Active");
			} else {
				$nActivateLink = "<a class=\"modal edit\" href=\"dialog/plugin_activate.php?id=$nID\" title=\""._("Activate Plugin").": $nPluginName\">"._("Activate")."</a>";
				$nDeleteLink = "<a href=\"javascript:;\" onClick=\"openDeleteDialog('plugin',$nID,'Delete Plugin');\" style=\"color:#777;\" title=\""._("Delete Plugin").": $nPluginName\">"._("Delete")."</a>";
				$nEditLinks = "$nActivateLink - $nDeleteLink";
				$nComponents = "";
				$nActive="<span style=\"color:#AA0000;\">$nDisabledText</span>";
			}
			$nDesc = strip_tags($nPluginDesc);
			if(!$nPluginName){ $nPluginName="<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[ _("Plugin Name") ] = array("<span rel=\"tooltips\" data-original-title=\"$nDesc\"><strong>$nPluginName</strong></span>","","","","");
			$nColumnARRAY[ _("Version") ] = array("$nPluginVersion","","","","text-align:center;");
			$nColumnARRAY[ _("Author") ] = array("$nAuthorText","","","","");
			$nColumnARRAY[ _("Available Components") ] = array("$nComponents","","","","");
			$nColumnARRAY[ _("Active?") ] = array("$nPluginActive","","","","text-align:center;");
			$nColumnARRAY[ _("Actions") ] = array("$nEditLinks","","","","");
			
			// 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 nGetAvailComponentsARRAY($nPluginID){
	global $DBName,$Link;
	if(!$nPluginID){ return false; }
	$nCompCodeARRAY = array();
	$nSQL = "SELECT nCompCode FROM nPluginComp WHERE nPluginID='$nPluginID' AND NOT nCompCode=''";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	while($Row = mysql_fetch_array($Result)){
		$nCompCodeARRAY[] = "[#".$Row["nCompCode"]."#]";
	}
	return $nCompCodeARRAY;
}

function nImportNewPlugins(){
	global $DBName,$Link;
	global $nPluginPath, $nDEBUG;
	// Get all folders in Plugins directory
	$nTable = "";
	$dir_handle = @opendir($nPluginPath) or die("Unable to open Plugin path: $nPluginPath");
	while ($file = readdir($dir_handle)) {
		if($file == "." || $file == ".." || $file == "index.php" )
			continue;
		if(is_dir("$nPluginPath$file/")){
			if($nDEBUG){ echo "<BR>Found folder in plugins directory: $file<BR>"; }
			$nFolderName="$file";
			$nFolderPath="$nPluginPath$file/";
			$nMasterFilePath = "$nPluginPath$file/$file.php";
			if(file_exists("$nMasterFilePath")){ // looking for {folder:plugin_name}/{file:plugin_name}.php (ex: myplugin/myplugin.php)
				if($nDEBUG){ echo "Valid master file found ($nMasterFilePath)<BR>"; }
				$nPluginID = "$file";
				if(!nGetPluginNameFromID($nPluginID)){ // if plugin doesn't already exist in DB (no name exists), add it
					if($nDEBUG){ echo "Plugin NOT currently installed ($nPluginID).  Installing...<BR>"; }
					// Pull in plugin master file
					$nDBConnFile = fopen($nMasterFilePath,"r");
					if($nDBConnFile){
						$nFileCode = fread($nDBConnFile,filesize($nMasterFilePath));
						fclose($nDBConnFile);
					} else {
						return 0;
					}
					if($nDEBUG){ echo "Pulled in master file ($nMasterFilePath) for plugin '$nPluginID'<BR>"; }
					// Separate by line and pull in lines 4-9 which contain general plugin info (after a small validity check)
					$nFileCodeARRAY = explode("\n",$nFileCode);
					
					// it'd be nice to put a check to see if plugin causes a fatal error here
					
					if(strpos($nFileCodeARRAY[2],"nPluginName")){ eval($nFileCodeARRAY[2]); }
					if(strpos($nFileCodeARRAY[3],"nPluginAuthor")){ eval($nFileCodeARRAY[3]); }
					if(strpos($nFileCodeARRAY[4],"nPluginDescription")){ eval($nFileCodeARRAY[4]); }
					if(strpos($nFileCodeARRAY[5],"nPluginVersion")){ eval($nFileCodeARRAY[5]); }
					if(strpos($nFileCodeARRAY[6],"nPluginURL")){ eval($nFileCodeARRAY[6]); }
					if(strpos($nFileCodeARRAY[7],"nPluginAuthorURL")){ eval($nFileCodeARRAY[7]); }
					if($nDEBUG){ echo "Line check (2) on master file ($nMasterFilePath) for plugin '$nPluginID': ".$nFileCodeARRAY[2]."<BR>"; }
					
					$nPluginID = nTruncateString(trim($nPluginID),50);
					$nPluginName = addslashes(nTruncateString(trim($nPluginName),50));
					$nPluginAuthor = addslashes(nTruncateString(trim($nPluginAuthor),50));
					$nPluginDescription = addslashes(trim($nPluginDescription));
					$nPluginVersion = nTruncateString(trim($nPluginVersion),16);
					$nPluginURL = nTruncateString(trim($nPluginURL),255);
					$nPluginAuthorURL = nTruncateString(trim($nPluginAuthorURL),255);
					
					// Add plugin to database un-activated if all tests passed
					if($nPluginName && $nPluginAuthor && $nPluginDescription && $nPluginVersion){
						$Query = "INSERT INTO nPlugins VALUES ('0','$nPluginID','$nPluginName','$nPluginDescription','$nPluginAuthor','$nPluginURL','$nPluginAuthorURL','$nPluginVersion','0')";
						mysql_select_db($DBName);
						mysql_query($Query, $Link);
						if($nDEBUG){ echo "Plugin '$nPluginID' successfully added to database.<BR>"; }
					} else { if($nDEBUG){ echo "Plugin '$nPluginID' NOT added to database! Missing one of these 4 variables -- nPluginName:$nPluginName, nPluginAuthor:$nPluginAuthor, nPluginDescription:$nPluginDescription, nPluginVersion:$nPluginVersion<BR>"; } }
					
					/* check to see if it returns anything
					if ((include "$nPluginPath$file/$file.php") == "") {
	    				print "file is empty except for PHP.<BR>";
					} else {
						print "file has some HTML or characters in it.<BR>";
					}*/
				}
			} else { if($nDEBUG){ echo "Plugin MISSING valid master file: $nMasterFilePath ... not installing!<BR>"; } }
		}
	}
	closedir($dir_handle);
	// $nTable = str_replace("[nTotal]",($nCount-1),$nTable);
	
	return $nTable;
}
function nCleanDiscardedPlugins(){
	global $DBName,$Link;
	global $nPluginPath;
	$dir_handle = @opendir($nPluginPath) or die("Unable to open Plugin path: $nPluginPath");
	$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 = "$nPluginPath$nPluginID/$nPluginID.php";
		if(!is_dir("$nPluginPath$nPluginID/") || !file_exists("$nMasterFilePath")){
			nDeletePlugin($nPluginID);
		}
	}
	closedir($dir_handle);
	return;
}
function nDeletePlugin($nPluginID){
	global $DBName,$Link;
	global $nPluginPath;
	if(!$nPluginID){ return; }
	$nMasterPluginPath = "$nPluginPath$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);
	}
}
function nGetPluginNameFromID($nPluginID){
	global $DBName, $Link;
	if(!$nPluginID){ return; }
	$nPluginName = "";
	$Query = "SELECT nName FROM nPlugins WHERE nPluginID='$nPluginID'";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	$nCurrentRecord = 0;
	while ($Row = mysql_fetch_array($Result)) {
		$nPluginName = $Row["nName"];
	}
	return $nPluginName;
}
function nPluginHasSettings($nPluginID){
	global $DBName, $Link;
	if(!$nPluginID){ return; }
	$nSQL = "SELECT nFunction FROM nPluginSettingsForm WHERE nPluginID='$nPluginID' LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nFunction = $Row["nFunction"];
		if($nFunction){ return true; }
	}
	return false;
}
function nGetPluginIDFromNum($nPluginNum){
	global $DBName, $Link;
	if(!$nPluginNum){ return; }
	$Query = "SELECT nPluginID FROM nPlugins WHERE nID='$nPluginNum'";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	$nCurrentRecord = 0;
	while ($Row = mysql_fetch_array($Result)) {
		$nPluginID = $Row["nPluginID"];
	}
	return $nPluginID;
}
function nTruncateString($nStr,$nMax){
  if(strlen($nStr)>$nMax) {
    $leave = $max - strlen($rep);
    return substr($nStr,0,$nMax);
  }
  return $nStr;
}
?>
<?
// disconnect from mysql
mysql_close($Link);
?>