Location: PHPKode > projects > OSShare > osshare-project-v1.0.1/app/controllers/videos_controller.php
<?php
/*
OsShare v1 , 
Coded By Paimpozhil B. , SaravanaKumar M.S.
*/
class VideosController extends AppController {
	var $layout = 'default';
	var $name = 'Videos';
	var $helpers = array('Html', 'Form','Javascript','Ajax','Pagination' ,'Time','Cache');
	var $uses= array('Video','Sitesetting','Category','Vcomment','Rating','Slaveserver','Favorite','Pl','User');
	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 adminindex() {
		$this->layout = "admin";
		$this->Video->recursive = 0;
		$data = $this->Session->read('User');
		$id = $data["id"];
		$criteria = "`Video`.user_id = " . $id . " OR `Video`.user_id != " . $id;
		list($order,$limit,$page) = $this->Pagination->init($criteria,NULL,array('page'=>$this->page,'show'=>$this->show)); // Added 
		$videos = $this->Video->findAll($criteria, NULL, $order, $limit, $page);
		$this->set('videos',$videos);
	
	}

	function userindex() {
	$this->layout="user";
		$this->Video->recursive = 0;
		$data = $this->Session->read('User');
		$id = $data["id"];
		
		$criteria = "`Video`.user_id = " . $id ;
		list($order,$limit,$page) = $this->Pagination->init($criteria,NULL,array('page'=>$this->page,'show'=>$this->show)); // Added 
		$videos = $this->Video->findAll($criteria, NULL, $order, $limit, $page);
		$this->set('videos',$videos);
			$this->set('head_title',$data["username"]."'s Videos");
	
	}
	
	function uploadview($id=null)
	{
		if($id)
		{
		$thisvideo = $this->Video->findbyid($id);
		$condition = "`Video`.user_id = " . $thisvideo["Video"]["user_id"] . " AND " ;
		$condition = "`Video`.is_encoded = " . 1 . " AND " ;
		$condition .= "`Video`.name = '" . $thisvideo["Video"]["name"] . "' AND " ;
//		$condition .= "`Video`.desc = '" . $thisvideo["Video"]["desc"] . "' AND " ;
		$condition .= "`Video`.id >= " . $thisvideo["Video"]["id"]  ;
		
		
		$this->set('videos',$this->Video->findAll($condition,NULL,"`Video`.id DESC",NULL,NULL,true)); 
		$this->layout= false;
		Configure::write('debug', '0');
		}
	}
	
	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' or 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'=>'adminindex'), null, true);
				}
			}
		}


	
	function related($id=null)
	{
	//debug($this->params);
	$type = $this->params["named"]["type"];
	if($id)
	{
		$this->Video->id = $id;
		if($type == "related")
		{
			$tags =		$this->Video->field("tags");
			//debug($tags);
	
			$condition = "";
			foreach(explode(" ",$tags) as $tag)
			{
			if($tag != "")
			$condition .= " `Video`.tags LIKE '%" . $tag . "%' OR `Video`.name LIKE '%" . $tag . "%' OR `Video`.desc LIKE '%" . $tag . "%' OR ";
			}
			
			$condition .= "0 AND ( `Video`.is_encoded = 1 )  ";
			$this->set('videos',$this->Video->findAll($condition,NULL,NULL,10,NULL,true)); 
		}
		elseif($type=="morefromuser")
		{
		
		$condition = "`Video`.is_encoded = 1 AND `Video`.user_id = " . $this->params["named"]["uid"];
		$this->set('videos',$this->Video->findAll($condition,NULL,"`Video`.id DESC",10,NULL,true)); 
		
		}
		elseif($type=="playlists")
		{
		
		$condition = "`Plsitem`.video_id = " . $id . " GROUP BY `Plsitem`.pl_id ";
		$this->set('videos',$this->Video->Plsitem->findAll($condition,NULL,NULL,10,NULL,2)); 	
		$this->render('relatedpls','ajax');
		//pr($this->Video->Plsitem->findAll($condition,NULL,NULL,10,NULL,3));
		}
		
	}
	$this->layout= false;
	Configure::write('debug', '0');
	}
	
		
	function confirmview($id = null)
	{
	$this->dolayout();
	if(!$id) {
			$this->Session->setFlash('Invalid Video.');
			$this->redirect(array('action'=>'index'), null, true);
		}
	$this->set('id',$id);	
	}
	
	function view($id = null) {

		$data = $this->dolayout();
		
		
		if(!$id) {
			$this->Session->setFlash('Invalid Video.');
			$this->redirect(array('action'=>'index'), null, true);
		}
		
		
		$abusethreshold = $this->ssettings['AbuseViewThreshold'];
		

		$this->Video->id = $id;
		$thisvideo = Cache::read('thvideo'.$id);
		if($thisvideo == false)
		{
			$thisvideo = $this->Video->read(null, $id);
			Cache::write('thvideo'.$id,$thisvideo,'+1 hour');
		}
//		$thisvideo = $this->Video->read(null, $id);
		if((int)$abusethreshold < (int)$thisvideo["Video"]["abusepoints"] && !isset($this->params["named"]["confirm"]))
		$this->redirect(array('action'=>'confirmview','id'=>$id));
		
		$this->set('video', $thisvideo );
		$this->set('head_title',$thisvideo['Video']['name']);
		$this->set('user',$data);
		$rating = Cache::read('video_rating'.$id);
		if($rating == false)
		{
			$rating = $this->Rating->findbyvideo_id($id);
			Cache::write('video_rating'.$id,$rating,'+1 hour');
		}
		$this->set('rating',$rating);
//		$this->set('rating',$this->Rating->findbyvideo_id($id));
		$this->set('settings',$this->ssettings);
		$this->set('head_title',$thisvideo['Video']['name']); //Title for view page
		$this->set('meta_key',str_replace(' ',',',$thisvideo['Video']['tags'])); //Tags for the page
		$this->set('meta_desc',str_replace(' ',',',$thisvideo['Video']['desc'])); //Description for the page
		if (isset($data['id']))
		{
		$userrating = Cache::read('vid_userrate'.$id);
		if($userrating == false)
		{
		$userrating = $this->Rating->findcount("`Rating`.user_id =  " . $data['id']  . "  and `Rating`.video_id = " . $id);
		Cache::write('vid_userrate'.$id,$userrating,'+1 hour');
		}
		$this->set('userrating',$userrating);
		// $this->set('userrating',$this->Rating->findcount("`Rating`.user_id =  " . $data['id']  . "  and `Rating`.video_id = " . $id)) ;
		 
		//Playlist
		//$playlists = $this->Pl->generateList("`Pl`.user_id = " . $data['id'],null,null,'{n}.Pl.id','{n}.Pl.plsname');
		$playlists = $this->Pl->find("list",array('conditions'=>"`Pl`.user_id = " . $data['id'],'fields'=>array('Pl.id','Pl.plsname'),'recursive'=>0));
	//	debug($playlists);
		$this->set(compact('playlists'));
	//	debug($playlists);
		$this->set('playlists',$playlists);

		
		$this->set('userfav',$this->Favorite->find("`Favorite`.user_id =  " . $data['id']  . "  and `Favorite`.video_id = " . $id)) ;
		}
		$this->set('ratingcount',$this->Rating->find("`Rating`.`video_id` = " . $id,array("Avg(`Rating`.`rating`) as average") ));
		
		$favorite = Cache::read('cache_favorite'.$id);
		if($favorite == false)
		{
			$favorite = $this->Favorite->findbyvideo_id($id,"count(*) as favcount");
			Cache::write('cache_favorite'.$id,$favorite,'+1 hour');
		}
		$this->set('favorite',$favorite);
		
		//$this->set('favorite',$this->Favorite->findbyvideo_id($id,"count(*) as favcount"));


		$this->Video->execute("UPDATE `videos` SET `views` = `views`+1 WHERE `id` = " . (int)$thisvideo["Video"]["id"] );
		//Social
		$social = $this->ssettings['SocialTools'];
		$this->set('social',$social);
		
		$this->set('logopath',$this->ssettings["LogoPath"]);
		
		
	}
	
	function userview($id = null) {
	
		if(!$id) {
			$this->Session->setFlash('Invalid Video.');
			$this->redirect(array('action'=>'index'), null, true);
		}
		$this->set('video', $this->Video->read(null, $id));
		$this->set('comments',$this->Vcomment->findallbyvideo_id($id));
	}



	function add() {
		$data = $this->dolayout();
		
		if(!empty($this->data)) {
			$this->cleanUpFields();
			$this->Video->create();
			
			$data = $this->Session->read('User');
			$id = $data["id"];
			
			$this->data["Video"]["user_id"]=$id;
//			print_r($this->data);
			if($this->Video->save($this->data)) {
				$this->Session->setFlash('Please Upload the Video');
				$this->redirect(array('action'=>'mupload','id'=>$this->Video->id), null, true);
			} else {
					$this->Session->setFlash('Video Could not be saved');
				}
		}
		$categories = $this->Video->Category->find('list');
		$this->set(compact('categories'));
		$this->set('head_title',"Upload Video");
	}
	
	function unadd() {

					$data = $this->dolayout();
		if(!empty($this->data)) {
			$this->cleanUpFields();
						$this->Video->create();
			$anon_vid = $this->User->findbyusername('anon');			
			$this->data["Video"]["user_id"]=$anon_vid["User"]["id"];
			
			if($this->Video->save($this->data)) {
				$this->Session->setFlash('Please Upload the Video');
				$this->redirect(array('action'=>'mupload','id'=>$this->Video->id), null, true);
			} else {
					$this->Session->setFlash('Video Could not be saved');
					$this->redirect(array('action'=>'index'));	}
		}
		$categories = $this->Video->Category->find('list');
		$this->set(compact('categories'));
		$this->set('head_title',"Anonymous Upload");
	}
	
	function edit($id = null) {
	$this->layout = "admin";
		if(!$id && empty($this->data)) {
			$this->Session->setFlash('Invalid Video');
			$this->redirect(array('action'=>'index'), null, true);
		}
		if(!empty($this->data)) {
			$this->cleanUpFields();
			if($this->Video->save($this->data)) {
				$this->Session->setFlash('The Video saved');
				$this->redirect(array('action'=>'index'), null, true);
			} else {
				$this->Session->setFlash('The Video could not be saved. Please, try again.');
			}
		}
		if(empty($this->data)) {
			$this->data = $this->Video->read(null, $id);
		}
		$categories = $this->Video->Category->find('list');
		$this->set(compact('categories'));
	}
	
	function useredit($id = null) {
		if(!$id && empty($this->data)) {
			$this->Session->setFlash('Invalid Video');
			$this->redirect(array('action'=>'index'), null, true);
		}
		
		$data = $this->Session->read('User');
			$uid = $data["id"];
			
			$video = $this->Video->findbyid($id);
			
			if ($video["Video"]["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->Video->save($this->data)) {
				$this->Session->setFlash('The Video saved');
				$this->redirect(array('action'=>'index'), null, true);
			} else {
				$this->Session->setFlash('The Video could not be saved. Please, try again.');
			}
		}
		if(empty($this->data)) {
			$this->data = $this->Video->read(null, $id);
		}
		$categories = $this->Video->Category->find('list');
		$this->set(compact('categories'));
	}

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

		if(!$id) {
			
			$this->Session->setFlash('Invalid id for Video');
			$this->redirect(array('action'=>'index'), null, true);
		}
		
			$data = $this->Session->read('User');
			$uid = $data["id"];
			$video = $this->Video->FindByid($id);
			
		
			if ($video["Video"]["user_id"]!=$uid)
			{
			$this->Session->setFlash('You Dont Have That Much Privileage , Try HARDER.');
			$this->redirect(array('action'=>'userindex'), null, true);
			}
			
		if($this->Video->del($id)) {
			$this->Session->setFlash('Video #'.$id.' deleted');
			$this->redirect(array('action'=>'userindex'), null, true);
		}
	}
	
	function tupload($id = null)
	{
		$data = $this->dolayout();	
		$thumb_qr = $this->Video->findbyid($id);
		if($data["id"] != $thumb_qr["Video"]["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["Video"]["user_id"] . md5(time() . str_replace(" ","_",addslashes($uploadFile))) ;
		
		$org_path = $uploadFile.".".$ext;
		
		$thumbwidth = 160;
		$thumbheight = 120;
		$medthumbhei = 360;
		$medthumbwid = 480;
		list($width, $height) = getimagesize($org_path);
		$ratio_orig = $width/$height;
//		echo $orgfile;
		if ($thumbwidth/$thumbheight > $ratio_orig) {
   		  $thumbwidth = $thumbheight*$ratio_orig;
		} else {
		   $thumbheight = $thumbwidth/$ratio_orig;
		}

		if(($ext == "png") || ($ext == "PNG"))
		{
		$newfilename  = $uploadDir .  $hash . $ext;
//		$thumbname = $actualfile;
		$thumbpath = $uploadDir . $hash . "_T" . ".jpg";
		$thumbfile = $hash . "_T" . ".jpg"; //// Path where thumb nail image will be stored
		$tn = imagecreatetruecolor($thumbwidth, $thumbheight);
		$image = imagecreatefrompng($org_path);
		imagecopyresized($tn, $image, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height); 
		imagejpeg($tn, $thumbpath , 100); 

		}
		if(($ext == "jpg") || ($ext == "jpeg") || ($ext == "JPEG") || ($ext == "JPG"))
		{
		$newfilename  = $uploadDir .  $hash . $ext;
//		$thumbname = $actualfile;
		$thumbpath = $uploadDir . $hash . "_T" . ".jpg";
		$thumbfile = $hash . "_T" . ".jpg"; //// Path where thumb nail image will be stored
		$tn = imagecreatetruecolor($thumbwidth, $thumbheight);
		$image = imagecreatefromjpeg($org_path);
		imagecopyresampled($tn, $image, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height); 
		imagejpeg($tn, $thumbpath , 100); 

		}
		if(($ext == "gif") || ($ext == "GIF"))
		{
		$newfilename  = $uploadDir .  $hash . $ext;
//		$thumbname = $actualfile;
		$thumbpath = $uploadDir . $hash . "_T" . ".jpg";
		$thumbfile = $hash . "_T" . ".jpg"; //// Path where thumb nail image will be stored
		$tn = imagecreatetruecolor($thumbwidth, $thumbheight);
		$image = imagecreatefromgif($org_path);
		imagecopyresampled($tn, $image, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height); 
		imagejpeg($tn, $thumbpath , 100); 

		}
		$newfilename = $thumbpath;
		
	if($activeslave["ftpuser"]=="sameserver" && $activeslave["ftppass"]=="sameserver" && $activeslave["ftphost"]=="sameserver")
		{
			rename($newfilename,$activeslave["ftpdirectory"]. DS . $hash . "_T.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 ."_T.jpg"   , $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"] . $hash . "_T.jpg";
		$thumb_qr["Video"]["thumbnailpath"] = $thumbnailpin_path;
		if($this->Video->save($thumb_qr,false))
		{
			$this->Session->SetFlash("Successfully Sent");
			$this->redirect(array('action'=>'index'));
		}
		}
		
	}
	function turlupload($id = null)
	{
		$data = $this->dolayout();	
		$thumb_qr = $this->Video->findbyid($id);
		if($data["id"] != $thumb_qr["Video"]["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']))));
		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["Video"]["user_id"] . md5(time() . str_replace(" ","_",addslashes($uploadFile))) ;
		
		$org_path = $uploadFile.".".$ext;
		
		$thumbwidth = 160;
		$thumbheight = 120;
		$medthumbhei = 360;
		$medthumbwid = 480;
		list($width, $height) = getimagesize($org_path);
		$ratio_orig = $width/$height;
//		echo $orgfile;
		if ($thumbwidth/$thumbheight > $ratio_orig) {
   		  $thumbwidth = $thumbheight*$ratio_orig;
		} else {
		   $thumbheight = $thumbwidth/$ratio_orig;
		}

		if(($ext == "png") || ($ext == "PNG"))
		{
		$newfilename  = $uploadDir .  $hash . $ext;
//		$thumbname = $actualfile;
		$thumbpath = $uploadDir . $hash . "_T" . ".jpg";
		$thumbfile = $hash . "_T" . ".jpg"; //// Path where thumb nail image will be stored
		$tn = imagecreatetruecolor($thumbwidth, $thumbheight);
		$image = imagecreatefrompng($org_path);
		imagecopyresized($tn, $image, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height); 
		imagejpeg($tn, $thumbpath , 100); 

		}
		if(($ext == "jpg") || ($ext == "jpeg") || ($ext == "JPEG") || ($ext == "JPG"))
		{
		$newfilename  = $uploadDir .  $hash . $ext;
//		$thumbname = $actualfile;
		$thumbpath = $uploadDir . $hash . "_T" . ".jpg";
		$thumbfile = $hash . "_T" . ".jpg"; //// Path where thumb nail image will be stored
		$tn = imagecreatetruecolor($thumbwidth, $thumbheight);
		$image = imagecreatefromjpeg($org_path);
		imagecopyresampled($tn, $image, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height); 
		imagejpeg($tn, $thumbpath , 100); 

		}
		if(($ext == "gif") || ($ext == "GIF"))
		{
		$newfilename  = $uploadDir .  $hash . $ext;
//		$thumbname = $actualfile;
		$thumbpath = $uploadDir . $hash . "_T" . ".jpg";
		$thumbfile = $hash . "_T" . ".jpg"; //// Path where thumb nail image will be stored
		$tn = imagecreatetruecolor($thumbwidth, $thumbheight);
		$image = imagecreatefromgif($org_path);
		imagecopyresampled($tn, $image, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height); 
		imagejpeg($tn, $thumbpath , 100); 

		}
		$newfilename = $thumbpath;
		
	if($activeslave["ftpuser"]=="sameserver" && $activeslave["ftppass"]=="sameserver" && $activeslave["ftphost"]=="sameserver")
		{
			rename($newfilename,$activeslave["ftpdirectory"]. DS . $hash . "_T.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 ."_T.jpg"   , $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"] . $hash . "_T.jpg";
		$thumb_qr["Video"]["thumbnailpath"] = $thumbnailpin_path;
		if($this->Video->save($thumb_qr,false))
		{
			$this->Session->SetFlash("Successfully Sent");
			$this->redirect(array('action'=>'index'));
		}
		}
		
	}

	function thumbupload($id = null)
	{
		$this->dolayout();
		$categories = $this->Video->Category->find('list');
		$this->set(compact('categories'));
		$setting = $this->Sitesetting->findbyid(1);
		$this->set('setting',$setting["Sitesetting"]);
		$this->set('id',$id);
	}
	function upload($id = null)
	{
		$this->dolayout();
		$categories = $this->Video->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->Video->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);
	}
	
/*	function mcompleteupload()
	{
		//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);
	
	


		$video =$this->Video->findbyid($this->params["pass"][0]);
		$actualfile = $uploadDir . str_replace(" ","_",addslashes($this->params["form"]["filename"])) . ".flv";
		$hash =  $video["Video"]["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);
			}
		}
		
		$video["Video"]["fspath"] =  $newfilename;
		
		$video["Video"]["size"] =  (int)$this->params["form"]["filesize"];
		$video["Video"]["path"] = $activeslave["httppath"] . $hash . ".flv";
		
		if($defaultthumb == 1)
		$video["Video"]["thumbnailpath"] = $ssettings["Sitesetting"]["DefaultThumbNail"] ;
		else
		$video["Video"]["thumbnailpath"] =  $activeslave["httppath"] . $hash . ".jpg";
		
		$video["Video"]["type"] = $this->params["form"]["filetype"];
		$video["Video"]["created"] = date("Y-m-d h-i-s");
		
		//Remove actual file
			//unlink($uploadDir . $unencodedfile);
			
		if($this->Video->save($video,false)){
		$this->Session->setFlash('The Video has been saved and it is Encoded now');
			} else {
			$this->Session->setFlash('The Video 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']) {
//Debugway	file_put_contents("e:\\iknowiknow.txt",print_r($_POST,true));
	$uploadDir = WWW_ROOT . 'files/';
	$uploadFile = $uploadDir . md5(str_replace(" ","_",(addslashes(basename($_FILES['Filedata']['name'])))));
	move_uploaded_file($_FILES['Filedata']['tmp_name'], $uploadFile);
	
	
	return $uploadFile;
	  }
	}
	else
	{
	    // REGULAR (JAVASCRIPT-OFF) FORM PROCESSING
    	return 'jqUploader disactivated';
	}

	}

	
	function muploaded()
	{
	set_time_limit(0);
//debug($_FILES);
	$ssettings = $this->Sitesetting->findbyid(1);
    if ($_FILES['Filedata']['name']) {
//Debugway	
//	file_put_contents("e:\\iknowiknow.txt",print_r($_POST,true) . print_r($_FILES,true));
	$uploadDir = WWW_ROOT . 'files/';
	$uploadFile = $uploadDir . md5(str_replace(" ","_",(addslashes(basename($_FILES['Filedata']['name'])))));
	move_uploaded_file($_FILES['Filedata']['tmp_name'], $uploadFile);
	$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;
		
	//	debug($this->params);
		
		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 = "( `Video`.desc LIKE '%" . $squery . "%' OR `Video`.tags LIKE '%" . $squery . "%' OR `Video`.name LIKE '%" . $squery . "%' )";
				$sortby = "`Video`.views DESC ";
				}
				elseif($this->params["named"]["sort"]=='date')
				{
				
				$condition = "( `Video`.desc LIKE '%" . $squery . "%' OR `Video`.tags LIKE '%" . $squery . "%' OR `Video`.name LIKE '%" . $squery . "%' )";
				$sortby = "`Video`.created DESC ";
				
				}
				
				elseif($this->params["named"]["sort"]=='category')
				{
				$this->set('rsscategory',$this->params["named"]["cname"]);
				$condition = "(( `Video`.desc LIKE '%" . $squery . "%' OR `Video`.tags LIKE '%" . $squery . "%' OR `Video`.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 = "(( `Video`.desc LIKE '%" . $squery . "%' OR `Video`.tags LIKE '%" . $squery . "%' OR `Video`.name LIKE '%" . $squery . "%' ) AND `Video`.user_id = '" . urldecode($this->params["named"]["cname"]) . "')";
				
				
				}
				
				elseif($this->params["named"]["sort"]=='rating')
				{
				
						
				$condition = " (`Video`.desc LIKE '%" . $squery . "%' OR `Video`.tags LIKE '%" . $squery . "%' OR `Video`.name LIKE '%" . $squery . "%') GROUP BY `Rating`.video_id ";
				
				$countcondition = " `Video`.desc LIKE '%" . $squery . "%' OR `Video`.tags LIKE '%" . $squery . "%' OR `Video`.name LIKE '%" . $squery . "%'";
				
//				"`Rating`.`video_id` = " . $id,array("Avg(`Rating`.`rating`) as average"
				
				$sortby = "avgrate DESC,maxrate DESC ";
				
				
				}
				
				
				
			}
			
			else
			{
				$condition = "((`Video`.name LIKE '%" . $squery . "%' AND `Video`.tags LIKE '%" . $squery . "%') OR `Video`.desc LIKE '%" . $squery . "%' OR `Video`.tags LIKE '%" . $squery . "%' OR `Video`.name LIKE '%" . $squery . "%')";
				
		

			}
			

		
		$condition .= " AND (`Video`.is_encoded = 1) ";
		
		
		if(isset($this->params["named"]["sort"]))
		{
		if($this->params["named"]["sort"]=='rating')
		{
		$this->Pagination->total = $this->Video->Rating->findCount($countcondition);
		list($order,$limit,$page) = $this->Pagination->init($condition,NULL,array('page'=>$this->page,'show'=>$this->show));
		$ntvideo = $this->Video->Rating->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)); 
			$ntvideo = $this->Video->findAll($condition,NULL,$sortby,$limit,$page);
		}
		}
		else
		{
			list($order,$limit,$page) = $this->Pagination->init($condition,NULL,array('page'=>$this->page,'show'=>$this->show));
			$ntvideo = $this->Video->findAll($condition,NULL,$sortby,$limit,$page);
		}
		
			
				//debug($ntvideo);
			$allvideo = $ntvideo;
			
			foreach (array_keys($allvideo) as $key)
			{
				$video =& $allvideo[$key];
				$video["Video"]["rating"] = $this->Video->vrating($video["Video"]["id"]);
				$video["Video"]["rating"] = $video["Video"]["rating"][0]["average"];
			}
			
			$this->set("squery",$squery);
			$this->set("svideo",$allvideo);
			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 Video');
			$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");
			
		$video = $this->Video->findbyid($id);
		$video["Video"]["abusepoints"] +=  $abval;
		
		$this->Video->save($video);
		$this->Session->setFlash('Abuse Reported ');
			$this->layout= false;
		 Configure::write('debug', '0');
	}
	

	
	function fetchurl()
	{
	//	die(pr($this->params,true));
		set_time_limit(0);
		$user = $this->dolayout();
		
		$details = $this->data["Video"];
		$unencodedfile = str_replace(" ","_",addslashes($details["url"]));
		
		$uploadDir = WWW_ROOT . 'files' . DS;
		$uploadfilepath = $uploadDir . md5($unencodedfile)  ;
		
		$ext = substr(strrchr($details["url"], "."), 1);
		
		if(!$this->simulatedownload($details["url"],$uploadfilepath ))
		{
		echo ('Error on retrieving  , please try another url or check if remote server is online, Go back and try again ');
		}
		$video =$this->Video->findbyid($details["id"]);
		$this->encode($details["id"],$unencodedfile);
		$this->set('id',$details["id"]);
	}
	
	function encode($id,$unencodedfile,$ext=null){
		ignore_user_abort(TRUE);
		set_time_limit(0);
		$ssettings = $this->Sitesetting->findbyid(1);
		$slave = $this->Slaveserver->findbyid($ssettings["Sitesetting"]["ActiveSlave"]);
		$activeslave = $slave["Slaveserver"];
		
		$videoresolution = $ssettings['Sitesetting']['VideoWidth'] . 'x' . $ssettings['Sitesetting']['VideoHeight'];
		//encode it
		
		$uploadDir = WWW_ROOT . 'files' . DS;
		$uploadfilepath = $uploadDir . md5($unencodedfile) ;
	$ffmpegpath = $ssettings["Sitesetting"]["FFMPEGPath"];
	$encodecmd = $ffmpegpath . " -i " . 	$uploadfilepath . " " . $ssettings['Sitesetting']['FFmpegArgs'] . " -y " . " -s " . $videoresolution  . " " . $uploadfilepath . ".flv";
	

	$ret = system($encodecmd);
	
	if($ssettings["Sitesetting"]["Flvtool2Path"] != ""){
	$flvtool2 = $ssettings["Sitesetting"]["Flvtool2Path"];
	$flvtool2cmd = $flvtool2 .  " -UP " . $uploadfilepath . ".flv";
	$ret = system($flvtool2cmd);
	}
	

	//die($uploadfilepath);
	if (file_exists($uploadfilepath . ".flv") ){
	
	
	$thumb = $ffmpegpath . " -i " . $uploadfilepath . " -y -v 0 -f mjpeg -ss 5 -vframes 1 -s 160x120 -an " . 	$uploadfilepath . ".jpg";
	
	$ret2 = system($thumb);
	
	


		$video =$this->Video->findbyid($id);
		
		//Special for Multi upload
		if((int)$video["Video"]["is_encoded"]==1)
		{
			
			//temp video array to lick all what we need from that 
			$tvideo = $video;
			$this->Video->create();
			$tvideo["Video"]["id"]= $this->Video->getLastInsertId();
			$this->Video->save($tvideo);
			$video = $this->Video->findbyid($tvideo["Video"]["id"]);
		}
		$actualfile = $uploadfilepath . ".flv";
		$hash =   md5(time() . $unencodedfile) ;
		$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);
			}
		}
		
		$video["Video"]["fspath"] =  $newfilename;
		$video["Video"]["is_encoded"]  = 1;
		$video["Video"]["size"] =  (int)filesize($newfilename);
		$video["Video"]["path"] = $activeslave["httppath"] . $hash . ".flv";
		
		if($defaultthumb == 1)
		{
		//Music Thumbnail
//		echo(stristr($ssettings['Sitesetting']['MusicExtensions']));
//		echo (stristr($ssettings['Sitesetting']['MusicExtensions'], $ext));
//		die($ext);
		if(stristr($ssettings['Sitesetting']['MusicExtensions'], $ext) !== FALSE)
		$video["Video"]["thumbnailpath"] = $ssettings["Sitesetting"]["MusicThumbNail"] ;
		else
		$video["Video"]["thumbnailpath"] = $ssettings["Sitesetting"]["DefaultThumbNail"] ;
		}
		else
		$video["Video"]["thumbnailpath"] =  $activeslave["httppath"] . $hash . ".jpg";
		
		$video["Video"]["type"] = $ext;
		$video["Video"]["created"] = date("Y-m-d h-i-s");
		
		//Remove actual file
			unlink($uploadfilepath);
			
			
		if($this->Video->save($video,false)){
		$this->Session->setFlash('The Video has been saved and it is Encoded now');
			} else {
			$this->Session->setFlash('The Video could not be saved. Please, try again.');
			}
			
		
	}
	else
	{
		$this->set('ftpstatus','This file couldnt be Encoded Sorry');
	}
	
	
	$this->render('completeupload');
	}
	
	function simulatedownload ($file_source, $file_target)
	{

		if (strstr($file_source,"youtube.com")){
		$data = @file_get_contents($file_source);
		@preg_match('#/watch_fullscreen\?video_id=([a-z0-9-_]+)&l=([0-9]+)&t=([a-z0-9-_]+)#i', $data, $matches);
		if (ereg($matches[1], $file_source)) {
			$file_source=("http://www.youtube.com/get_video?video_id=$matches[1]&l=$matches[2]&t=$matches[3]");
		} 
	}
		
	/*if (strstr($file_source,"video.google.com")){
		$file=@file($url);
		$count=count($file);

		$main="";
		for ($i=0;$i<$count;$i++){
			$main=$main.$file[$i];
		}


		$parse=explode("http://vp.video.google.com",$main);
		$parse1=explode('"',$parse[1]);
		$google="http://vp.video.google.com".$parse1[0];
		$google=str_replace('&amp;','&',$google);

		$file_source=$google;

	}*/
	

	if (strstr($file_source,"ifilm.com")){
		$file=@file($url);
		$count=count($file);
	
		$flag=0;
		for ($i=0;$i<$count;$i++){
			if (strstr($file[$i],"so.addVariable") and strstr($file[$i],"getStream")){
					$main=$file[$i]; $flag=1; break;
			}
		}

	if ($flag==1){
		$parse=explode("http://",$main);
		$parse1=explode("?e=",$parse[1]);

		$ifilm="http://".$parse1[0]."?e=";
		$file_source=("$ifilm");
		}
		if ($flag==0){
			$file_source=("http://ifilm-840.vo.llnwd.net/o/contentstore/getStream/2826840_300.flv?e=");
		}
	}


	if (strstr($file_source,"blip.tv")){
		$file=@file($url);
		$count=count($file);

		for ($i=0;$i<$count;$i++){
			if (strstr($file[$i],"setPrimaryMediaUrl")){
				$main=$file[$i]; break;
			}
		}

		$parse=explode('setPrimaryMediaUrl("',$main);
		$parse1=explode('?source=',$parse[1]);

		$blip=$parse1[0];
		$file_source=$blip;
	}

	if (strstr($file_source,"break.com")){
		$file=@file($url);
		$count=count($file);

		$main="";
		for ($i=0;$i<$count;$i++){
			$main=$main.$file[$i];
		}

		$parse=explode("sGlobalFileName='",$main);
		$parse1=explode("'",$parse[1]);

		$name=$parse1[0];


		$parse2=explode("sGlobalContentFilePath='",$main);
		$parse3=explode("'",$parse2[1]);

		$fp=$parse3[0];
		$break="http://media1.break.com/dnet/media/".$fp."/".$name.".flv";
		$file_source=$break;

	}
		

	
  // 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;
}

	
function addflv()
	{
		$user = $this->dolayout();
		
		$details = $this->data["Video"];
		$video =$this->Video->findbyid($details["id"]);
		$video["Video"]["is_encoded"]  = 1;
		$video["Video"]["is_embedded"]  = 0;
		$video["Video"]["path"] = $details['url'];
		$video["Video"]["thumbnailpath"] = $details['thumburl'];
		
		if($this->Video->save($video,false)){
		$this->Session->setFlash('The Video has been saved and it is online now');
			} else {
			$this->Session->setFlash('The Video could not be saved. Please, try again.');
			}
			$this->set('id',$details["id"]);
			$this->render("completeupload");
		
	}
	

	function embedvideo()
	{
		$user = $this->dolayout();
		
		$details = $this->data["Video"];
		$video =$this->Video->findbyid($details["id"]);
		$video["Video"]["is_encoded"]  = 1;
		$video["Video"]["is_embedded"]  = 1;
		$video["Video"]["embedcode"] = $details['url'];
		$video["Video"]["thumbnailpath"] = $details['thumburl'];
		
		if($this->Video->save($video,false)){
		$this->Session->setFlash('The Video has been saved and it is online now');
			} else {
			$this->Session->setFlash('The Video could not be saved. Please, try again.');
			}
			$this->set('id',$details["id"]);
			$this->render("completeupload");
		
	}

}
?>
Return current item: OSShare