<?php
class scode_upandsell extends Smarty  {
var $accuser;
var $mylang;
	function __construct() {
		parent::__construct(); 
	}
	private function is_valid_email( $email )
	{
		return preg_match( '/[.+a-zA-Z0-9_-]+@[a-zA-Z0-9-]+.[a-zA-Z]+/', $email );
	}
	
	private  function byteFormat($bytes, $unit = "", $decimals = 2) {
		$units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 
				'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
	 
		$value = 0;
		if ($bytes > 0) {
			if (!array_key_exists($unit, $units)) {
				$pow = floor(log($bytes)/log(1024));
				$unit = array_search($pow, $units);
			}
			$value = ($bytes/pow(1024,floor($units[$unit])));
		}
		if (!is_numeric($decimals) || $decimals < 0) {
			$decimals = 2;
		}
		return sprintf('%.' . $decimals . 'f', $value);
	}
	public function get_value_settings($type){
		return @mysql_result(mysql_query("SELECT `value` FROM `settings` WHERE `type`='$type'"),0,0);
	}
	private function query($qr){
		return @mysql_query($qr);
	}
	private function result($qr){
		return @mysql_result(mysql_query($qr),0,0);
	}
	private function numrows($qr){
		return @mysql_num_rows(mysql_query($qr));
	}
	public function fetcharray($qr){
		return @mysql_fetch_array(mysql_query($qr));
	}
	public function checklogin(){
	
		if(!isset($_SESSION['auth']) && !isset($_SESSION['authid'])){

			return false;
		}else{
			$myarray=$this->fetcharray("SELECT * FROM `members` WHERE `username`='".$_SESSION['auth']."'");
			$this->accuser=$myarray;
			return true;
		}
	
	}
	public function verifyregister(){
		if(isset($_POST['register_submit'])){
			$username=$_POST['s_username'];
			$pass=$_POST['s_password'];
			$cpass=$_POST['s_cpassword'];
			$yourname=$_POST['s_name'];
			$email=$_POST['s_email'];
			$ppemail=$_POST['s_paypal_email'];
			$terms=$_POST['terms'];
			$v=true;
			$error=array();
			$this->mylang=$this->getTemplateVars('lang');
				if(!preg_match('/^[a-zA-Z0-9_]+$/',$username)){
				$v=false;
				$error[]=$this->mylang['register_username_incorrect'];
				}
				if($this->is_valid_email($email)==false){
				$v=false;
				$error[]=$this->mylang['register_email_incorrect'];
				}
				if($this->is_valid_email($ppemail)==false){
				$v=false;
				$error[]=$this->mylang['register_paypalemail_incorrect'];
				}
				if($pass != $cpass || strlen($pass)==0){
				$v=false;
				$error[]=$this->mylang['register_password_not_same'];
				}
				if(strlen($yourname)==0){
				$v=false;
				$error[]=$this->mylang['register_name_incorrect'];
				}
				if($terms!="1"){
				$v=false;
				$error[]=$this->mylang['register_termns_incorrect'];
				}
				$getmaildb=$this->numrows("SELECT `id` FROM `members` WHERE `email`='$email' OR `paypalemail`='$ppemail'");
				if($getmaildb > 0 ){
				$v=false;
				$error[]=$this->mylang['register_email_exists'];
				}
				$getusersdb=$this->numrows("SELECT `id` FROM `members` WHERE `username`='$username'");
				if($getusersdb > 0 ){
				$v=false;
				$error[]=$this->mylang['register_username_exists'];
				}
			if($v){
				$md5pass=md5($pass);
				$time=time();
				$timefix=date('d-m-Y');
				$this->query("INSERT INTO `members`(`username`,`password`,`email`,`name`,`paypalemail`,`role`,`register`,`registerfix`) VALUES('$username','$md5pass','$email','$yourname','$ppemail','0','$time','$timefix')");
				$this->assign("success_register",$this->mylang['register_success']);
			}else{
				$this->assign("error_register",$error);
			}
		
		}
	}
	
	public function verifylogin(){
		if(isset($_POST['login_submit'])){
			$username=$_POST['s_username'];
			$pass=$_POST['s_password'];
			$v=true;
			$this->mylang=$this->getTemplateVars('lang');
			if(!preg_match("/[a-zA-Z0-9_\-]+/",$username)){
				$v=false;
				$error[]=$this->mylang['login_username_incorrect'];
			}
			if(strlen($pass)==0){
				$v=false;
				$error[]=$this->mylang['login_password_empty'];
			}
			if($v){
			$passdb=$this->result("SELECT `password` FROM `members` WHERE `username`='$username'");
				if($passdb != md5($pass)){
					$v=false;
					$error[]=$this->mylang['login_username_password_incorrect'];
				}
			}
			
				if($v){
					$this->assign("success_login",$this->mylang['login_success_submit']);
					$_SESSION['auth']=$username;
					$_SESSION['authid']=$this->result("SELECT `id` FROM `members` WHERE `username`='$username'");
					echo "<script type=\"text/javascript\">window.location = \"index.php\"</script>";
				}else{
					$this->assign("error_login",$error);
				}
		
		}
	
	}
	public function verifyfile(){
		if(isset($_POST['file_submit'])){
			$s_file=$_FILES['s_file'];
			$s_product_name=$_POST['s_product_name'];
			$s_product_description=$_POST['s_product_description'];
			$s_product_price=$_POST['s_product_price'];
			$s_product_currency=$_POST['s_product_currency'];
			$s_client_name=$_POST['s_client_name'];
			$s_client_paypal_adress=$_POST['s_client_paypal_adress'];
			$s_client_email=$_POST['s_client_email'];
			$s_distribute_rights=$_POST['s_distribute_rights'];
			$s_tos_rights=$_POST['s_tos_rights'];
			$v=true;
			$vfile=true;
			$this->mylang=$this->getTemplateVars('lang');
				if(isset($s_file)){
					$site_max_file_size=$this->get_value_settings("site_max_file_size");
					$getfiletype=$this->get_value_settings("site_type_file");
					$s_filesize=$this->byteFormat($s_file[size],"MB");
					$ext = pathinfo($s_file['name'], PATHINFO_EXTENSION);
						if(!preg_match("/$ext/i",$getfiletype)){
							$vfile=false;
							$v=false;
							$error[]="$ext".$this->mylang['files_not_allowed'];
						}
						if($s_filesize > $site_max_file_size){
							$vfile=false;
							$v=false;
							$error[]=$this->mylang['files_max_file_size']."$site_max_file_size";
						}
						if($vfile){
						$time=date('d-m-Y');
						$time.="-".time();
						$target_path = "uploads/$time.$ext";
							if(move_uploaded_file($s_file['tmp_name'], $target_path)) {
							$filesuccess=$target_path;
								//$error[]="$target_path";
							} else{
								$error[]=$this->mylang['files_upload_problem'];
							}
						}
				}else{
					$v=false;
					$error[]=$this->mylang['files_upload_empty'];
				}
				if(strlen($s_product_name)==0){
					$v=false;
					$error[]=$this->mylang['files_product_name_empty'];
				}
				if(strlen($s_product_description)==0){
					$v=false;
					$error[]=$this->mylang['files_description_empty'];
				}
				if(!is_numeric($s_product_price)){
					$v=false;
					$error[]=$this->mylang['files_price_error'];
				}
				if(!isset($s_product_currency)){
					$v=false;
					$error[]=$this->mylang['files_currency_error'];
				}
				if(strlen($s_client_name)==0){
					$v=false;
					$error[]=$this->mylang['files_name_empty'];
				}
				if($this->is_valid_email($s_client_paypal_adress)==false){
					$v=false;
					$error[]=$this->mylang['files_paypalemail_empty'];
				}
				if($this->is_valid_email($s_client_email)==false){
					$v=false;
					$error[]=$this->mylang['files_email_empty'];
				}
				if($s_distribute_rights!="1"){
					$v=false;
					$error[]=$this->mylang['files_distribute_rights'];
				}
				if($s_tos_rights!="1"){
					$v=false;
					$error[]=$this->mylang['files_tos_rights'];
				}
					if($v){
							if($_SESSION['auth']){
								$idu=$_SESSION['authid'];
							}else{
								$idu="0";
							}
						$time=time();
						$this->query("INSERT INTO `products`(`idu`,`name`,`price`,`price_value`,`contact_name`,`contact_email`,`contact_paypal`,`register`,`limit`,`description`,`file`) VALUES('$idu','$s_product_name','$s_product_price','$s_product_currency','$s_client_name','$s_client_email','$s_client_paypal_adress','$time','0','$s_product_description','$filesuccess')");
						$prid=mysql_insert_id();
						$this->assign("success_file",$this->mylang['files_success']);
						$this->emailfile($s_client_email,$s_client_name,$s_product_name,$s_product_description,$s_product_price,$s_product_currency,$prid);
					}else{
						$this->assign("error_file",$error);
					}
		}
	}
	public function emailfile($email,$name,$productname,$productdescription,$price,$pricevalue,$prid){
	$website=$this->get_value_settings('site_url');
				$message="<!DOCTYPE html>
				<html>
				<head>
					<title>Email template</title>
					<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-9\" />

					<style type=\"text/css\">
						body {
							padding:0;
							margin:0;
							-webkit-text-size-adjust: none;
						}
					</style>

				</head>
				<body leftmargin=\"0\" topmargin=\"0\" marginwidth=\"0\" marginheight=\"0\" background=\"$website/images/paypal/background.png\">

				<table width=\"100%\" height=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
					<tr>
						<td background=\"$website/images/paypal/background.png\">
							
							<!-- Header -->

								<table width=\"600\" align=\"center\" cellpadding=\"10\" cellspacing=\"0\">
									<tr>
										<td bgcolor=\"white\" background=\"$website/images/paypal/second_background.png\" height=\"180\" align=\"center\">
											<br/><br/><br/><a href=\"#website\"><img src=\"$customlogo\" /></a>
										</td>
									</tr>
								</table>

							<!-- End header -->
							<!-- Content -->

								<table width=\"600\" align=\"center\" cellspacing=\"0\" cellpadding=\"10\">
									<tr>
										<td bgcolor=\"#f8f8f9\">
											
											<p style=\"margin: 0; padding: 0;\">
												<h2 style=\"margin: 0; padding: 0;\"><strong>Hello ".$name.",</strong></h2>
												 you get download link avaible 24 hours !<br/><br/>

												<div style=\"font-size: 14px;\">
												 <strong>Name:</strong> $productname<br/>
												 <strong>Description:</strong> $productdescription<br/>
												 <strong>Price:</strong> $price $pricevalue<br/>
												</div>

											</p>
											<center><img src=\"$website/images/paypal/hr.png\" /></center>
											<p>
												<strong>Here are your buy link:</strong><br/><Br/>
												Buy Page : <a href=\"$website/buy/$prid\">$website/buy/$prid</a><br/>
												Buy direct link : <a href=\"$website/buyredirect/$prid\">$website/buyredirect/$prid</a><br/>
											</p>

										</td>
									</tr>
								</table>

							<!-- end content -->

						</td>
					</tr>
				</table>

				</body>
				</html>";
		
			//mail($_POST['payer_email'], 'Download Link', $message);
			$headers = "MIME-Version: 1.0\r\n";
			$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
			$headers .= "From: UpAndSell\r\n"; 
			mail($email, 'Your Links for Buy', $message,$headers);
	
	}
	public function displayfiles(){
	$text="";
		if($this->numrows("SELECT * FROM `products` WHERE `idu`='".$_SESSION['authid']."'") > 0 ){
	
	if(is_numeric($_GET['fldl'])){
		$this->query("DELETE FROM `products` WHERE `id`='".$_GET['fldl']."' AND `idu`='".$_SESSION['authid']."'");
		$text.="<div class=\"alert alert-error\">".$this->mylang['account_files_delete']."</div>";
	}
	if(is_numeric($_GET['fled'])){
		$idedit= $_GET['fled'];
		$fetch=@mysql_fetch_array(mysql_query("SELECT * FROM `products` WHERE `id`='$idedit' AND `idu`='".$_SESSION['authid']."'"));
		if(!$fetch){
		echo "WRONG";
		exit;
		}		
		if($_POST['submit']){
			$name=$_POST['name'];
			@mysql_query("UPDATE `products` SET `name`='$name' WHERE `id`='$idedit' AND `idu`='".$_SESSION['authid']."'");
			$text.="<div class=\"alert alert-success\">".$this->mylang['account_files_edit_success']."</div>";
		}else{
			
		$text.="
			<form action=\"\" method=\"post\" class=\"form-horizontal\" style=\"width: 450px; margin: 0 auto;\">
				<div class=\"control-group\">
					<label class=\"control-label\" for=\"inputPrice\">Price: </label>
					<div class=\"controls\">
						<input type=\"text\" name=\"price\" id=\"inputPrice\" readonly value=\"$fetch[price] $fetch[price_value]\"/>
					</div>
				</div>
				<div class=\"control-group\">
					<label class=\"control-label\" for=\"inputProductName\">Product name: </label>
					<div class=\"controls\">
						<input type=\"text\" name=\"name\" id=\"inputProductName\" value=\"$fetch[name]\"/>
					</div>
				</div>
				<div style=\"text-align: center;\"><input type=\"submit\" name=\"submit\" class=\"btn btn-primary btn-large\" style=\"width: 300px;\" /></div>
			</form>";
		}
	}
	if(is_numeric($_GET['fllk'])){
		$idfl=$_GET['fllk'];
		$website=$this->get_value_settings('site_url');
	$text.="<legend class=\"clearfix\">
				
				<div class=\"file_link\" style=\"float:left\">
					<p>Sale Page link <input type=\"text\" value=\"$website/buy/$idfl\" class=\"input-xxlarge\" /></p>
					<p>Direct paypal link <input type=\"text\" value=\"$website/buyredirect/$idfl\" class=\"input-xxlarge\" /></p>
				</div>
			</legend>";	
	}
	if(is_numeric($_GET['flst'])){
		$idedit=$_GET['flst'];
		$getnamefile=$this->result("SELECT `name` FROM `products` WHERE `id`='$idedit'");
		$getlastdate=@mysql_result(mysql_query("SELECT `date` FROM `sales` WHERE `idu`='".$_SESSION['authid']."' AND `idp`='$idedit' ORDER BY `date` ASC LIMIT 1"),0,0);
			$sir=array();
			$sirtips=array();
			$numar=array();
			if($getlastdate){
				$datenow=date('d-m-Y',$getlastdate);
			}else{
				$datenow=date('d-m-Y');
			}
			$sir[]="'".$datenow."'";
			$numarquery=@mysql_num_rows(mysql_query("SELECT `id` FROM `sales` WHERE `datefix`='$datenow' AND `idu`='".$_SESSION['authid']."' AND `idp`='$idedit'"));
			$numar[]=$numarquery;
			$sirtips[]="'$numarquery new sales'";
				for ($i = 1; $i <= 10; $i++) {
					if($getlastdate){
						$nextdate=date('d-m-Y', strtotime('+'.$i.' day',$getlastdate));
					}else{
						$nextdate=date('d-m-Y', strtotime('+'.$i.' day'));
					}
					$sir[]="'".$nextdate."'";
					$numarquery=@mysql_num_rows(mysql_query("SELECT `id` FROM `sales` WHERE `datefix`='$nextdate' AND `idu`='".$_SESSION['authid']."' AND `idp`='$idedit'"));
					$numar[]=$numarquery;
					$sirtips[]="'$numarquery new sales'";
				}
			$sir=implode(",",$sir);
			$sirtips=implode(",",$sirtips);
			$numar=implode(",",$numar);
		$text.="<script type=\"text/javascript\">
$(document).ready(function(){
	
		var line2 = new RGraph.Bar('cvs', [$numar]);
            line2.Set('chart.filled', true);
            line2.Set('chart.fillstyle', ['transparent']);
            line2.Set('chart.colors', ['red']);
            line2.Set('chart.linewidth', 2);
            line2.Set('chart.hmargin', 5);
            line2.Set('chart.tickmarks', 'circle');
            line2.Set('chart.labels', [$sir]);
            line2.Set('chart.tooltips', [$sirtips]);
           // line2.Draw();
		   RGraph.Effects.Fade.In(line2);
});
</script>
<h3>Stats for $getnamefile </h3>	
	<canvas id=\"cvs\" width=\"920\" height=\"400\">[No canvas support]</canvas>";
		
		
	}
		
			$text.= "<table class=\"table table-bordered table-hover\">
					<thead>
						<tr>
							<td width=\"10\">#</td>
							<td>File Name</td>
							<td>Date Added</td>
							<td>Sales</td>
							<td width=\"170\">Actions</td>
						</tr>
					</thead>
					<tbody>";
				$filequery=$this->query("SELECT * FROM `products` WHERE `idu`='".$_SESSION['authid']."'");
				
					while($rowfile=@mysql_fetch_array($filequery)){
					$sales=$this->numrows("SELECT `id` FROM `sales` WHERE `idp`='$rowfile[id]' AND `idu`='".$_SESSION['authid']."'");
						$text.= "<tr>
								<td width=\"10\">$rowfile[id]</td>
								<td>$rowfile[name]</td>
								<td>".date("d-m-Y",$rowfile[register])."</td>
								<td>$sales</td>
								<td width=\"300\"><a href=\"files&fled=$rowfile[id]\" class=\"btn btn-info\"><i class=\"icon-pencil icon-white\"></i> Edit</a> <a href=\"files&fldl=$rowfile[id]\" class=\"btn btn-danger\"><i class=\"icon-remove icon-white\"></i> Delete</a> <a href=\"files&flst=$rowfile[id]\" class=\"btn btn-success\"><i class=\"icon-signal icon-white\"></i> Statistics</a> <a href=\"files&fllk=$rowfile[id]\" class=\"btn btn-info\"><i class=\"icon-download-alt icon-white\"></i> Links</a></td>
							</tr>";
					}
				
			$text.= "	</tbody>
				 </table>";
		}else{
			$text= "<h1>".$this->mylang['account_files_notfound']."</h1>";
		}
	return $text;
	}
	
	
	
	public function verifysettings(){
		if(isset($_POST['s_user_submit'])){
			$s_user_name=$_POST['s_user_name'];
			$s_user_email=$_POST['s_user_email'];
			$s_user_paypalemail=$_POST['s_user_paypalemail'];
			$v=true;
				if(strlen($s_user_name)==0){
					$v=false;
					$error[]=$this->mylang['account_settings_name_empty'];
				}
				if($this->is_valid_email($s_user_paypalemail)==false){
					$v=false;
					$error[]=$this->mylang['account_settings_paypalemail_incorrect'];
				}
				if($this->is_valid_email($s_user_email)==false){
					$v=false;
					$error[]=$this->mylang['account_settings_email_incorrect'];
				}
					if($v){
						$this->query("UPDATE `members` SET `name`='$s_user_name',`email`='$s_user_email',`paypalemail`='$s_user_paypalemail' WHERE `id`='".$_SESSION['authid']."'");
						$this->assign("success_settings",$this->mylang['account_settings_success']);
					}else{
						$this->assign("error_settings",$error);
					}
		}
	}
	public function verifystats(){
			$getlastdate=@mysql_result(mysql_query("SELECT `date` FROM `sales` WHERE `idu`='".$_SESSION['authid']."' ORDER BY `date` ASC LIMIT 1"),0,0);
			$sir=array();
			$sirtips=array();
			$numar=array();
			if($getlastdate){
				$datenow=date('d-m-Y',$getlastdate);
			}else{
				$datenow=date('d-m-Y');
			}
			$sir[]="'".$datenow."'";
			$numarquery=@mysql_num_rows(mysql_query("SELECT `id` FROM `sales` WHERE `datefix`='$datenow'"));
			$numar[]=$numarquery;
			$sirtips[]="'$numarquery new sales'";
				for ($i = 1; $i <= 5; $i++) {
					if($getlastdate){
						$nextdate=date('d-m-Y', strtotime('+'.$i.' day',$getlastdate));
					}else{
						$nextdate=date('d-m-Y', strtotime('+'.$i.' day'));
					}
					$sir[]="'".$nextdate."'";
					$numarquery=@mysql_num_rows(mysql_query("SELECT `id` FROM `sales` WHERE `datefix`='$nextdate'"));
					$numar[]=$numarquery;
					$sirtips[]="'$numarquery new sales'";
				}
			$sir=implode(",",$sir);
			$sirtips=implode(",",$sirtips);
			$numar=implode(",",$numar);
	
			$numberoffiles=$this->numrows("SELECT `id` FROM `products` WHERE `idu`='".$_SESSION['authid']."'");
			$user_stats_totalsales=$this->numrows("SELECT `id` FROM `sales` WHERE `idu`='".$_SESSION['authid']."'");
			$user_stats_bigfile=$this->result("SELECT `price` FROM `sales` WHERE `idu`='".$_SESSION['authid']."' ORDER BY price DESC LIMIT 1");
			$user_stats_smallfile=$this->result("SELECT `price` FROM `sales` WHERE `idu`='".$_SESSION['authid']."' ORDER BY price ASC LIMIT 1");

			$this->assign("user_stats_sir",$sir);
			$this->assign("user_stats_sirtips",$sirtips);
			$this->assign("user_stats_numar",$numar);
			$this->assign("user_stats_numberoffiles",$numberoffiles);
			$this->assign("user_stats_totalsales",$user_stats_totalsales);
			$this->assign("user_stats_bigfile",$user_stats_bigfile);
			$this->assign("user_stats_smallfile",$user_stats_smallfile);
	
	}
} 
?>