<?php
/*
 * This file is part of Web Pro Manager.
 * 
 * Web Pro Manager is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Web Pro Manager is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Web Pro Manager.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @author The Web Pro Miami, Inc. <info@thewebpro.com>
 * @copyright The Web Pro Miami, Inc. <info@thewebpro.com>, http://www.thewebpro.com/
 * @license http://www.gnu.org/licenses/gpl.html GNU GPL
 * @package WebProManager
*/

require("../inc/stop_cache.php");
$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");
include("../inc/paginator.php");
include("../inc/pageutil.php");
include("../inc/calendar.php");
require("../inc/langutil.php");

$nShowPerPg = 20;

$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 passed-in vars
if(isset($_GET["pg"])){ $nPage = $_GET["pg"]; } else { $nPage = ""; }
if(!$nPage && isset($_POST["pg"])){ $nPage = $_POST["pg"]; }
if(isset($_GET["srt"])){ $nSort = $_GET["srt"]; } else { $nSort = ""; }
if(isset($_GET["ord"])){ $nSortOrder = $_GET["ord"]; } else { $nSortOrder = ""; }
if(isset($_GET["spp"])){ $nShowPerPgOverride = $_GET["spp"]; } else { $nShowPerPgOverride = ""; }
if($nShowPerPgOverride){ $nShowPerPg = $nShowPerPgOverride; }

// Setup SQL query for displayed listing
if(!$nSort){ $nSort="nName"; }  // default sort
if(!$nSortOrder){ $nSortOrder="ASC"; }  // default sort order
// if($nUserID){ $nWhereARRAY[] = "nID='$nUserID'"; }

$nWhereSQL = "";
if(isset($nWhereARRAY)){ $nWhereSQL = "WHERE ".implode(" AND ",$nWhereARRAY); } else { $nWhereSQL = ""; }
$nOrderBySQL = "ORDER BY $nSort $nSortOrder";
$nListingSQL = "SELECT * From nComponent $nWhereSQL $nOrderBySQL";
?>
<div id="listContent" style="padding-top:0px;">
<?php
$nPassThru = "";
$nDivToUpdate = "ajaxComponents";
$nPageInDiv = "list/components.php";
$nCurrQueryStr = $_SERVER['QUERY_STRING'];
if($nCurrQueryStr){ $nFullPageInDiv = $nPageInDiv."?".$nCurrQueryStr; } else { $nFullPageInDiv = $nPageInDiv; }
$nPagingText = nGetPaging($nListingSQL,$nPage,$nShowPerPg,$nPassThru,$nDivToUpdate,$nPageInDiv);
if($nPassThru){ $nPassThruQry="?".$nPassThru; $nPassThru="&".$nPassThru; }
// for extrenal refresh requests
print "<script>refreshComps = function(){ loadContent('".$nDivToUpdate."','".$nFullPageInDiv."'); }</script>";
?>

<!--[if !IE]>start section inner<![endif]-->
<div class="section_inner">
	<!--[if !IE]>start table_wrapper<![endif]-->
	<div class="table_wrapper">
		<div class="table_wrapper_inner">
		<table cellpadding="0" cellspacing="0" width="100%">
			<tbody><tr>
				<th style="width:25px;"><?php echo _("No."); ?></th>
				<?$nSortFld="nName"; if($nSortFld==$nSort){ if($nSortOrder=="ASC"){ $nLink="?srt=$nSortFld&ord=DESC$nPassThru";$nSortClass=" class=\"asc\""; } else { $nLink="?srt=$nSortFld&ord=ASC$nPassThru";$nSortClass=" class=\"desc\""; } } else { $nLink="?srt=$nSortFld&ord=ASC$nPassThru";$nSortClass=""; }?>
				<th><a href="javascript:loadContent('<?php echo $nDivToUpdate?>','<?php echo $nPageInDiv.$nLink?>');"<?php echo $nSortClass;?>><?php echo _("Component Name"); ?></a></th>
				<?$nSortFld="nActive"; if($nSortFld==$nSort){ if($nSortOrder=="ASC"){ $nLink="?srt=$nSortFld&ord=DESC$nPassThru";$nSortClass=" class=\"asc\""; } else { $nLink="?srt=$nSortFld&ord=ASC$nPassThru";$nSortClass=" class=\"desc\""; } } else { $nLink="?srt=$nSortFld&ord=ASC$nPassThru";$nSortClass=""; }?>
				<th width="80" style="text-align:center;"><a href="javascript:loadContent('<?php echo $nDivToUpdate?>','<?php echo $nPageInDiv.$nLink?>');"<?php echo $nSortClass;?>><?php echo _("Active?"); ?></a></th>
				<th width="80" style="text-align:center;"><?php echo _("Usage"); ?></th>
				<th style="width:96px;"><?php echo _("Actions"); ?></th>
			</tr>
			<?php echo nGetCompList();?>
		</tbody></table>
		</div>
	</div>
	<!--[if !IE]>end table_wrapper<![endif]-->
</div>
<!--[if !IE]>end section inner<![endif]-->

<?php if($nTotalPg>1){ ?>
	<!--[if !IE]>start pagination<![endif]-->
	<div class="pagination">
		<?php echo $nPagingText;?>
	</div>
	<!--[if !IE]>end pagination<![endif]-->
<?php } else {?>
	<!--[if !IE]>start pagination<![endif]-->
	<div class="pagination">
		<span class="page_no">&nbsp;</span>
	</div>
	<!--[if !IE]>end pagination<![endif]-->
<?php } ?>


<?php
function nGetCompList(){
	global $DBName,$Link,$nListingSQL;
	global $nShowPerPg,$nTotalRec,$nStartRec,$nEndRec,$nTotalPg;
	if(!$nListingSQL){ return ""; }
	$nCurrRec = 0;
	$nTable = "";
	$nRowClass = "";
	mysql_select_db($DBName); $Result = mysql_query($nListingSQL,$Link);
	while($Row = mysql_fetch_array($Result)){
		$nCurrRec++;
		if($nCurrRec>=$nStartRec && $nCurrRec<=$nEndRec && $nCurrRec<=$nTotalRec){
			$nID = $Row["nID"];
			$nName = $Row["nName"];
			$nActive = $Row["nActive"];
			$nEditText = _("Edit");
			$nEnableText = _("Enable");
			$nDisableText = _("Disable");
			$nDisabledText = _("Disabled");
			$nEditItemText = _("Edit Component");
			$nToggleItemText = _("Toggle Component");
			$nPageUsage = nGetPageCount($nID);
			$nPageText = _("pages");
			if($nActive){
				$nActive = _("Active");
				//$nEditCODE = "<li><a class=\"modal edit\" href=\"dialog/component_files_edit.php?id=$nID\" title=\"$nEditItemText\">$nEditText</a></li>";
				$nEnableCODE = "<li><a class=\"modal delete\" href=\"dialog/component_toggle.php?id=$nID\" title=\"$nToggleItemText\">$nDisableText</a></li>";
			} else {
				$nActive="<span style=\"color:#AA0000;\">$nDisabledText</span>";
				//$nEditCODE = "<li><a class=\"modal edit\" href=\"dialog/component_files_edit.php?id=$nID\" title=\$nEditItemText\">$nEditText</a></li>";
				$nEnableCODE = "<li><a class=\"modal approve\" href=\"dialog/component_toggle.php?id=$nID\" title=\"$nToggleItemText\">$nEnableText</a></li>";
			}
			if(!$nName){ $nName="<span class=\"caption\"><em>&lt;"._("unnamed")."&gt;</em></span>"; }
			if($nRowClass=="second"){ $nRowClass="first"; } else { $nRowClass="second"; }
			$nTable.= <<<CODE
			<tr id="row$nCurrRec" class="$nRowClass" onMouseOver="$('#row$nCurrRec').addClass('rowhilite');" onMouseOut="$('#row$nCurrRec').removeClass('rowhilite');">
				<td>$nCurrRec.</td>
				<td><strong>$nName</strong></td>
				<td align="center" style="text-align: center;">$nActive</td>
				<td align="center" style="text-align:center;">$nPageUsage $nPageText</td>
				<td>
					<div class="actions_menu" style="margin:6px 0;">
						<ul>
							$nEnableCODE
						</ul>
					</div>
				</td>
			</tr>
CODE;
		}
	}
	if(!$nTable){ $nTable = "<tr id=\"$nRowClass\"><td height=\"200\" align=\"center\" class=\"caption\" colspan=\"5\"><em>"._("No data available to display.")."</em></td></tr>"; }
	return $nTable;
}

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);
	}
}
?>
<?php require("../../inc/db_close.php"); ?>
