<?php 
class zMusic extends father{
	
public function user(){
	if(isset($_COOKIE[user_cookie])){
		global $b;
		$cToken = $_COOKIE[user_cookie];
		$expiryNow = time();
		$inDB = $this->select("SELECT expiry FROM users_sess WHERE token=? AND expiry>? LIMIT 1", array($cToken, time()), "ss");
		if($inDB->count == 0){
			return $this->json(array('result' => 'fail', 'reason' => 'Invalid token'), true); exit;
		}
		@list($UID, $hashUID, $expiry, $browserName, $browserVersion, $browserOS) = explode("@@", $this->decode($cToken));
		if(empty($UID) || empty($hashUID)){
			return $this->json(array('result' => 'fail', 'reason' => 'Empty User ID'), true); exit;
		}
		if($browserName!=$b->getBrowser() || $b->getVersion()!=$browserVersion || $b->getPlatform()!=$browserOS){
			return $this->json(array('result' => 'fail', 'reason' => 'Browser mismatched'), true); exit;
		}
		if(!is_numeric($UID) || $UID <= 0){ return $this->json(array('result' => 'fail'), true); exit; }
		$user = $this->select("SELECT * FROM users WHERE ID=? AND status!=? AND status!=? LIMIT 1",
		array($UID, 'banned', 'deleted'), "iss");
		if($user->count==0){ return $this->json(array('result' => 'fail', 'reason' => 'User not exists'), true); exit; }
		$dp = baseurl.'dp/'.$this->encode($user->row->dp).'/100x100/picture.jpg';							
		$time = time();
		$this->update("UPDATE users SET last_login=? WHERE ID=? LIMIT 1", array(time(),$UID), "si");
		return $this->json(array(
			'result' => 'ok',
			'ID' => $UID,
			'name' => array(
				'first' => $user->row->fname, 
				'last' => $user->row->lname, 
				'full' => $user->row->fname.' '.$user->row->lname
			),
			'email' => $user->row->email,
			'me' => $user->row,
			'type' => $user->row->utype,
			'dp' => $dp
		), true);
		exit;
	}
	return $this->json(array('result' => 'failed'), true);
}

public function isSessAdmin($yid, $token){
	$expiryNow = time();
	$inDB = $this->select("SELECT expiry FROM users_sess WHERE token=? AND expiry>? LIMIT 1", array($token, time()), "ss");
	if($inDB->count == 0){
		return $this->json(array('result' => 'fail'), false); exit;
	}
	@list($UID, $hashUID, $expiry, $browserName, $browserVersion, $browserOS) = explode("@@", $this->decode($token));
	if(empty($UID) || empty($hashUID) || $yid!=$UID){
		return $this->json(array('result' => 'fail'), false); exit;
	}
	if(!is_numeric($UID) || $UID <= 0){ return $this->json(array('result' => 'fail'), false); exit; }
	$user = $this->select("SELECT * FROM users WHERE ID=? AND status!=? AND status!=? LIMIT 1",
	array($UID, 'banned', 'deleted'), "iss");
	if($user->count==0){ return $this->json(array('result' => 'fail'), false); exit; }
	if($user->row->utype=="admin" || $user->row->utype=="moderator"){
		return $this->json(array('result' => 'ok'), false); exit;
	}else{
		return $this->json(array('result' => 'fail'), false); exit;
	}
	exit;
}

public function signup($uid, $email, $utype, $fname, $lname, $offline, $mod = 'google'){
	global $b; global $hash;	
	$_isa = array('admin','moderator');
	$utoken = $this->randit(12);		
	$ucode = $this->randit(8);
	$accesstoken = strtolower($this->randit(20));
	$expiry = time() + (86400 * 7);
	$browserInfo = $b->getBrowser().'@@'.$b->getVersion().'@@'.$b->getPlatform();
	$time = time();					
	$geo = $this->Geo($this->myip()); $location = is_object($geo) ? $geo->IP.'@@'.$geo->city.'@@'.$geo->country : 'none@@none@@none';		
	$chk = $this->select("SELECT ID,utype,email,fname,lname FROM users WHERE googleid=? OR email=? LIMIT 1", array($uid,$email), "ss");
	$ruri = $offline=='yes' && in_array($chk->row->utype, $_isa) ? baseurl.'admin/dashboard' : baseurl;
	
	if($chk->result=="ok" && $chk->count > 0){
		$_UID = (int) $chk->row->ID;		
		$update = $this->update("UPDATE users SET token=?,last_login=?,last_login_location=? WHERE ID=? LIMIT 1", 
		array($accesstoken,time(),$location,$_UID), "sssi");		
		//$cookie = $this->encode($_UID.'@@'.$hash->encode($_UID).'@@'.$expiry.'@@'.$browserInfo);
		$cookie = $this->encode($_UID.'@@'.$hash->encode($_UID).'@@'.$expiry.'@@'.$browserInfo);
		$uinfo = $browserInfo.'@@'.$location;					
		$this->insert("INSERT INTO users_sess (uid,token,expiry,uinfo) VALUES (?,?,?,?)",array($_UID,$cookie,$expiry,$uinfo), "isss");
		$this->cookie(user_cookie, $cookie, 24*7);
		return $this->json(array(
			'result' => 'ok',
			'uri' => $ruri,
			'message' => 'Redirecting...'
		)); exit;
	}else{		
		$password = $this->randit(8);
		$pass = $this->encode($password);		
		$nDP = "no-dp.png";
		if($mod=="google"){
			$idField = "googleid";
			$xdp = parse_url($this->getDP($uid, 0)->dp);
			$dp = $xdp['scheme'].'://'.$xdp['host'];
			$dp .= str_replace("/s64-c/", "/s500-c/", $xdp['path']);
			$nDP = $uid.'.jpg';
			@file_put_contents(realpath(__DIR__ . '/..') . "/assets/dps/".$nDP, @file_get_contents($dp));
		}else{
			$idField = "fbid";
			//save dp from facebook
		}
		$new = $this->insert("INSERT INTO users (token,ucode,utype,".$idField.",email,password,fname,lname,dp,join_date,join_location,last_login,last_login_location,status)
		VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", array($utoken,$ucode,$utype,$uid,$email,$pass,$fname,$lname,$nDP,time(),$location,time(),$location,'active'),
		"sssissssssssss");
		if($new->result!="ok"){
			return $this->json(array(
				'result' => 'failed',				
				'message' => 'This is not you, this is us. We are facing problems in processing your request...'
			), false); exit;
		}
		
		$_UID = $new->ID;		
		$cookie = $this->encode($_UID.'@@'.$hash->encode($_UID).'@@'.$expiry.'@@'.$browserInfo);
		$uinfo = $browserInfo.'@@'.$location;					
		$this->insert("INSERT INTO users_sess (token,expiry,uinfo) VALUES (?,?,?)",array($cookie,$expiry,$uinfo), "sss");
		$this->cookie(user_cookie, $cookie, 24*7);
		$serviceName = $mod == 'google' ? 'Google' : 'Facebook';
		$_mail = $this->getMail(
			'Welcome to '.SITE_NAME.' '.$fname.'!', 
			'Hey '.strtolower($fname).', Welcome to '.SITE_NAME.' :)<br>We\'re incredibly excited to have you on board and tell this is the beginning of something beautiful.<br><br>
			Sine this is a beta, not everything will be perfect yet. But with your help, we can make '.SITE_NAME.' as beautiful and easy to use as possible.<br><br>
			Your feedback and requests are very welcomed and encouraged at <b>'.admin_email.'</b><br><br>
			Cheers!<br>
			The '.SITE_NAME.' Team'
		);
		$this->SendMail(
			array('user' => MAIL_FROM, 'pass' => MAIL_PASSWORD, 'name' => SITE_NAME),
			array('mail' => $email, 'name' => $fname.' '.$lname),
			'Welcome to '.SITE_NAME,
			$_mail
		);
		return $this->json(array(
			'result' => 'ok',
			'uri' => $ruri,
			'message' => 'Redirecting...'
		));	
		exit;
	}		
}	
	
public function isAdmin($session){
	$is = array('admin','moderator');
	return $session->result=="ok" && in_array($session->type, $is) ? true : false;
}

public function addServer($title, $url, $disk){
	$this->insert("INSERT INTO servers (title,address,tspace) VALUES(?,?,?)", array($title,$url,$disk), "ssi");
}
	
public function isValidSession($session, $uid, $token, $checkForAdmin = false){
	global $hash;
	$uid = (int) $hash->decode($uid)[0];
	@list($coken) = explode("@@", $this->decode($token));
	if($_COOKIE[user_cookie]!=$coken || $session->ID!=$uid){
		return $this->json(array('result' => 'failed'), true);
	}	
	if($checkForAdmin==true){
		if($this->isAdmin($session)==true){
			return $this->json(array('result' => 'ok'), true);			
		}else{
			return $this->json(array('result' => 'failed'), true);	
		}
	}else{
		return $this->json(array('result' => 'ok'), true);
	}	
}	
	
public function getSetting($field){
	return $this->select("SELECT valu FROM settings WHERE optn=? LIMIT 1", array($field), "s")->row->valu;
}

public function getDP($gid, $fbid){
	if($gid!=0){
		$json = @json_decode(str_replace("$", "", $this->_CURL("http://picasaweb.google.com/data/entry/api/user/".$gid."?alt=json", false)))->entry;
		return $this->json(array(
			'name' => $json->gphotonickname->t,
			'dp' => $json->gphotothumbnail->t
		), true);
	}
}	

public function toHMS($seconds) {
  $t = round($seconds);
  return sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60);
}

public function streamLink($item){
	$format = '128';
	if(strpos($item->formats, ",")!==false){
		@list($format) = explode(",", $item->formats);
	}else{
		$format = $item->formats;
	}
	return $this->encode($item->ID.'@@'.$item->server.'@@'.$item->filename.'@@'.$format.'@@'.stripslashes($item->title).'@@'.time());
}

public function trackItem($item, $isad = false){
	if($isad==true){
		return '<li class="rel track-ad">'.$item.'</li>';
	}else{
		global $hash;
		$trackTitle = stripslashes($item->title);
		$dTitle = strlen($trackTitle) > 45 ? substr($trackTitle, 0, 45).'...' : $trackTitle;
		$s = $item->views > 1 ? "s" : "";
		$img = baseurl.'photo/track/'.$this->encode($item->poster.'@@'.$item->type).'/default.jpg';
		$stream = $this->streamLink($item);
		$li = '<li class="rel"><a href="'.baseurl.'track/'.$item->slug.'" class="bl noul anim init-track rel" '
			. 'title="'.stripslashes($item->title).'" data-slug="'.$item->slug.'" data-artist="'.$item->artist.'" data-img="'.$img.'" '
			. 'data-stream="'.$stream.'" data-duration="'.$this->toHMS($item->duration).'" data-id="'.$hash->encode($item->ID).'" data-formats="'.$item->formats.'">'
			. '<div class="ovr abs anim"><div class="abs ico icon-play_arrow"></div></div>'
			. '<div class="mThumb mibl">'
				. '<img src="'.$img.'" class="bl poster">'
			. '</div>'
			. '<div class="mDet mibl">'
				. '<h2 class="size13 fontb naam">'.$dTitle.'</h2>'
				. '<h2 class="size13 fontn loops">'.number_format($item->views).' loop'.$s.'</h2>'
			. '</div>'
			. '</a></li>';
		return $li;
	}
}

public function trackItemAdmin($item){
	global $hash;
	$trackTitle = stripslashes($item->title);
	$dTitle = strlen($trackTitle) > 45 ? substr($trackTitle, 0, 45).'...' : $trackTitle;
	$s = $item->views > 1 ? "s" : "";
	$img = baseurl.'photo/track/'.$this->encode($item->poster.'@@'.$item->type).'/default.jpg';
	$stream = $this->streamLink($item);
	$li = '<li class="rel atrack'.$hash->encode($item->ID).'"><a href="'.baseurl.'track/'.$item->slug.'" class="bl noul anim init-track rel" '
		. 'title="'.stripslashes($item->title).'" data-slug="'.$item->slug.'" data-artist="'.$item->artist.'" data-img="'.$img.'" '
		. 'data-stream="'.$stream.'" data-duration="'.$this->toHMS($item->duration).'" data-id="'.$hash->encode($item->ID).'" data-formats="'.$item->formats.'">'
		. '<div class="ovr abs anim"><div class="abs ico icon-play_arrow"></div></div>'
		. '<img src="'.$img.'" class="bl poster">'
		. '<h2 class="size13 fontb naam">'.$dTitle.'</h2>'
		. '<h2 class="size13 fontn loops">'.number_format($item->views).' loop'.$s.'</h2></a>'		
		. '<button class="editBtn bl size13 fontn anim" '
			. 'data-album="'.$hash->encode($item->albumid).'" '
			. 'data-genre="'.$hash->encode($item->genre).'" '
			. 'data-title="'.stripslashes($item->title).'" '
			. 'data-tags="'.stripslashes($item->tags).'" '
			. 'data-artist="'.stripslashes($item->artist).'" '
			. 'data-poster="'.$img.'" '			
			. 'data-id="'.$hash->encode($item->ID).'" '
		. '>Edit</button>'
		. '<a href="javascript:;" class="size11 noul noulh rmTrack" data-id="'.$hash->encode($item->ID).'">Delete</a>'
		. '</li>';
	return $li;
}

public function trackItemPlaylist($item, $playlistID){
	global $hash;
	$trackTitle = stripslashes($item->title);
	$dTitle = strlen($trackTitle) > 45 ? substr($trackTitle, 0, 45).'...' : $trackTitle;
	$s = $item->views > 1 ? "s" : "";
	$img = baseurl.'photo/track/'.$this->encode($item->poster.'@@'.$item->type).'/default.jpg';
	$stream = $this->streamLink($item);
	$li = '<li class="rel anim pitem'.$hash->encode($item->ID).'"><a href="'.baseurl.'track/'.$item->slug.'" class="bl noul anim init-track rel" '
		. 'title="'.stripslashes($item->title).'" data-slug="'.$item->slug.'" data-artist="'.$item->artist.'" data-img="'.$img.'" '
		. 'data-stream="'.$stream.'" data-duration="'.$this->toHMS($item->duration).'" data-id="'.$hash->encode($item->ID).'" data-formats="'.$item->formats.'">'
		. '<div class="ico icon-notes-outline ibl"></div>'
		. '<div class="info ibl">'
			. '<h2 class="size14 fontn bl wordwrap naam">'.$dTitle.'</h2>'
			. '<h2 class="size11 fontn bl wordwrap artist">'.$item->artist.' &#46; '.$this->toHMS($item->duration).'</h2>'
		. '</div>'		
		. '</a><button class="abs bl removeFromPlist anim" data-id="'.$hash->encode($item->ID).'" data-token="'.$this->encode($item->ID.'@@'.$playlistID.'@@'.time()).'">&times;</button>'
		. '<div class="spinner abs"></div></li>';
	return $li;
}

public function playListItem($item){
	global $hash;
	$trackTitle = stripslashes($item->title);
	$s = $item->views > 1 ? "s" : "";
	$img = baseurl.'photo/track/'.$this->encode($item->poster.'@@'.$item->type).'/default.jpg';
	$stream = $this->encode($item->ID.'@@'.$item->server.'@@'.$item->filename.'@@192@@'.$trackTitle.'@@'.time());	
	return $this->json(array(
		'ID' => $hash->encode($item->ID),
		'link' => baseurl.'track/'.$item->slug,
		'title' => $trackTitle,
		'artist' => $item->artist,
		'image' => $img,
		'stream' => $stream,
		'duration' => $this->toHMS($item->duration),
		'formats' => $item->formats,
		'views' => number_format($item->views).' loop'.$s
	), true);	
}

public function getAd($type='all'){
	$device = $this->isMobile() ? 'mobile' : 'desktop';
	$ad = $this->select("SELECT * FROM ads WHERE device=? AND status=? LIMIT 1", array($device,'yes'), "ss");
	if($ad->result=="ok" && $ad->count > 0){
		return $ad->row->code;	
	}
	return 'none';
}

//API
public function apiTrackItem($item){
	global $hash;	
	$genre = $this->select("SELECT * FROM genres WHERE ID=? LIMIT 1", array($item->genre), "i")->row;
	return array(
		'ID' => $hash->encode($item->ID),
		'genre' => array(
			'ID' => $hash->encode($item->genre),
			'label' => stripslashes($genre->title),
			'slug' => stripslashes($genre->slug),
			'trackCount' => number_format($genre->tracks)
		),
		'poster' => baseurl.'photo/track/'.$this->encode($item->poster.'@@'.$item->type).'/default.jpg',
		'title' => stripslashes($item->title),
		'slug' => $item->slug,
		'link' => baseurl.'track/'.$item->slug,
		'tags' => $item->tags,
		'duration' => $this->toHMS($item->duration),
		'artist' => $item->artist,
		'loops' => number_format($item->views),
		'added' => date("d M Y", $item->added),
		'stream' => baseurl.'do/stream?token=' . $this->streamLink($item)
	);
}
	
	
	
	
}
?>