Location: PHPKode > projects > OSShare > osshare-project-v1.0.1/app/controllers/pictures_controller.php
<?php
/*
OsShare v1 , 
Coded By Paimpozhil B. , SaravanaKumar M.S.
*/
class PicturesController extends AppController {
	
	var $name = 'Pictures';
	var $helpers = array('Html', 'Form','Javascript','ajax','Pagination' ,'Time');
	var $uses= array('Picture','Sitesetting','Category','Pcomment','Prating','Slaveserver','Pfavorite','User','Alb');
	var $components = array ('Pagination'); 


	
	function index() {

		$data = $this->Session->read('User');
		$priv = $data["privilege"];
		if ($priv=='user')
		{
			$this->redirect(array('action'=>'userindex'), null, true);
		}
		elseif ($priv =='admin')
		{
			$this->layout = "admin";
			$this->redirect(array('action'=>'adminindex'), null, true);
				
		}
		}
		
		function bunchd()
		{
			//debug($this->params);
			$data = $this->Session->read('User');
			$priv = $data["privilege"];
			//print_r($_POST);
			$i=0;
			/*foreach($_GET as $delid)
			{
				echo $delid[$i++];
			}*/

			if ($priv=='admin')
			{
				foreach($this->params['url'] as $delid)				
				{
				$delid = intval($delid);
					if($delid!=0)
					$this->Picture->del($delid);		
					$flag=1;									
				}			
				if($flag==1)
				{
				$this->Session->SetFlash("Selected Items Deleted");
			$this->redirect(array('controller'=>'pictures','action'=>'adminindex'), null, true);
				}
			}
			else if($priv=='user')
			{
				foreach($this->params['url'] as $delid)				
				{
				$delid = intval($delid);
					if($delid!=0)
					$this->Picture->del($delid);		
					$flag=1;									
				}			
				if($flag==1)
				{
				$this->Session->SetFlash("Selected Items Deleted");
			$this->redirect(array('controller'=>'pictures','action'=>'userindex'), null, true);
				}
			}		

		}


	function adminindex($s=null) {
		$this->layout = "admin";
		$this->Picture->recursive = 0;
		$data = $this->Session->read('User');
		$id = $data["id"];
		$criteria = "`Picture`.user_id = " . $id . " OR `Picture`.user_id != ". $id;
		list($order,$limit,$page) = $this->Pagination->init($criteria,NULL,array('page'=>$this->page,'show'=>$this->show)); // Added 
		$pictures = $this->Picture->findAll($criteria, NULL, $order, $limit, $page);
		$this->set('pictures',$pictures);
	}

	function userindex() {
		$this->layout = "user";
		$this->Picture->recursive = 0;
		$data = $this->Session->read('User');
		$id = $data["id"];
		
		$criteria = "`Picture`.user_id = " . $id ;
		list($order,$limit,$page) = $this->Pagination->init($criteria,NULL,array('page'=>$this->page,'show'=>$this->show)); // Added 
		$pictures = $this->Picture->findAll($criteria, NULL, $order, $limit, $page);
		$this->set('pictures',$pictures);
	
	}
	
	function related($id=null)
	{
	if($id)
	{
		$this->Picture->id = $id;
		$tags =		$this->Picture->field("tags");
		//debug($tags);

		$condition = "";
		foreach(explode(" ",$tags) as $tag)
		{
		if($tag != "")
		$condition .= " `Picture`.tags LIKE '%" . $tag . "%' OR `Picture`.name LIKE '%" . $tag . "%' OR `Picture`.desc LIKE '%" . $tag . "%' OR ";
		}
		
		$condition .= "0 AND ( `Picture`.is_corrupted = 1 )  ";
		$this->set('pictures',$this->Picture->findAll($condition,NULL,NULL,10,NULL,true)); 
		
	}
	$this->layout= false;
	Configure::write('debug', '0');
	}
	
		
	function confirmview($id = null)
	{
	$this->dolayout();
	if(!$id) {
			$this->Session->setFlash('Invalid Picture.');
			$this->redirect(array('action'=>'index'), null, true);
		}
	$this->set('id',$id);	
	}
	
	function view($id = null) {
		
		$data = $this->dolayout();
//		debug($data);
//		die();
		if(!$id) {
			$this->Session->setFlash('Invalid Picture.');
			$this->redirect(array('action'=>'index'), null, true);
		}
		
		$abusethreshold = $this->ssettings['AbuseViewThreshold'];
		

		$this->Picture->id = $id;
		$thispicture = Cache::read('thpicture'.$id);
		if($thispicture == false)
		{
			$thispicture = $this->Picture->read(null, $id);
			Cache::write('thpicture'.$id,$thispicture,'+1 hour');
		}
//		$thispicture = $this->Picture->read(null, $id);
		if((int)$abusethreshold < (int)$this->Picture->field("abusepoints") && !isset($this->params["named"]["confirm"]))
		$this->redirect(array('action'=>'confirmview','id'=>$id));
		$picture = Cache::read('cache_picture'.$id);
		if($picture == false)
		{
//		$this->set('$picture', $this->Picture->read(null, $id));
		$picture = $this->Picture->read(null, $id);
		Cache::write('cache_picture'.$id,$picture,'+1 hour');
		}
		$this->set('picture',$picture);
		$this->set('user',$data);
		 $rating = Cache::read('cache_rating'.$id);
		 if($rating == false)
		 {
		 	$rating = $this->Prating->findbypicture_id($id);
			Cache::write('cache_rating'.$id,$rating,'+1 hour');
		}
		$this->set('rating',$rating);
//		$this->set('rating',$this->Prating->findbypicture_id($id));
		$this->set('settings',$this->ssettings);
		
		
		if (isset($data['id']))
		{
		$userrating = Cache::read('cache_userrate'.$id);
		if($userrating == false)
		{
		$userrating = $this->Prating->findcount("`Prating`.user_id =  " . $data['id']  . "  and `Prating`.picture_id = " . $id);
		cache::write('cache_userrate'.$id,$userrating,'+1 hour');
		}
		$this->set('userrating',$userrating);
//		 $this->set('userrating',$this->Prating->findcount("`Prating`.user_id =  " . $data['id']  . "  and `Prating`.picture_id = " . $id)) ;

//		 $albums = $this->Alb->generateList("`Alb`.user_id = " . $data['id'],null,null,'{n}.Alb.id','{n}.Alb.albname');
       $albums = $this->Alb->find("list",array('conditions'=>"`Alb`.user_id = " . $data['id'],'fields'=>array('Alb.id','Alb.albname')));

//		$this->set(compact('albums'));
		$this->set('albums',$albums);
		}
		 
		 
		$this->set('ratingcount',$this->Prating->find("`Prating`.`picture_id` = " . $id,array("Avg(`Prating`.`rating`) as average") ));
		$favorite = Cache::read('pic_favorite'.$id);
		if($favorite == false)
		{
			$favorite = $this->Pfavorite->findbypicture_id($id,"count(*) as favcount");
			Cache::write('pic_favorite'.$id,$favorite,'+1 hour');
		}
		$this->set('favorite',$favorite);
//			$this->set('favorite',$this->Pfavorite->findbypicture_id($id,"count(*) as favcount"));
			

		if (isset($data['id']))
		$this->set('userfav',$this->Pfavorite->find("`Pfavorite`.user_id =  " . $data['id']  . "  and `Pfavorite`.picture_id = " . $id)) ;
		$this->Picture->execute("UPDATE `pictures` SET `views` = " . ((int)$thispicture["Picture"]["views"] + 1) ." WHERE `id` = " . (int)$thispicture["Picture"]["id"] );
	
		//Social
		$social = $this->ssettings['SocialTools'];
		
		$this->set('social',$social);
		

		
	}
	
	function picuploadview($id=null)
	{
		if($id)
		{
		$thispicture = $this->Picture->findbyid($id);
		$condition = "`Picture`.user_id = " . $thispicture["Picture"]["user_id"] . " AND " ;
		$condition .= "`Picture`.name = '" . $thispicture["Picture"]["name"] . "' AND " ;
		$condition = "`Picture`.is_corrupted = " . 1 . " AND " ;
		$condition .= "`Picture`.desc = '" . $thispicture["Picture"]["desc"] . "' AND " ;
		$condition .= "`Picture`.id >= " . $thispicture["Picture"]["id"]  ;
		
		
		$this->set('pictures',$this->Picture->findAll($condition,NULL,"`Picture`.id DESC",NULL,NULL,true)); 
		$this->layout= false;
		Configure::write('debug', '0');
		}
	}
	function userview($id = null) {
	
		if(!$id) {
			$this->Session->setFlash('Invalid Picture.');
			$this->redirect(array('action'=>'index'), null, true);
		}
		$this->set('picture', $this->Picture->read(null, $id));
		$this->set('comments',$this->Vcomment->findallbypicture_id($id));
	}



	function add() {
		$data = $this->dolayout();
		
		if(!empty($this->data)) {
			$this->cleanUpFields();
			$this->Picture->create();
			
			$data = $this->Session->read('User');
			$id = $data["id"];
			
			$this->data["Picture"]["user_id"]=$id;
			if($this->Picture->save($this->data)) {
				$this->Session->setFlash('Please Upload the Picture');
				$this->redirect(array('action'=>'mupload','id'=>$this->Picture->id), null, true);
			} else {
				$this->Session->setFlash('The Picture could not be saved. Please, try again.');
			}
		}
		$categories = $this->Picture->Category->find('list');
		$this->set(compact('categories'));
	}
	
	function unadd() {
		$data = $this->dolayout();
		
		if(!empty($this->data)) {
			$this->cleanUpFields();
			$this->Picture->create();
			$anon_pic = $this->User->findbyusername('anon');			
			$this->data["Picture"]["user_id"]=$anon_pic["User"]["id"];
		
			if($this->Picture->save($this->data)) {
				$this->Session->setFlash('Please Upload the Picture');
				$this->redirect(array('action'=>'mupload','id'=>$this->Picture->id), null, true);
			} else {
				$this->Session->setFlash('The Picture could not be saved. Please, try again.');
			}
		}
		$categories = $this->Picture->Category->find('list');
		$this->set(compact('categories'));
	}
	
	
	function edit($id = null) {
	$this->layout = "admin";
		if(!$id && empty($this->data)) {
			$this->Session->setFlash('Invalid Picture');
			$this->redirect(array('action'=>'index'), null, true);
		}
		if(!empty($this->data)) {
			$this->cleanUpFields();
			if($this->Picture->save($this->data)) {
				$this->Session->setFlash('The Picture saved');
				$this->redirect(array('action'=>'index'), null, true);
			} else {
				$this->Session->setFlash('The Picture could not be saved. Please, try again.');
			}
		}
		if(empty($this->data)) {
			$this->data = $this->Picture->read(null, $id);
		}
		$categories = $this->Picture->Category->find('list');
		$this->set(compact('categories'));
	}
	
	function useredit($id = null) {
		if(!$id && empty($this->data)) {
			$this->Session->setFlash('Invalid Picture');
			$this->redirect(array('action'=>'index'), null, true);
		}
		
		$data = $this->Session->read('User');
			$uid = $data["id"];
			
			$picture = $this->Picture->findbyid($id);
			
			if ($picture["Picture"]["user_id"]!=$uid)
			{
			$this->Session->setFlash('You Dont Have That Much Privileage , Try HARDER.');
			$this->redirect(array('action'=>'userindex'), null, true);
			}
			
		if(!empty($this->data)) {
			$this->cleanUpFields();
			
			
			
			if($this->Picture->save($this->data)) {
				$this->Session->setFlash('The Picture saved');
				$this->redirect(array('action'=>'index'), null, true);
			} else {
				$this->Session->setFlash('The Picture could not be saved. Please, try again.');
			}
		}
		if(empty($this->data)) {
			$this->data = $this->Picture->read(null, $id);
		}
		$categories = $this->Picture->Category->find('list');
		$this->set(compact('categories'));
	}

	function delete($id = null) {
		if(!$id) {
			$this->Session->setFlash('Invalid id for Picture');
			$this->redirect(array('action'=>'index'), null, true);
		}
		
		
		if($this->Picture->del($id)) {
		
			$this->Session->setFlash('Picture #'.$id.' deleted');
			$this->redirect(array('action'=>'index'), null, true);
		}
	}
	
	function userdelete($id = null) {

		if(!$id) {
			
			$this->Session->setFlash('Invalid id for Picture');
			$this->redirect(array('action'=>'index'), null, true);
		}
		
			$data = $this->Session->read('User');
			$uid = $data["id"];
			$picture = $this->Picture->FindByid($id);
			
		
			if ($picture["Picture"]["user_id"]!=$uid)
			{
			$this->Session->setFlash('You Dont Have That Much Privileage , Try HARDER.');
			$this->redirect(array('action'=>'userindex'), null, true);
			}
			
		if($this->Picture->del($id)) {
			$this->Session->setFlash('Picture #'.$id.' deleted');
			$this->redirect(array('action'=>'userindex'), null, true);
		}
	}
	
	
	function upload($id = null)
	{
		$this->dolayout();
		$categories = $this->Picture->Category->find('list');
		$this->set(compact('categories'));
		$setting = $this->Sitesetting->findbyid(1);
		$this->set('setting',$setting["Sitesetting"]);
		$this->set('id',$id);
	}
	function mupload($id = null)
	{
		if($id){
		$this->dolayout();
		$categories = $this->Picture->Category->find('list');
		$this->set(compact('categories'));
		$setting = $this->Sitesetting->findbyid(1);
		$this->set('setting',$setting["Sitesetting"]);
		$this->set('id',$id);
		}
	}

	
	function completeupload()
	{
		//get slave details
		$this->dolayout();
		set_time_limit(0);		
	
		$unencodedfile = str_replace(" ","_",addslashes($this->params["form"]["filename"]));
		$ext = substr(strrchr($unencodedfile, "."), 1);
		$this->encode($this->params["pass"][0],$unencodedfile,$ext);
	}
	/*	//encode it
	$ffmpegpath = $ssettings["Sitesetting"]["FFMPEGPath"];
	$encodecmd = $ffmpegpath . " -y -i " . 	$uploadfilepath . " -ar 22050 -ab 64 -v -1 -f flv -s 320x240 -acodec mp3 " . 	$uploadfilepath . ".flv";
	


	$ret = system($encodecmd);
	
	
	$thumb = $ffmpegpath . " -y -i " . 	$uploadfilepath . " -v 0 -f mjpeg -ss 5 -vframes 1 -s 160x120 -an " . 	$uploadfilepath . ".jpg";
	
	$ret2 = system($thumb);
	
	


		$picture =$this->Picture->findbyid($this->params["pass"][0]);
		$actualfile = $uploadDir . str_replace(" ","_",addslashes($this->params["form"]["filename"])) . ".flv";
		$hash =  $picture["Picture"]["user_id"] . md5(time() . str_replace(" ","_",addslashes($this->params["form"]["filename"]))) ;
		$newfilename  = $uploadDir .  $hash . ".flv";
		
		$actualthumb = str_replace(".flv",".jpg",$actualfile);
		$newthumb =str_replace(".flv",".jpg",$newfilename);
		
		if(filesize($actualthumb)==0)
		$defaultthumb = 1;
		else
				$defaultthumb = 0;
		
		rename($actualfile,$newfilename );
		rename( $actualthumb,$newthumb );
		
		if($activeslave["ftpuser"]=="sameserver" && $activeslave["ftppass"]=="sameserver" && $activeslave["ftphost"]=="sameserver")
		{
			rename($newfilename,$activeslave["ftpdirectory"]. DS . $hash . ".flv");
			rename($newthumb,$activeslave["ftpdirectory"]. DS . $hash . ".jpg");
			$ftpstatus = "File Has been sent to the slave <br />";
			$this->set('ftpstatus',$ftpstatus);
		}
		else
		{
				//FTP it to slave
			$conn_id = ftp_connect($activeslave["ftphost"],21,10);
			if($conn_id)
			{
			$login_result = ftp_login($conn_id, $activeslave["ftpuser"], $activeslave["ftppass"]);
			 
			
			if ((!$conn_id) || (!$login_result)) {  // check connection
					$ftpstatus = "Connected <br />";
				 } else {
				 //    echo "Connected to $ftp_server, for user $ftp_user_name <br />";
			  }
			  
			  ftp_chdir($conn_id, $activeslave["ftpdirectory"] );
		
			  $upload = ftp_put($conn_id,  $hash . ".flv"  , $newfilename  , FTP_BINARY);  // upload the file
					
				  if (!$upload) {  // check upload status
					$ftpstatus = "Uploading Failed <br />";
				  } else {
					 $upload = ftp_put($conn_id,  $hash . ".jpg" , $newthumb  , FTP_BINARY);  // upload the file
					 $ftpstatus = "Uploaded <br />";
					 
				  }
		
				  ftp_close($conn_id); // close the FTP stream
  				$this->set('ftpstatus',$ftpstatus);
			}
		}
		
		$picture["Picture"]["fspath"] =  $newfilename;
		
		$picture["Picture"]["size"] =  (int)$this->params["form"]["filesize"];
		$picture["Picture"]["path"] = $activeslave["httppath"] . $hash . ".flv";
		
		if($defaultthumb == 1)
		$picture["Picture"]["thumbnailpath"] = $ssettings["Sitesetting"]["DefaultThumbNail"] ;
		else
		$picture["Picture"]["thumbnailpath"] =  $activeslave["httppath"] . $hash . ".jpg";
		
		$picture["Picture"]["type"] = $this->params["form"]["filetype"];
		$picture["Picture"]["created"] = date("Y-m-d h-i-s");
		
		//Remove actual file
			//unlink($uploadDir . $unencodedfile);
			
		if($this->Picture->save($picture,false)){
		$this->Session->setFlash('The Picture has been saved and it is Encoded now');
			} else {
			$this->Session->setFlash('The Picture could not be saved. Please, try again.');
			}
		
	}
	*/
	
	function uploaded()
	{
	set_time_limit(0);
	$ssettings = $this->Sitesetting->findbyid(1);

	
	if ($_GET['jqUploader']==1){

    if ($_FILES['Filedata']['name']) {
	$uploadDir = WWW_ROOT . 'files/';
	$uploadFile = $uploadDir . md5(str_replace(" ","_",(addslashes($_REQUEST['Filename']))));
	$ext = substr(strrchr($_FILES['Filedata']['name'], "."), 1);
	move_uploaded_file($_FILES['Filedata']['tmp_name'], $uploadFile.".".$ext);
//	file_put_contents("d:\\iknowiknow.txt",print_r($_REQUEST,true));	
//	file_put_contents("d:\\iknowiknow.txt",$_FILES['Filedata']['filename']);
	return $uploadFile;
	  }
	}
	else
	{
	    // REGULAR (JAVASCRIPT-OFF) FORM PROCESSING
    	return 'jqUploader disactivated';
	}

	}
		
	function muploaded()
	{
	set_time_limit(0);
	$ssettings = $this->Sitesetting->findbyid(1);
    if ($_FILES['Filedata']['name']) {
//Debugway	
	$of = md5(str_replace(" ","_",(addslashes(basename($_FILES['Filedata']['name'])))));
	$uploadDir = WWW_ROOT . 'files/';
	$uploadFile = $uploadDir . md5(str_replace(" ","_",(addslashes(basename($_FILES['Filedata']['name'])))));
	$ext = substr(strrchr($_FILES['Filedata']['name'], "."), 1);
	move_uploaded_file($_FILES['Filedata']['tmp_name'], $uploadFile.".".$ext);
	$unencodedfile = str_replace(" ","_",addslashes($_FILES['Filedata']['name']));
	$ext = substr(strrchr($unencodedfile, "."), 1);
	$this->encode($this->params["pass"][0],$unencodedfile,$ext);
	}

	}


	function search()
	{
		
		$data = $this->dolayout();	
			
		$this->set('user',$data);
	
		$this->set('categories',$this->Category->findall());
		//die(print_r($this->params,true));
		$sortby = "";		
		$fields = NULL;
	
	//	if(!isset($this->params["named"]["search"]))
	//	$this->params["named"]["search"]="";
		
	//	$squery = isset($this->params["url"]["data"])?$this->params["url"]["data"]["Picture"]["search"]:$this->params["named"]["search"];
	if(!isset($this->params["named"]["search"]))
		$this->params["named"]["search"]="";
		
		$squery = isset($this->params["url"]["search"])?$this->params["url"]["search"]:$this->params["named"]["search"];


			if(isset($this->params["named"]["sort"]))
			{
				$this->set('rsssort',$this->params["named"]["sort"]);
				
				if($this->params["named"]["sort"]=='views')
				{	
				$condition = "( `Picture`.desc LIKE '%" . $squery . "%' OR `Picture`.tags LIKE '%" . $squery . "%' OR `Picture`.name LIKE '%" . $squery . "%' )";
				$sortby = "`Picture`.views DESC ";
				}
				elseif($this->params["named"]["sort"]=='date')
				{
				
				$condition = "( `Picture`.desc LIKE '%" . $squery . "%' OR `Picture`.tags LIKE '%" . $squery . "%' OR `Picture`.name LIKE '%" . $squery . "%' )";
				$sortby = "`Picture`.created DESC ";
				
				}
				
				elseif($this->params["named"]["sort"]=='category')
				{
				$this->set('rsscategory',$this->params["named"]["cname"]);
				$condition = "(( `Picture`.desc LIKE '%" . $squery . "%' OR `Picture`.tags LIKE '%" . $squery . "%' OR `Picture`.name LIKE '%" . $squery . "%' ) AND `Category`.name = '" . urldecode($this->params["named"]["cname"]) . "')";
				
				
				}
				elseif($this->params["named"]["sort"]=='user')
				{
				$this->set('rsscategory',$this->params["named"]["cname"]);
				$condition = "(( `Picture`.desc LIKE '%" . $squery . "%' OR `Picture`.tags LIKE '%" . $squery . "%' OR `Picture`.name LIKE '%" . $squery . "%' ) AND `Picture`.user_id = '" . urldecode($this->params["named"]["cname"]) . "')";
				
				
				}
				
				elseif($this->params["named"]["sort"]=='rating')
				{
				
						
				$condition = " (`Picture`.desc LIKE '%" . $squery . "%' OR `Picture`.tags LIKE '%" . $squery . "%' OR `Picture`.name LIKE '%" . $squery . "%') GROUP BY `Prating`.picture_id ";
				
				$countcondition = " `Picture`.desc LIKE '%" . $squery . "%' OR `Picture`.tags LIKE '%" . $squery . "%' OR `Picture`.name LIKE '%" . $squery . "%'";
				
//				"`Prating`.`picture_id` = " . $id,array("Avg(`Prating`.`rating`) as average"
				
				$sortby = "avgrate DESC,maxrate DESC ";
				
				
				}
				
				
				
			}
			
			else
			{
				$condition = "((`Picture`.name LIKE '%" . $squery . "%' AND `Picture`.tags LIKE '%" . $squery . "%') OR `Picture`.desc LIKE '%" . $squery . "%' OR `Picture`.tags LIKE '%" . $squery . "%' OR `Picture`.name LIKE '%" . $squery . "%')";
				
		

			}
			

		
		$condition .= " AND (`Picture`.is_corrupted = 1) ";
		
		
		if(isset($this->params["named"]["sort"]))
		{
		if($this->params["named"]["sort"]=='rating')
		{
		$this->Pagination->total = $this->Picture->Prating->findCount($countcondition);
		list($order,$limit,$page) = $this->Pagination->init($condition);
		$ntpicture = $this->Picture->Prating->findAll($condition,"*,sum(`rating`.rating) as maxrate,Avg(`rating`.rating) as avgrate ",$sortby,$limit,$page,2);

		
		
		}
		else
		{
			list($order,$limit,$page) = $this->Pagination->init($condition,NULL,array('page'=>$this->page,'show'=>$this->show)); 
			$ntpicture = $this->Picture->findAll($condition,NULL,$sortby,$limit,$page);
		}
		}
		else
		{
			list($order,$limit,$page) = $this->Pagination->init($condition,NULL,array('page'=>$this->page,'show'=>$this->show)); 
			$ntpicture = $this->Picture->findAll($condition,NULL,$sortby,$limit,$page);
		}
		
			
				//debug($ntpicture);
			$allpicture = $ntpicture;
			
			foreach (array_keys($allpicture) as $key)
			{
				$picture =& $allpicture[$key];
				$picture["Picture"]["rating"] = $this->Picture->prating($picture["Picture"]["id"]);
				$picture["Picture"]["rating"] = $picture["Picture"]["rating"][0]["average"];
			}
			
			$this->set("squery",$squery);
			$this->set("spicture",$allpicture);
			if(isset($this->params["named"]["output"]))
			{
				Configure::write('debug', '0');
				if($this->params["named"]["output"]=="rss")
				{
					$setting = $this->Sitesetting->findbyid(1);
					$this->set("ssetting",$setting["Sitesetting"]);
					$this->render('rss','rss');
				}
			}
		}
		
		function abuse($id = null) {
		if(!$id) {
			$this->Session->setFlash('Invalid id for Picture');
			$this->redirect(array('action'=>'index'), null, true);
		}
		
		$data = $this->Session->read('User');
		$priv = $data["privilege"];
		if ($priv=='user')
			$abval = 1;	
		elseif ($priv =='admin')
			$abval = 5;
		elseif ($priv == 'mod')
			$abval = 3;
		else
			echo("Please Login");
			
		$picture = $this->Picture->findbyid($id);
		$picture["Picture"]["abusepoints"] +=  $abval;
		
		$this->Picture->save($picture);
		$this->Session->setFlash('Abuse Reported ');
			$this->layout= false;
		 Configure::write('debug', '0');
	}
	

		function tupload($id = null)
	{
		$data = $this->dolayout();	
		$thumb_qr = $this->Picture->findbyid($id);
		if($data["id"] != $thumb_qr["Picture"]["user_id"])
		{
			$this->Session->SetFlash("Invalid User");
			$this->redirect(array('action'=>'index','controller'=>'pages'));
		}
		$ssettings = $this->Sitesetting->findbyid(1);
		$slave = $this->Slaveserver->findbyid($ssettings["Sitesetting"]["ActiveSlave"]);
		$activeslave = $slave["Slaveserver"];
		if ($_FILES['Filedata']['name']) 
		{
		$uploadDir = WWW_ROOT . 'files/';
		$uploadFile = $uploadDir . md5(str_replace(" ","_",(addslashes($_FILES['Filedata']['name']))));
		$ext = substr(strrchr($_FILES['Filedata']['name'], "."), 1);
		move_uploaded_file($_FILES['Filedata']['tmp_name'], $uploadFile.".".$ext);
		$hash = $thumb_qr["Picture"]["user_id"] . md5(time() . str_replace(" ","_",addslashes($uploadFile))) ;
		$thumbfile = basename($thumb_qr["Picture"]["thumbnailpath"]);
		$thumbpath = $uploadDir.$thumbfile;
		$org_path = $uploadFile.".".$ext;
//		file_put_contents("c:\sara.txt",$thumbfile.$thumbpath);
		if($ssettings["Sitesetting"]["Pic_Soft"] == 'ImageMagick'){
		$this->create_thumbnail($org_path,$thumbpath);
		}
		else
		{
		$this->gd_thumbnail($org_path,$thumbpath,$ext);
		}
		$newfilename = $thumbpath;
		
	if($activeslave["ftpuser"]=="sameserver" && $activeslave["ftppass"]=="sameserver" && $activeslave["ftphost"]=="sameserver")
		{
			rename($newfilename,$activeslave["ftpdirectory"].DS.$thumbfile);
			$ftpstatus = "File Has been sent to the slave <br />";
			$this->set('ftpstatus',$ftpstatus);
		}
		else
		{
				//FTP it to slave
			$conn_id = ftp_connect($activeslave["ftphost"],21,10);
			if($conn_id)
			{
			$login_result = ftp_login($conn_id, $activeslave["ftpuser"], $activeslave["ftppass"]);
			 
			
			if ((!$conn_id) || (!$login_result)) {  // check connection
					$ftpstatus = "Connected <br />";
				 } else {
				 //    echo "Connected to $ftp_server, for user $ftp_user_name <br />";
			  }
			  
			  ftp_chdir($conn_id, $activeslave["ftpdirectory"] );
		
			  $upload = ftp_put($conn_id,  $thumbfile  , $newfilename  , FTP_BINARY);  // upload the file
					
				  if (!$upload) {  // check upload status
					$ftpstatus = "Uploading Failed <br />";
				  } else {

					 
				  }
		
				  ftp_close($conn_id); // close the FTP stream
  				$this->set('ftpstatus',$ftpstatus);
			}
		}
		$thumbnailpin_path = $activeslave["httppath"] .$thumbfile;
		$thumb_qr["Picture"]["thumbnailpath"] = $thumbnailpin_path;
		if($this->Picture->save($thumb_qr,false))
		{
			$this->Session->SetFlash("Successfully Sent <br> Please Refresh the Page");
			$this->redirect(array('action'=>'index'));
		}
		}
		
	}
	function turlupload($id = null)
	{
		$data = $this->dolayout();	
		$thumb_qr = $this->Picture->findbyid($id);
		if($data["id"] != $thumb_qr["Picture"]["user_id"])
		{
			$this->Session->SetFlash("Invalid User");
			$this->redirect(array('action'=>'index','controller'=>'pages'));
		}
		$ssettings = $this->Sitesetting->findbyid(1);
		$slave = $this->Slaveserver->findbyid($ssettings["Sitesetting"]["ActiveSlave"]);
		$activeslave = $slave["Slaveserver"];
		$ext = substr(strrchr($_POST['Filedata'], "."), 1);
//		file_put_contents("d:\\sara.txt",$ext);
		if ($_POST['Filedata']) 
		{
		$uploadDir = WWW_ROOT . 'files/';
		$uploadFile = $uploadDir . md5(str_replace(" ","_",(addslashes($_POST['Filedata']))));
		$httpfile = md5(str_replace(" ","_",(addslashes($_POST['Filedata']))));
		if(!$this->simulatedownload($_POST['Filedata'],$uploadFile.".".$ext))
		{
		die ('Error on retrieving  , please try another url or check if remote server is online, Go back and try again ');
		}
		$hash = $thumb_qr["Picture"]["user_id"] . md5(time() . str_replace(" ","_",addslashes($uploadFile))) ;
		
		$thumbfile = basename($thumb_qr["Picture"]["thumbnailpath"]);
		$thumbpath = $uploadDir.$thumbfile;
		$org_path = $uploadFile.".".$ext;
//		file_put_contents("c:\sara.txt",$thumbfile.$thumbpath);
		if($ssettings["Sitesetting"]["Pic_Soft"] == 'ImageMagick'){
		$this->create_thumbnail($org_path,$thumbpath);
		}
		else
		{
		$this->gd_thumbnail($org_path,$thumbpath,$ext);
		}
		$newfilename = $thumbpath;
		
	if($activeslave["ftpuser"]=="sameserver" && $activeslave["ftppass"]=="sameserver" && $activeslave["ftphost"]=="sameserver")
		{
			rename($newfilename,$activeslave["ftpdirectory"]. DS .$thumbfile);
			$ftpstatus = "File Has been sent to the slave <br />";
			$this->set('ftpstatus',$ftpstatus);
		}
		else
		{
				//FTP it to slave
			$conn_id = ftp_connect($activeslave["ftphost"],21,10);
			if($conn_id)
			{
			$login_result = ftp_login($conn_id, $activeslave["ftpuser"], $activeslave["ftppass"]);
			 
			
			if ((!$conn_id) || (!$login_result)) {  // check connection
					$ftpstatus = "Connected <br />";
				 } else {
				 //    echo "Connected to $ftp_server, for user $ftp_user_name <br />";
			  }
			  
			  ftp_chdir($conn_id, $activeslave["ftpdirectory"] );
		
			  $upload = ftp_put($conn_id, $thumbfile   , $newfilename  , FTP_BINARY);  // upload the file
					
				  if (!$upload) {  // check upload status
					$ftpstatus = "Uploading Failed <br />";
				  } else {

					 
				  }
		
				  ftp_close($conn_id); // close the FTP stream
  				$this->set('ftpstatus',$ftpstatus);
			}
		}
		$thumbnailpin_path = $activeslave["httppath"] .$thumbfile;
		$thumb_qr["Picture"]["thumbnailpath"] = $thumbnailpin_path;
		if($this->Picture->save($thumb_qr,false))
		{
			$this->Session->SetFlash("Thumbnail Created <br> Please Refresh the page");
			$this->redirect(array('action'=>'index'));
		}
		}
		
	}

	function thumbupload($id = null)
	{
		$this->dolayout();
		$categories = $this->Picture->Category->find('list');
		$this->set(compact('categories'));
		$setting = $this->Sitesetting->findbyid(1);
		$this->set('setting',$setting["Sitesetting"]);
		$this->set('id',$id);
	}

	function fetchurl()
	{ 
	//	die(pr($this->params,true));
		set_time_limit(0);
		$this->dolayout();
		
		$details = $this->data["Picture"];
		$unencodedfile = str_replace(" ","_",addslashes($details["url"]));
//		debug($details);
		$uploadDir = WWW_ROOT . 'files' . DS;
		$uploadfilepath = $uploadDir . md5($unencodedfile)  ;
		
		$ext = substr(strrchr($details["url"], "."), 1);
		
		if(!$this->simulatedownload($details["url"],$uploadfilepath.".".$ext))
		{
		die ('Error on retrieving  , please try another url or check if remote server is online, Go back and try again ');
		}
		$picture =$this->Picture->findbyid($details["id"]);
		$this->encode($details["id"],$unencodedfile,$ext);
	}
	
	function encode($id,$unencodedfile,$extn=null){
		//echo $unencodedfile;
		set_time_limit(0);
		$ssettings = $this->Sitesetting->findbyid(1);
		$slave = $this->Slaveserver->findbyid($ssettings["Sitesetting"]["ActiveSlave"]);
		$activeslave = $slave["Slaveserver"];
		$uploadDir = WWW_ROOT . 'files' . DS;
		$uploadfilepath = $uploadDir .md5(str_replace(" ","_",(addslashes($unencodedfile))));
		$httpfile = md5(str_replace(" ","_",(addslashes($unencodedfile))));
		$picture =$this->Picture->findbyid($id);
		$hash = $picture["Picture"]["user_id"] . md5(time() . str_replace(" ","_",addslashes($unencodedfile))) ;
		$orgfile = $uploadfilepath.".".$extn;
//		sleep(5);
//		file_put_contents("c:\sara.txt",$ssettings["Sitesetting"]["PictureSoftware"]);
		$thumbpath = $uploadDir . $hash . "_T" . ".jpg";
		$mthumbpath = $uploadDir . $hash . "_M.jpg"; //// Path where thumb nail image will be stored
		if($ssettings["Sitesetting"]["Pic_Soft"] == 'ImageMagick'){
		$this->create_thumbnail($orgfile,$thumbpath);
//		file_put_contents("c:\sara.txt",$thumbpath.$mthumbpath);
		$this->create_mediumthumbnail($orgfile,$mthumbpath);
		}
		else{
		
		$this->gd_thumbnail($orgfile,$thumbpath,$extn);
		$this->gd_mediumthumbnail($orgfile,$mthumbpath,$extn);
		}
//			$cmd = "c:\imagemagick\convert -size 200x200 ".$orgfile." -thumbnail 100x100\> ".$thumbpath;
//			$cmd = "c:\imagemagick\convert ".$orgfile." -resize 100x100 ".$thumbpath;
//			$cmd = "convert -size 200x200 ".$orgfile." -thumbnail 100x100 -background white  -gravity center -extent 100x100 ".$thumbpath;

			//Special for Multi upload
		if((int)$picture["Picture"]["is_corrupted"]==1)
		{
			
			//temp Picture array to lick all what we need from that 
			$tpicture = $picture;
			$this->Picture->create();
			$tpicture["Picture"]["id"]= $this->Picture->getLastInsertId();
			$this->Picture->save($tpicture);
			$picture = $this->Picture->findbyid($tpicture["Picture"]["id"]);
		}
	
		$newfilename = $orgfile;
		$newthumb = $thumbpath;
		$newmthumb = $mthumbpath;
		
		
		if($activeslave["ftpuser"]=="sameserver" && $activeslave["ftppass"]=="sameserver" && $activeslave["ftphost"]=="sameserver")
		{
			rename($newfilename,$activeslave["ftpdirectory"]. DS . $httpfile .".". $extn);
			rename($newthumb,$activeslave["ftpdirectory"]. DS . $hash . "_T.jpg");
			rename($newmthumb,$activeslave["ftpdirectory"]. DS . $hash . "_M.jpg");
			$ftpstatus = "File Has been sent to the slave <br />";
			$this->set('ftpstatus',$ftpstatus);
		}
		else
		{
				//FTP it to slave
			$conn_id = ftp_connect($activeslave["ftphost"],21,10);
			if($conn_id)
			{
			$login_result = ftp_login($conn_id, $activeslave["ftpuser"], $activeslave["ftppass"]);
			 
			
			if ((!$conn_id) || (!$login_result)) {  // check connection
					$ftpstatus = "Connected <br />";
				 } else {
				 //    echo "Connected to $ftp_server, for user $ftp_user_name <br />";
			  }
			  
			  ftp_chdir($conn_id, $activeslave["ftpdirectory"] );
		
			  $upload = ftp_put($conn_id,  $httpfile .".".$extn   , $newfilename  , FTP_BINARY);  // upload the file
					
				  if (!$upload) {  // check upload status
					$ftpstatus = "Uploading Failed <br />";
				  } else {
				  	$upload = ftp_put($conn_id,  $hash . "_M.jpg" , $newmthumb  , FTP_BINARY);
					 $upload = ftp_put($conn_id,  $hash . "_T.jpg" , $newthumb  , FTP_BINARY);  // upload the file
					 $ftpstatus = "Uploaded <br />";
					 
				  }
		
				  ftp_close($conn_id); // close the FTP stream
  				$this->set('ftpstatus',$ftpstatus);
			}
		}
		
	
		$http_path = $activeslave["httppath"] .$hash . "." . $extn;
		$picture["Picture"]["fspath"] =  $newfilename;
		$picture["Picture"]["is_corrupted"]  = 1;
		$picture["Picture"]["size"] =  filesize($newfilename);
		$picture["Picture"]["path"] = $activeslave["httppath"] . $httpfile . "." . $extn;
		$thumnailpin_path = $activeslave["httppath"] . $hash . "_T.jpg";
		$picture["Picture"]["thumbnailpath"] =  $thumnailpin_path;
		$picture["Picture"]["type"] = $extn;
		
		$picture["Picture"]["created"] = date("Y-m-d h-i-s");
		
		//Remove actual file
			//unlink($uploadDir . $unencodedfile);
			
		if($this->Picture->save($picture,false)){
		$this->Session->setFlash('The Picture has been saved and it is Encoded now');
//		$this->redirect(array('action'=>'pic_action',$picture["Picture"]["id"]));
		$file = $this->Picture->findbyid($picture["Picture"]["id"]);
		$this->set('file',$file);
			} else {
			$this->Session->setFlash('The Picture could not be saved. Please, try again.');
			}
	
	$this->render('completeupload');
	}

	function pic_action($flpath=null)
	{
		$data = $this->dolayout();
		$usid = $data["id"];
		$file = $this->Picture->findbyid($flpath);
		$this->set('file',$file);
				
	}
	function enlarge_view($id=null)
	{
		$data = $this->dolayout();
		$usid = $data["id"];
		$enlargepic = $this->Picture->findbyid($id);
		$this->set('enlargepic',$enlargepic);
	}
	function simulatedownload ($file_source, $file_target)
	{

			
  // Preparations
  $file_source = str_replace(' ', '%20', html_entity_decode($file_source)); // fix url format
  if (file_exists($file_target)) { chmod($file_target, 0777); } // add write permission

  // Begin transfer
  if (($rh = fopen($file_source, 'rb')) === FALSE) { return false; } // fopen() handles
  if (($wh = fopen($file_target, 'wb')) === FALSE) { return false; } // error messages.
  while (!feof($rh))
  {
    // unable to write to file, possibly because the harddrive has filled up
    if (fwrite($wh, fread($rh, 1024)) === FALSE) { fclose($rh); fclose($wh); return false; }
  }

  // Finished without errors
  fclose($rh);
  fclose($wh);
  return true;
}
	

}
?>
Return current item: OSShare