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

// This file requires the following functions be declared by the caller:
// choiceSave('id','fld');

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

// Get passed-in vars
if(isset($_GET["t"])){ $nType = $_GET["t"]; } else { $nType = ""; }
if(isset($_GET["fld"])){ $nFieldToUpdate = $_GET["fld"]; } else { $nFieldToUpdate = ""; }
if(isset($_GET["filter"])){ $nTypeFilter = $_GET["filter"]; } else { $nTypeFilter = ""; }
if(isset($_GET["refreshJS"])){ $nRefreshJS = $_GET["refreshJS"]; } else { $nRefreshJS = ""; }

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

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

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

$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

$nPassThru = "?fld=$nFieldToUpdate&filter=$nTypeFilter"; // for refresh calls
$nPage = 1;
$nShowPerPg = 999;
$nDivToUpdate = "imageGallery";
$nPageInDiv = "list/images_choose.php";

$nPagingText = nGetPaging($nListingSQL,$nPage,$nShowPerPg,$nPassThru,$nDivToUpdate,$nPageInDiv);
// for extrenal refresh requests
print "<script>refreshImages = function(){ loadContent('$nDivToUpdate','$nPageInDiv$nPassThru&refreshJS=0'); }</script>";

// defaults
if($nRefreshJS!=="0"){ $nRefreshJS = 1; }
?>

<ul id="<?php echo $nDivToUpdate;?>" class="gallery" style="width:800px; padding-bottom:10px;">
	<?php echo nGetImageList();?>
</ul>

<?php
if($nRefreshJS){
?>
<script type="text/javascript">
var uploadifyActive = 0;
var imageCounter = 0;
toggleUploadBox = function(){
	$('#buttonBox').toggle('slow');
	$('#imgFormDiv').toggle('slow');
	// Uploadify
	if(!uploadifyActive){
		$('#file_upload').uploadify({
			'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,'','<?=$nTypeFilter?>');
			},
			'onAllComplete' : function() {
				//alert('all files uploaded');
				//refreshImages();
			}
		});
		uploadifyActive = 1;
	}
}
// 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>

	<div id="buttonBox" style="position:absolute; width:100%; bottom:0; background:#E8E8E8;padding:20px 14px;">
		<a href="javascript:;" title="Add New Image" onClick="toggleUploadBox();" class="button blue">Upload a new image</a> 
		<a href="javascript:;" onClick="choiceSave('','<?php echo $nFieldToUpdate; ?>');" title="No image" class="button">Don't use an image</a>
	</div>
	<div id="imgFormDiv" style="position:absolute; width:100%; bottom:0; background:#E8E8E8;padding:20px 14px; display:none;">
		<table style="width: auto;">
			<tr style="background-color:transparent;">
				<td style="vertical-align:bottom;"><?php echo _("Choose image(s) to upload:"); ?></td>
				<td><input id="file_upload" name="file_upload" class="file_upload" /></td>
				<td style="vertical-align:bottom;" id="imageCounter"></td>
			</tr>
		</table>
		<BR><BR>
		<a href="javascript:;" title="Close" onClick="toggleUploadBox();" class="button"><?php echo _("I'm finished uploading"); ?></a>
	</div>
<?php
}
?>
	
<?php
function nGetImageList(){
	global $DBName,$Link,$nListingSQL;
	global $nShowPerPg,$nTotalRec,$nStartRec,$nEndRec,$nTotalPg,$nTypeFilter,$nFieldToUpdate;
	global $nSortableCreateARRAY,$nSortableARRAY;
	if(!$nListingSQL){ return ""; }
	$nTable = "";
	$nTypeFilterIDName = str_replace(" ","--",$nTypeFilter);
	$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 = "<a href=\"javascript:;\" onClick=\"choiceSave('$nID','$nFieldToUpdate');\" title=\"Choose This Image\">$nImgTag</a>";
			$nHandle = "<td colspan=\"4\" id=\"galleryInfo\" style=\"width:100px\">&nbsp; &nbsp;$nTitle</td>";
			$nEdit = $nDelete = "";
			
			$nTable.= <<<CODE
			<li id="libimg_$nID">
			    $nImageLink
			    <ul class="img_options">$nEdit $nDelete </ul>
			</li>
CODE;
		}
	}
	if(!$nTable){
		// if inline edit mode, show a "choose image" button, otherwise show a "no images" message
		$nTable = "<table width=\"100%\"><tr><td height=\"460\" align=\"center\" class=\"caption\" colspan=\"5\"><em>No images available in this library.<BR><BR>Click the button below to add a new image.<BR><BR><BR></em></td></tr></table>";
	} else {
		$nTable = "<div id=\"libImages_$nTypeFilterIDName\" style=\"height:460px; overflow:scroll;\">$nTable</div>";
	}
	// Create sortable
	$nSortableARRAY[] = "#libImages_$nTypeFilterIDName";
	
	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"); ?>
