<?php
$sumfingIncl=true;
$settingsfile=true;
include '../../config.thing.php';
require_once 'thumb/ThumbLib.inc.php';
// Get options
$set = get_adm_opts();
include '../translate.php';
require '../../fb/facebook.php';

$canclose = false;

$token = (isset($_GET['token'])) ? $_GET['token'] : $_POST['token'];
$id = (isset($_GET['id'])) ? $_GET['id'] : $_POST['id'];

   // Init the Facebook SDK
   $facebook = new Facebook(array(
     'appId'  => FB_APPID,
     'secret' => FB_SECRET,
	 'cookie' => true,
   ));

   // Get the current user
   $user = $facebook->getUser();
    
   // If the user is not admin, kill the script
   if (sha1($user) != $token) {
     die( _("Access denied") );//die(ERROR_2);
   }
//string shortener
function truncate ($string, $max = '', $rep = '') {
	if(strlen($string) >= $max) {
		$leave = $max - strlen ($rep);
		return substr_replace($string, $rep, $leave);
	} else
		return $string;
}

$folder = "../../uploads/";
function buildFileList5($theFolder,$folder) {
			//global $folder;
		  if ($contents = @ scandir($theFolder)) {
			$found = array();
			$fileTypes = array('jpg','jpeg','gif','png');
			$found = array();
			foreach ($contents as $item) {
			  $fileInfo = pathinfo($item);
			  if (array_key_exists('extension', $fileInfo) && in_array($fileInfo['extension'],$fileTypes)) {
				$found[] = $item;
				}
			  }
			if ($found) {
			  natcasesort($found);
			  foreach ($found as $filename) {
				  $shorten=$filename;
				  
					$shorten = truncate ($shorten, 14, '...');
				  
					echo "
					<div class='img-polaroid upl_thmb'>
					<img src='".$folder."thumbs/".$filename."' title='".$filename."' title='".$filename."'><br>".$shorten."<br>
					<input type='checkbox' name='".$filename."' value='".$filename."' class='img_check'>
					</div>
					";
					
				}
			  }
			}
}

// File usage part


// FILE deletion part
if(isset($_POST['delete']) && $_SERVER['REQUEST_METHOD'] == "POST") {
	
	if(!isset($_POST['delete_img'])) {
		
		$posted = array_values($_POST);
		$imagetouse = $posted[0];
		$canclose = true;
		
	} else {
	if($_POST['delete'] == 1) {
		
		unset($_POST['delete']);
		$i=0;
		foreach($_POST as $file) {
			
			$noext=explode(".",$file);
			$extensions=array('.jpg','.jpeg','.gif','.png','.bmp','.tiff');
			
			if(!empty($noext[1])) {
				
				unlink($folder.'thumbs/'.$file);
			
				foreach($extensions as $ext) {
					if(file_exists($folder.$noext[0] . $ext)) {			
						
						unlink($folder.$noext[0] . $ext);
						$i++;
					}
				
			    }
			
			
			}
		}
		$deleted = $i;
		
	}
  }
}


// FILEUPLOAD PART
if(isset($_POST['upl']) && $_SERVER['REQUEST_METHOD'] == "POST") {
			$a=1;
			//loop trough uploaded files
			foreach($_FILES as $imgfile) {
				
				//posted file properties
				$file_name = $imgfile['name'];
				
				//check if file is image
				if(!empty($file_name)){
					$size=getimagesize($imgfile['tmp_name']);
					if($size == false) {
						echo $file_name._UPLOAD_WRONG_FORMAT;
					} else {
						
						//upload to directory
						//move_uploaded_file($imgfile['tmp_name'], '../uploads/'.$file_name);
						//get file name without extension
						$justname=explode(".", $file_name);
						$thumb = PhpThumbFactory::create($imgfile['tmp_name']);
						$thumb->save($folder.$justname[0].'.jpg','jpg');
						
						
						//making thumbs
						$thumb = PhpThumbFactory::create($imgfile['tmp_name']);
						$thumb->resize(100, 100);
						$thumb->save($folder.'thumbs/'.$justname[0].'.jpg','jpg');
						
						
					}
				} else {
					echo $a.'* ' . _("Can't save file, I guess it's empty.") . "<br>";
				}
			$a++;
			}
}

//count files in thumb dieectory
$directory = $folder."thumbs/";
if (glob($directory . "*.jpg") != false)
{
 $filecount = count(glob($directory . "*.jpg"));
}

?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo _("Image Uploader");?></title>
<link href="../../bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" media="screen">
<!-- Javascripts -->
<script src="../../bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="../../js/jquery.js" type="text/javascript"></script>

<script type="text/javascript">	

$(document).ready(function() {
	
	$("#moreBtn").click(function() { 
	
		var fileFieldCount = $('input[type="file"]').length;
		var fileFieldPlus = fileFieldCount +1;
		
		$("#inputs").append('<p><input type="file" name="file_' + fileFieldPlus + '"></p>');		
		if(fileFieldPlus == 6)  {
			$('#moreBtn').hide();
		}
		
		});
	
	$("#uploadBtn").click(function() { 
		$("#uploadBtn,#moreBtn").hide();
		$("#loaderimage").fadeIn('slow');
	});
	
	$("#delBtn").click(function() { 
		$("#delBtn").hide();
		$("#loaderdelete").fadeIn('slow');
	});
    
	$("#useBtn").click(function() {
	    var num_check = $(":checkbox:checked").length;
		if(num_check == 0) {
			alert('<?php echo _("No image selected. Can\'t add!");?>');
			return false;
		}
		if(num_check > 1) {
			alert('<?php echo _("You can use only one image at once.");?>');
			return false;
		}
		
		$("#manage_img").submit();
		
	});
	
	<?php if($canclose) {?>
			close_change();		
	<?php }?>
	
}); // doc ready

// Close and change
function close_change() {
	var chng_elem = '<?php echo $id;?>'.split("_");
	var elem_id = "#"+chng_elem[0]+"_thumb";
	window.opener.$(elem_id).attr('src', "uploads/thumbs/<?php echo $imagetouse;?>");
	window.opener.$("#"+chng_elem[0]+"_img_input").html('<input type="hidden" name="<?php echo $id;?>" value="<?php echo $imagetouse;?>">');
	window.close();
}


</script>
<style type="text/css">
.upl_thmb{
	float:left;
	text-align:center;
	font-size:10px;
	height:130px;
	margin:6px;
	padding:3px	
}
</style>
</head>
<body>

<div class="container">

    <div class="span12">
    
    	
        <h3><?php echo _("Manage or Upload images");?></h3>
        
        <form id="imgup" name="uploadform" method="post" action="uploader.php" enctype="multipart/form-data">
            <input type="hidden" name="upl" value="1">
            <input type="hidden" name="token" value="<?php echo $token;?>">
            <input type="hidden" name="id" value="<?php echo $id;?>">
            <span id="inputs">
                <p>
                    <input type="file" name="file_1">
                </p>
            </span>
            <span style="float:left; display:none" id="loaderimage"><img src="barLoader.gif" alt="loading"></span>
            
            <button type="submit" class='button2 btn btn-success btn-small'  id="uploadBtn" data-loading-text="<?php echo _("Loading...");?>">
                <i class="icon icon-upload icon-white"></i>&nbsp;&nbsp;<?php echo _("Upload");?>
            </button>
            
            <button type="button" class='button2 btn btn-warning btn-small' id="moreBtn" onclick="return false;">
                <i class="icon icon-plus-sign icon-white"></i>&nbsp;&nbsp;<?php echo _("Add another");?>
            </button>           
         
               
        </form>	
    	  
    
    </div>
    <div class="clearfix"></div>
    <hr>
   
    <div>
    	<form id="manage_img" action="uploader.php" method="post">
    	<?php		  
		if(isset($filecount) && $filecount >0 ) { ?>
                	
			<div style="clear:both; font-size:11px;">
				<?php 
					echo $filecount.' '._("images in /uploads");
                	if(isset($deleted)) echo "<br>".$deleted. " ". _("file(s) has been deleted");
				?>
            </div>
			<div class="row-fluid">
            	<ul class="thumbnails">
              	<?php
					buildFileList5($folder.'/thumbs/', $folder);
				?>
            	</ul>
            </div>
            
            <input type="hidden" name="delete" value="1">
            <input type="hidden" name="token" value="<?php echo $token;?>">
            <input type="hidden" name="id" value="<?php echo $id;?>">								 
            <div>
            
            <button type="submit" name="use_img" class='button2 btn btn-success btn-small' id="useBtn" onClick="return false;">
                <i class="icon icon-ok icon-white"></i>&nbsp;&nbsp;<?php echo _("Use selected");?>
            </button>
            
            <button type="submit" name="delete_img" class='button2 btn btn-danger btn-small' id="delBtn">
                <i class="icon icon-remove icon-white"></i>&nbsp;&nbsp;<?php echo _("Delete");?>
            </button>
            </div>
			<?php } ?>
          </form>
        
      
    </div>
    
    <div style="clear:both"></div>
    
</div>

</body>
</html>