<?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/list/images.php - version 1.0a
*/

// This file requires the following functions be declared by the caller:
// choiceSave('$nPath','$nRelID','$nType');
// editImage('$nID');
// unlinkImage('$nID');
// deleteImage('$nID');

$nSecureMe=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/pageutil.php");
include("../inc/paginator.php");
include("../inc/calendar.php");
require("../inc/imgedit_gd.php");
include_once("../inc/imageedit_gd_class.php");

$nShowPerPg = 999;

// 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; }
if(isset($_POST["nPostProcess"])){ $nPostProcess = $_POST["nPostProcess"]; } else { $nPostProcess = ""; }

if(isset($_GET["t"])){ $nType = $_GET["t"]; } else { $nType = ""; }
//if(!$nType){ $nType = "Content"; }
$nRelID = (isset($_GET["id"]) ? $_GET["id"] : NULL); // ID to save choice to for "c" mode
$nScroll = (isset($_GET["s"]) ? $_GET["s"] : NULL); // Toggle list scrolling (for use in dialogs)

if(isset($_GET["div"])){ $nParentDiv = $_GET["div"]; } else { $nParentDiv = ""; }
$nShowImgOverride = (isset($_GET["show"]) ? $_GET["show"] : NULL); // Toggle list scrolling (for use in dialogs)

// import images from usr folders (catches uploads and completely unlinked images)
nImportNewLibraryImages();

// Globals
$nSortableCreateARRAY = array();
$nSortableARRAY = array();

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

// Special case (product images are stored in one folder, "prod", but can be of two distinct types, "prdMain" and "Prd"... show both)
if($nType=="Prd" || $nType=="prdMain"){ $nWhereARRAY["nType"] = "(nType='Prd' OR nType='prdMain')"; }

$nWhereSQL = "";
if(isset($nWhereARRAY)){ $nWhereSQL = "WHERE ".implode(" AND ",$nWhereARRAY); } else { $nWhereSQL = ""; }
$nOrderBySQL = "ORDER BY $nSort $nSortOrder";
$nListingSQL = "SELECT * From nImage $nWhereSQL GROUP BY nPath $nOrderBySQL"; // grouping prevents showing duplicates

if($nShowImgOverride){ $nListingSQL = "SELECT * From nImage WHERE nID=$nShowImgOverride"; }

$nPassThru = "?t=$nType&s=$nScroll&id=$nRelID&div=$nParentDiv";

$nDivToUpdate = "imageGallery$nType";
$nPageInDiv = "list/images.php";
$nPagingText = nGetPaging($nListingSQL,$nPage,$nShowPerPg,$nPassThru,$nDivToUpdate,$nPageInDiv);
// for extrenal refresh requests
print "<script>refreshImages = function(){ loadContent('$nDivToUpdate','$nPageInDiv$nPassThru'); }</script>";
?>

<div id="<?php echo $nDivToUpdate;?>" style="margin-top:-18px;">
	<div id="imgFormDiv" style="clear:both; float:none; background:#E8E8E8;padding:8px 10px;"><input name="file_upload" id="file_upload"></div>
	<BR><span id="imageCounter"></span>
	<ul class="gallery" style="padding-bottom:10px;">
		<?php echo nGetImageList();?>
	</ul>
</div>

<script type="text/javascript">
// Handle sorting and order saving
$("<?php if($nSortableARRAY){ echo implode(",",$nSortableARRAY); } ?>").sortable({
	distance: 20,
	update: function(event, ui) {
		var dataString = "group=" + $(this).attr("id") + "&order=" + $(this).sortable('toArray').toString();
		// save updated order
		var url = "edit/image_order.php";
		$.ajax({  
			type: "POST", url: url, data: dataString,  
			error: function(msg,msg2,errorMsg){ alert('error returned in call to '+url+': '+errorMsg); },
			success: function(msg){ }
		});
		$(this).effect("highlight", {}, 1500);
	}
});
var imageCounter = 0;
$('#file_upload').uploadify({
	'buttonText' : '<?php echo _("Upload images"); ?>',
	'uploader'  : 'assets/scripts/uploadify/uploadify.swf',
	'script'    : 'assets/scripts/uploadify/uploadify.php',
	'cancelImg' : 'assets/scripts/uploadify/cancel.png',
	'folder'    : '<?if(PHP_OS == 'WINNT'){ echo str_replace("\\","/","/////".$nSiteRootPath."usr/img/tmp/"); } else { echo "../usr/img/tmp"; }?>',
	'multi'     : true,
	'auto'      : true,
	//'queueSizeLimit' : 10, // for display purposes only
	'checkScript' : 'assets/scripts/uploadify/check.php',
	'onComplete' : function(event, ID, fileObj, response, data) {
		imageSave(fileObj.name,'','<?=$nType?>');
	},
	'onAllComplete' : function() {
		refreshImages();
	}
});
// Handle image saving
imageSave = function(path,id,xType){
	var formData = "rid="+id+"&path="+path+"&t="+xType;
	var loadUrl = "process/image_save.php";
	$('#imageCounter').html(loaderImgS).load(loadUrl, formData, function(response, status, xhr) {
		if(status!="error"){
			if(response == "1"){
				// additional processing, if needed
				imageCounter++;
				//$('#imageCounter').html(imageCounter+" images uploaded.");
				//refreshImages();
			} else { alert("There was an error saving the image: "+response); }
		} else {
			 alert("An error occurred while performing your request: " + xhr.status + " " + xhr.statusText);
		}
	});
	return false;
}
</script>

<?php
function nGetImageList(){
	global $DBName,$Link,$nListingSQL;
	global $nShowPerPg,$nTotalRec,$nStartRec,$nEndRec,$nTotalPg,$nType,$nParentDiv;
	global $nSortableCreateARRAY,$nSortableARRAY,$nScroll,$nRelID;
	if(!$nListingSQL){ return ""; }
	$nTable = "";
	$nTypeIDName = str_replace(" ","--",$nType);
	$nCurrRec = 0;
	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"];
			$nPath = $Row["nPath"];
			$nTitle = $Row["nTitle"];
			$nCaption = $Row["nCaption"];
			$nFilename = nGetImageNameFromPath($nPath);
			$nImgTag = "<img src=\"../$nPath\" alt=\"\" height=\"121\" border=\"0\">";
			if(file_exists("../../$nPath")){
				$nFilesize = filesize("../../$nPath");
				if($nFilesize){ $nFilesize = number_format(($nFilesize/1000),0,'.',''); }
				$nImgSizeARRAY = getimagesize("../../$nPath");
				$nImgW = $nImgSizeARRAY[0]; $nImgH = $nImgSizeARRAY[1]; $nResizeRatio = $nImgW/100;
				if($nImgH<121){ $nImgTag = "<img src=\"../$nPath\" alt=\"\" width=\"$nImgW\" height=\"$nImgH\" border=\"0\">"; }
				//if($nResizeRatio && ($nImgH/$nResizeRatio)>100){ $nImgTag = "<div style=\"overflow:hidden; height:121px; width:121px; vertical-align:middle;\">$nImgTag</div>"; }
			}
			if(!$nTitle){ $nTitle = $nFilename; }
			$nImageLink = "$nImgTag";
			$nHandle = "<td colspan=\"3\" id=\"galleryInfo\" class=\"handleComp\" style=\"width:100px\">&nbsp; &nbsp;$nTitle</td>";
			$nEdit = "<li class=\"edit\"><a href=\"javascript:;\" onClick=\"editImage('$nID');\" class=\"btn\">Edit</a></li>";
			$nDelete = "<li class=\"delete\"><a href=\"javascript:;\" onClick=\"deleteImage('$nID');\" class=\"btn\">Delete</a></li>";
			$nTable.= <<<CODE
			<li id="libimg_$nID">
			    $nImageLink
			    <ul class="img_options">$nEdit $nDelete </ul>
			</li>
CODE;
		}
	}
	if(!$nTable){
		$nTable = "<table width=\"100%\"><tr><td height=\"200\" align=\"center\" class=\"caption\" colspan=\"5\"><em>No images available in this library.</em></td></tr></table>";
	} else {
		if($nScroll){
			$nTable = "<div id=\"libImages_$nTypeIDName\" style=\"height:460px; overflow:scroll;\">$nTable</div>";
		} else {
			$nTable = "<div id=\"libImages_$nTypeIDName\">$nTable</div>";
		}
	}
	// Create sortable
	$nSortableARRAY[] = "#libImages_$nTypeIDName";
	
	return $nTable;
}

function nGetImageNameFromPath($nPath){
	if(!$nPath){ return; }
	$nPathARRAY = explode("/",$nPath);
	$nImgName = $nPathARRAY[(count($nPathARRAY)-1)];
	return $nImgName;
}

function nGetSectionName($nRecID){
	global $DBName,$Link;
	$nSQL = "SELECT nName,nParentID FROM nSection WHERE nID='$nRecID' LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nName = $Row["nName"];
		$nParentID = $Row["nParentID"];
	}
	if($nParentID){ $nParentName = nGetSectionName($nParentID)." &gt; "; } else { $nParentName = ""; }
	return "$nParentName$nName";
}

function nSectionExists($nSectionID){
	global $DBName,$Link;
	if(!$nSectionID){ return 0; }
	$nSQL = "SELECT nID FROM nSection WHERE nID=$nSectionID";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	$nCount = mysql_num_rows($Result);
	return $nCount;
}
function nGetPageIDAccessARRAY($ValidUser){
	global $DBName,$Link;
	if(!$ValidUser){ return; }
	// Get user ID
	$nSQL = "SELECT nID FROM nEditor WHERE nUser='$ValidUser' LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nEditorID = $Row["nID"];
	}
	$nDataARRAY = array();
	$nSQL = "SELECT nPageID FROM xEditorPage WHERE nEditorID=$nEditorID";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	while($Row = mysql_fetch_array($Result)){
		$nPageID = $Row["nPageID"];
		$nDataARRAY[] = $nPageID;
	}
	return $nDataARRAY;
}
function nImportNewLibraryImages(){
	global $DBName,$Link;
	
	$nImgFolderARRAY = array();
	// Build array of folders to search in from library
	$Query = "SELECT nID,nName FROM nLibrary WHERE nType='image'";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	while ($Row = mysql_fetch_array($Result)){
		$nName = $Row["nName"];
		$nImgFolderARRAY[$nName] = "../../usr/img/".strtolower($nName)."/original/"; // only look in this folder for new images
	}
	// Search each folder
	foreach($nImgFolderARRAY AS $nImgFolderTag => $nImgFolderPath){
		// Get all files in directory
		$dir_handle = @opendir($nImgFolderPath);
		if($dir_handle){
			while ($file = readdir($dir_handle)) {
				if($file == "." || $file == ".." || $file == "index.php" )
					continue;
				if(!is_dir("$nImgFolderPath$file")){
					$nRealImgFolderPath = str_replace("../","",$nImgFolderPath);
					$nImgID = nGetImgIDFromPath("$nRealImgFolderPath$file"); // check to see if already exists
					if(!$nImgID){
						$Query = "INSERT INTO nImage (nID,nPath,nType,nOrderID) VALUES ('','$nRealImgFolderPath$file','$nImgFolderTag','1')";
						mysql_select_db($DBName);
						mysql_query($Query, $Link);
					}
				}
			}
			closedir($dir_handle);
		}
	}
}
function nGetImgIDFromPath($nPath){
	global $DBName, $Link;
	if(!$nPath){ return; }
	$nID = "";
	$Query = "SELECT nID FROM nImage WHERE nPath='$nPath'";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	while ($Row = mysql_fetch_array($Result)) {
		$nID = $Row["nID"];
	}
	return $nID;
}
?>
<?php require("../../inc/db_close.php"); ?>
