<?php
if(!isset($sumfingIncl)) {header("HTTP/1.0 403 Forbidden"); die();}

function  dbConnection() {
	// Database connection
	$conn = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_DATABASE, DB_USER, DB_PASS);
	return $conn;
}

// Check for tickets
function is_tickets() {
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	// Return user object
	$sql = "SELECT * FROM tickets";
	
	$stmt = $conn->prepare($sql);
   	$stmt->execute();
   	
	// Return true if ticket exists
	if($stmt->rowCount() != 0)
	{
		return true;
	}
	$conn = NULL;
}

// Function Get Leaderboard
function get_leaderboard($rows) {
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	try {
			$sql = "
			 SELECT fb_id, name, COUNT(fb_id) AS total_tickets
			 FROM tickets
			 GROUP BY fb_id
			 ORDER BY total_tickets DESC LIMIT " . $rows;
			$stmt = $conn->query($sql);
			$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
			return $results;
			
		} catch(PDOExepction $e) {
			error_log($e->getMessage());
		}
	$conn = NULL;
}

// Winners after end 
function setwinners($data,$method) {
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	// Check if winners already in table or not
	$stmt = $conn->prepare("SELECT * FROM latest_winners");
   	$stmt->execute();
   	$cantransport = false;
		
	// Insert winners if not exists
	if(($stmt->rowCount() == 0)){
		$cantransport = true;
		$offlimit = 0;
		// Get opts
		$set = get_adm_opts();
		$i = 1;
		$prize = '';
		foreach($data as $k=>$v) {
			
			// Get prizes
			switch($i) {
				case 1:
				$prize = $set->prize1_title;
				break;
				case 2:
				$prize = $set->prize2_title;
				break;
				case 3:
				$prize = $set->prize3_title;
				break;
			}
			
			// Get winners, depending by method - random/by tickets amount
			$winners= array();
			if($method == 'random') {
				$sql = "SELECT fb_id, name, email, code FROM tickets ORDER BY RAND() LIMIT " . $v;
			} else {
				$sql = "SELECT fb_id, name, email, code, COUNT(fb_id) AS total_tickets
				 FROM tickets
				 GROUP BY fb_id
				 ORDER BY total_tickets DESC LIMIT " . $offlimit . "," . $v;
			}
			
			$stmt = $conn->query($sql);			
			while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
				  $winners[] = $row['fb_id'].":;:".$row['name'].":;:".$row['email'].":;:".$row['code'];
				  
				  ++$offlimit;
				  
				  // Send emails to winners
				  if(isset($set->send_win_email)) {
					  					  
					  // Make subject and message
					  $subject = str_replace("[NAME]",$row['name'],$set->win_email_subject);
					  $message = str_replace("[NAME]",$row['name'],$set->win_email_body);
					  $message = str_replace("[PRIZE]",$prize,$message);
					  $message = str_replace("[APPLINK]","<a href='".MY_APP_URL."'>".MY_APP_URL."</a>",$message);
					  $message = nl2br($message);
					  
					  if(!ref_note_email('',$row['email'],$subject,$message)) {
						  error_log(_("Winners email sending failed. User_id: ") . $row['fb_id']);  
					  }
				  }
				  
				  // Update winning tickets
				  $sqlupd = "UPDATE tickets SET winner = 1 WHERE code = '".$row['code']."'";
				  if(!$conn->query($sqlupd)) {
					  error_log(_("Winning ticket updater failed. Ticket code:").$row['code']);
				  }
			}
			
			// And finally INSERT
			try
			{
				$sql = "INSERT INTO latest_winners (id,winners_data,prize,raftime) VALUES (0,'".serialize($winners)."', '".$prize."', '".date("Y-m-d H:i:s", time())."')";
				$stmt = $conn->query($sql);
			} catch(PDOExepction $e) 
			{
				error_log($e->getMessage());
			}
		++$i;
		}// Foreach loop end
		
		// Send admin notification if set
		if(isset($set->send_end_email)) {
			$emailbody = '';
			$emailbody .= $set->end_email_body . '<br>' . MY_APP_URL;
			$emailbody = nl2br($emailbody);
			if(!ref_note_email('',$set->admin_email,$set->end_email_subject,$emailbody)) {
				error_log(_("Admin email sending failed."));  
			}
		}
	}
	
	if($cantransport === true) {
		// Transport winners from latest_winners table
		// Get all results and delete lowers
		$sql = "SELECT * FROM latest_winners ORDER BY id ASC";
		$stmt = $conn->query($sql);
		
		$windata = '';
		while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
			
			// Make array from latest_winners table, row by row
			$prize = $result['prize'];
			$rafdate = $result['raftime'];
			
			$windata[] = array('time'=>$rafdate, 'winners'=>$result['winners_data'], 'prize'=>$prize);
			
		}
		
		// Insert into winners table
		try {
			$sql = "INSERT INTO winners (id,date,winners_data) VALUES (NULL, '".time()."','".serialize($windata)."')";
			$stmt = $conn->query($sql);
			$error = false;
		} catch(PDOExepction $e) {
			error_log( $e->getMessage());
			$error = true;
		}	
		
		if($error) error_log("Can't insert into winners table!");
	
	}
		
	// Winners inserted, get winners from table
	$sql = "SELECT * FROM latest_winners";
	$stmt = $conn->query($sql);
	$toreturn = array();
	while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$toreturn[] = $row['id'].",".$row['winners_data'].",".$row['raftime'];
	}
		
		return $toreturn;
	
	
	$conn = NULL;	
}

// Function get_option
function get_options($table) {
		
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	try {
			$sql = "SELECT * FROM " . $table;
			$stmt = $conn->query($sql);
			$results = $stmt->fetch(PDO::FETCH_OBJ);
			return $results;
			
		} catch(PDOExepction $e) {
			error_log($e->getMessage());
		}
	$conn = NULL;
}

// save user data
function save_and_return($params, $user) {
	
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	$stmt = $conn->prepare("SELECT fb_id FROM user WHERE fb_id = '" . $user . "'");
   	$stmt->execute();
   	
	// Insert user if not exists
	if(($stmt->rowCount() == 0) && ($params != ""))
	{
		
		
			$sql = "INSERT INTO user (fb_id,isadmin,offline_access,name,email,birthday,regdate,banned,longterm_token,token_expires,fake_id,verified,share_int,req_int,slot_int) VALUES (" . $params . ")";
			if(!$stmt = $conn->query($sql)) {
				error_log('Can\'t save user data');	
			}
		
	}
	
	// Return user object
	$sql = "SELECT * FROM user WHERE fb_id = '" . $user . "'";
	$stmt = $conn->query($sql);
	$results = $stmt->fetch(PDO::FETCH_OBJ);
	return $results;
	
	$conn = NULL;
}
function get_user_thumbs($amount){
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	$users = array();
	// Return user object
	$sql = "SELECT * FROM user ORDER BY id DESC LIMIT ".$amount;
	$stmt = $conn->query($sql);
	while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$name = explode(" ",$row['name']);
		$users[] = $row['fb_id'].','.$name[0];	
	}
	return $users;
	
	$conn = NULL;
}

// Check fake_id user
function is_user_fakeid($user) {
	
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	
	// Return user object
	$sql = "SELECT * FROM user WHERE fake_id = '" . $user . "'";
	$stmt = $conn->query($sql);
	$results = $stmt->fetch(PDO::FETCH_OBJ);
	return $results;
	
	$conn = NULL;
}

// Update longterm token
function update_user_token($token, $user) {
	
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	try
	{
		$sql = "UPDATE user SET offline_access = '".$token."' WHERE fb_id = '" . $user . "'";
		$stmt = $conn->query($sql);
	} catch(PDOExepction $e) {
		echo $e->getMessage();
	}
	
	$conn = NULL;
}

// Update user data
function update_user($param, $user) {
	
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");

	try
	{
		$sql = "UPDATE user SET ".$param." WHERE fake_id = '" . $user . "'";
		$stmt = $conn->query($sql);
		return true;
	} catch(PDOExepction $e) {
		echo $e->getMessage();
		return false;
	}
	
	$conn = NULL;
}

// Update longterm token
function update_verified_user($data, $fake_id) {
	
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	try
	{
		$sql = "UPDATE user SET verified = '".$data."' WHERE fake_id = '" . $fake_id . "'";
		$stmt = $conn->query($sql);
		return true;
	} catch(PDOExepction $e) {
		echo $e->getMessage();
		return false;
	}
	
	$conn = NULL;
}

// Get requests count
function get_request_count($user) {
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	$sql = "SELECT request_id FROM app_requests WHERE fromuser = '" . $user . "'";
	
	$stmt = $conn->prepare($sql);
   	$stmt->execute();

	return $stmt->rowCount();
	
	$conn = NULL;
}

//build the full_request_id from request_id and user_id 
function build_full_request_id($request_id, $user_id) {
   return $request_id . '_' . $user_id; 
}

// Insert requests
function request_insert($data, $fromuser) {
	
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	$stmt = $conn->prepare('INSERT INTO app_requests VALUES (:fb_user_id, :request_id, :fromuser, 0, :req_time)');	
	$i=0;
	try {
	 $conn->beginTransaction();
	 
	 foreach ($data as $value) {
	   
	     $parts = explode('_',$value);
	     
		     $stmt->bindValue(':fb_user_id', $parts[1]);
		     $stmt->bindValue(':request_id', $parts[0]);
		     $stmt->bindValue(':fromuser', $fromuser);
			 $stmt->bindValue(':req_time', time());
		     $stmt->execute();
		     $i++;
	     
	 }
	 
	 $conn->commit();
	} catch (PDOException $e) {
	 error_log($e->getMessage());
	 $conn->rollBack();
	 $error = true;
	}
	
	$conn = NULL;
	
	if(!isset($error))
	return $i;
}

// Get pending requests
function get_pending_request($time) {
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	$deltime = ($time < 1) ? (time() - 86400) : (time() - ($time * 86400));
	$requestarray = array();
	// Return user object
	$sql = "SELECT * FROM app_requests WHERE req_time < '" . $deltime . "' AND answered = 0";
    $result = $conn->query($sql);
    while($row = $result->fetch(PDO::FETCH_ASSOC)) {
		$requestarray[] = $row['request_id'] . '_' . $row['fb_user_id'];
	}
	
	return $requestarray;
	
	$conn = NULL;	
}

function get_app_token($appId, $appSecret) {
    $token_url =    "https://graph.facebook.com/oauth/access_token?" .
                    "client_id=" . $appId .
                    "&client_secret=" . $appSecret .
                    "&grant_type=client_credentials";
    $token = file_get_contents($token_url);
    return $token;
}

// Get referred user data
function get_ref_user($user) {
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	// Return user object
	$sql = "SELECT * FROM user WHERE fake_id = '" . $user . "'";
	$stmt = $conn->query($sql);
	$results = $stmt->fetch(PDO::FETCH_OBJ);
	return $results;
	
	$conn = NULL;
}

// Get ref tickets
function get_ref_tickets($user, $fake_id) {
	
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	// Return user object
	$sql = "SELECT * FROM tickets WHERE fb_id = '" . $user . "' AND for_what = '".$fake_id."'";
	
	$stmt = $conn->prepare($sql);
   	$stmt->execute();
   	
	// Return true if ticket exists
	if($stmt->rowCount() != 0)
	{
		return true;
	}
	$conn = NULL;
}
// Make request tickets
function update_request($request_id,$ticketamount,$user,$fake_id) {
	// Get request from database
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	$sql = "SELECT * FROM app_requests WHERE request_id = '" . $request_id . "' AND fb_user_id = '".$user."'";
	$stmt = $conn->query($sql);
	$results = $stmt->fetch(PDO::FETCH_OBJ);
	if($results->fb_user_id != '') {
		try {
			$sql = "UPDATE app_requests SET answered = 1 WHERE request_id = '" . $request_id . "'";
			$stmt = $conn->query($sql);
			$updated = true;
		} catch(PDOExepction $e) {
			error_log($e->getMessage());
		}	
	}
		
	// Get user data
	$params = '';
	$touser = save_and_return($params, $results->fromuser);
	
	$sql = "SELECT * FROM tickets WHERE fb_id = '".$results->fromuser."' AND for_what = '" . $fake_id . "'";
	$stmt = $conn->prepare($sql);
   	$stmt->execute();
   	
	// If no previous tickets from current user
	if($stmt->rowCount() == 0) {
		if($updated && ($ticketamount != 0)) {
			make_tickets($ticketamount,$results->fromuser,$fake_id,$touser->name,$touser->email);
				
				// Get options
				$set = get_adm_opts();
				
				// Send email to referrer
				if(isset($set->send_ref_email)) {
					
					// Subject and message
					$fromusername = save_and_return($params, $user);
					$subject = str_replace("[NAME]",$touser->name, $set->ref_email_subject);
					$message = str_replace("[NAME]",$touser->name, $set->ref_email_body);
					$message = str_replace("[APPLINK]","<a href='".MY_APP_URL."'>" . MY_APP_URL . "</a>", $message);
					$message = str_replace("[REFNAME]","<a href='https://facebook.com/".$user."/'>" . $fromusername->name . "</a>", $message);
					$message = nl2br($message);
					if(!ref_note_email('',$touser->email,$subject,$message)) {
						error_log(_("Error! Referrer email not sent."));	
					}
				}	
			return true;
		}
	}
	
	$conn = NULL;
}

// Make tickets
function make_tickets($amount,$to,$from,$toname,$toemail) {
	
	//set timezone
	$set = get_adm_opts();
	date_default_timezone_set($set->timezone);
	
	// Confirm code for any case
	function code() {
		$random= "";
		$data = srand((double)microtime()*1000000);
		$data .= time(); 
		$data .= "ABCDEFGHIJKLMNOPQRSTUVWZXYabcdefghijklmnopqrstuvwzxy";
		$data .= "0123456789";
					
		for($i = 0; $i < 9; $i++) { 
			$random .= substr($data, (rand()%(strlen($data))), 1); 
		}
		return $random; 
	}
	
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	// To give to admin or not, default is not
	$userdata = save_and_return('',$to);
	if(!isset($set->give_admin_tickets) && $userdata->isadmin == 1) {
		return false;
		 die('');
	}
	// Give tickets
	$i = 1;
		
	while($i < ($amount+1)) {
		$sql = "INSERT INTO tickets (id, fb_id, name, email, code, date, for_what, winner) VALUES ('','".$to."','".$toname."','".$toemail."','".code()."','".date("d-m-Y H:i:s",time())."','".$from."', 0)";
		$stmt = $conn->query($sql);
		++$i;
	}
	
	$conn = NULL;	
}

function users_and_tickets() {
	
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	// Get tickets amount
	$sql = "SELECT id FROM tickets";
	$stmt = $conn->prepare($sql);
   	$stmt->execute();
   	$tickets = $stmt->rowCount();
	
	// Get tickets amount
	$sql = "SELECT DISTINCT fb_id FROM tickets";
	$stmt = $conn->prepare($sql);
   	$stmt->execute();
   	$users = $stmt->rowCount();
	$conn = NULL;
	
	return array($users,$tickets);
}

function save_admi_settings($postedform) {
	
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	// Truncate table
	$query = $conn->query("TRUNCATE TABLE admin_options") or die("failed!");
	$stmt = $conn->prepare('INSERT INTO admin_options VALUES (0, :option_name, :option_value)');	
	
	try {
	 $conn->beginTransaction();
	 $i=0;
	 foreach ($postedform as $column => $value) {
	   $stmt->bindValue(':option_name', $column);
	   $stmt->bindValue(':option_value', $value);
	   $stmt->execute();
	   $i++;
	 }
	 $conn->commit();
	} catch (PDOException $e) {
	 error_log($e->getMessage());
	 $conn->rollBack();
	 $error = true;
	}
	
	$conn = NULL;
	
	if(!isset($error))
	echo $i . " rows saved";
}

function get_adm_opts() {
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);	
	$conn->exec("SET CHARACTER SET utf8");

  $sql = "SELECT * FROM admin_options";
  $result = $conn->query($sql);
  
  $obj = new stdClass();
  // Parse returned data
  while($row = $result->fetch(PDO::FETCH_ASSOC)) {
	  $obj->$row['option_name'] = $row['option_value'];
  }
  return $obj;
	
  $conn = NULL;
}

function get_sec_data() {
	
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);	
	$conn->exec("SET CHARACTER SET utf8");

  	// Define and perform the SQL SELECT query
  	$sql = "SELECT * FROM sec_data";
  	if($result = $conn->query($sql)) {

		$array = array();
		// Parse returned data, and displays them
		while($row = $result->fetch(PDO::FETCH_ASSOC)) {
		  //$array = $row['option_value'];
		  array_push($array, $row['option_value']);
		}
		return $array;
	}
  $conn = NULL;
}

function add_sec_data($user, $data) {
	
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	// Insert into table
	$stmt = $conn->prepare('INSERT INTO sec_data VALUES (0, :id, :option_name, :option_value)');
	try {
	 $conn->beginTransaction();
	 
	 foreach ($data as $key=>$value) {
		 
		   $stmt->bindValue(':id', $user);
		   $stmt->bindValue(':option_name', $key);
		   $stmt->bindValue(':option_value', $value);
		   $stmt->execute();
		
	 }
	 $conn->commit();
	} catch (PDOException $e) {
	 error_log($e->getMessage());
	 $conn->rollBack();
	 $error = true;
	}
	$conn = NULL;
	if(!$error)
	return 0;
	else return 2;
}

function other(){ // adminn
	
	// If admin data update
	if($table === 'admin')
	{
		try
			{
				$sql = "UPDATE " . $table . " SET " . $params;
				$stmt = $conn->query($sql);
			} catch(PDOExepction $e) {
				error_log($e->getMessage());
			}	
	}
	
	
	try {
			$sql = "SELECT * FROM " . $table;
			$stmt = $conn->query($sql);
			$results = $stmt->fetch(PDO::FETCH_OBJ);
			return $results;
			
		} catch(PDOExepction $e) {
			echo $e->getMessage();
		}
	$conn = NULL;
}

// A function that makes dropdown box with folder image files
function build_pic_list($theFolder,$selected) {
  if ($contents = @ scandir($theFolder)) {
    $found = array();
    $fileTypes = array('jpg','jpeg','gif','png');
	$found = array();
    foreach ($contents as $item) {
      $fileInfo = pathinfo($item);
      if (array_key_exists('extension', $fileInfo) && in_array($fileInfo['extension'],$fileTypes)) {
        $found[] = $item;
        }
      }
    if ($found) {
      natcasesort($found);
	  $selection = "";
      foreach ($found as $filename) {
		$selection = ($selected == $filename) ? 'selected="selected"' : '';
        echo "<option value='".$filename."' ".$selection.">".$filename."</option>\n";
        }
      }
    }
}

function tz_list($selected) {
	$selection = "";
	// Array with all timezones
	$tzlist = DateTimeZone::listIdentifiers();
	foreach($tzlist as $val) {
		
		// If timezones from database and in list are the same, mark it as selected
		$selection = ($selected == $val) ? 'selected="selected"' : '';	
		
		echo "<option value='".$val."' ".$selection.">".$val."</option>";
	}
}

// Make wins table
function make_win_table($data) {
	$fulltable = '';
	// Loop over winning combinations. Exclude 0's
	foreach($data as $k=>$v) {
		$itm = explode('_',$k);
		if($v != 0) {
			if($itm[1] == 2) {
				$fulltable .= '
					<div class="inline" style="margin-bottom:6px">
						
						<img src="img/slot/'.$itm[0].'-mini.png" class="img-polaroid">
						<img src="img/slot/'.$itm[0].'-mini.png" class="img-polaroid">
						<img src="img/slot/x.png" class="img-polaroid">
						
						<span style="font-size:18px"> <strong class="badge badge-info">'.$v.'</strong></span>
					</div>
				
				';
			} else {
				$fulltable .= '
					<div class="inline" style="margin-bottom:6px">
						
						<img src="img/slot/'.$itm[0].'-mini.png" class="img-polaroid">
						<img src="img/slot/'.$itm[0].'-mini.png" class="img-polaroid">
						<img src="img/slot/'.$itm[0].'-mini.png" class="img-polaroid">
						
						<span style="font-size:18px"> <strong class="badge badge-info">'.$v.'</strong></span>
					</div>
				
				';
			}
		}
	}
	/*
	
	*/
	return $fulltable;
}

// Draw slot machine wheels
function draw_wheels($pos) {
	$lmar = '';
	switch($pos) {
		case 'L': $posvar = 'left';	break;
		case 'C': $posvar = 'center'; $lmar = 'margin-left:3px'; break;
		case 'R': $posvar = 'right'; $lmar = 'margin-left:6px'; break;
	}
	
	$wheel = '
		<img src="img/slot/heart_single.png" style="margin:40px 0 0 14px; display:none;" id="single_heart_'.$pos.'" class="single_items" />
        <img src="img/slot/clover_single.png" style="margin:40px 0 0 14px; display:none;" id="single_clover_'.$pos.'" class="single_items"/>
        <img src="img/slot/star_single.png" style="margin:40px 0 0 14px; display:none;" id="single_star_'.$pos.'" class="single_items"/>
                
        <img src="img/slot/heart_single_win.png" style="margin:40px 0 0 14px; display:none;" id="single_heart_'.$pos.'_win" class="single_items" />
        <img src="img/slot/clover_single_win.png" style="margin:40px 0 0 14px; display:none;" id="single_clover_'.$pos.'_win" class="single_items"/>
        <img src="img/slot/star_single_win.png" style="margin:40px 0 0 14px; display:none;" id="single_star_'.$pos.'_win" class="single_items"/>
                
        <img src="img/slot/roll_'.$posvar.'.gif" id="roll_'.$pos.'" style="margin-top:-1px; '.$lmar.' ; display:none" />
	';
	
	return $wheel;
}

// Get user spins
function get_spins($user) {
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	$stmt = $conn->query("SELECT * FROM slot_spins WHERE user = '".$user."'");
	$result = $stmt->fetch(PDO::FETCH_OBJ);
	return $result;
	$conn = NULL;
}

// Delete spins and continue if int is over
function set_slot_int($user, $interval){
	
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	if(($interval == '') || ($interval == 0))
		$interval = 24;
	$interval = time() + ($interval * 3600);
	
	try {
		$sql = "UPDATE user SET slot_int = '".$interval."' WHERE fb_id = '".$user."'";
		$stmt = $conn->query($sql);
	}catch(PDOExepction $e) {
		error_log( $e->getMessage() );
	}
	
	// Delete old data from spins table
	try {
		$sql = "DELETE FROM slot_spins  WHERE user = '".$user."'";
		$stmt = $conn->query($sql);
	} catch(PDOExepction $e) {
		error_log( $e->getMessage());
	}
	
	$conn = NULL;
}

// Save or update spin
function save_and_update_spin($user,$win,$total,$spins,$freespins){
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	if($spins == 1) {
		try {
			$sql = "INSERT INTO slot_spins (user, spins, tickets, last_spin, done) VALUES ('".$user."', 1, ".$win.", '".time()."', 0)";
			$stmt = $conn->query($sql);
			return true;
		} catch(PDOExepction $e) {
			error_log( $e->getMessage());
		}	
	} else {
		
		if($freespins == $spins) {
			$sql = "UPDATE slot_spins SET spins = (spins+1), tickets = (tickets + ".$win."), last_spin = '".time()."', done = 1 WHERE user = '".$user."'";
		} else {
			$sql = "UPDATE slot_spins SET spins = (spins+1), tickets = (tickets + ".$win."), last_spin = '".time()."' WHERE user = '".$user."'";
		}
				
		try {
			$stmt = $conn->query($sql);
			return true;
		} catch(PDOExepction $e) {
			error_log( $e->getMessage());
		}
		
	}
	
	$conn = NULL;
}

// Give tickets for slot spins
function slot_give_tickets($user) {
	$spins = get_spins($user);
	if(($spins->done == 1) && ($spins->tickets > 0)) {
		$userdata = save_and_return('',$user);
		make_tickets($spins->tickets,$userdata->fb_id,'slot',$userdata->name,$userdata->email);
		
		$conn = dbConnection();
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$conn->exec("SET CHARACTER SET utf8");

		// Insert new entry
	
		try {
			$sql = "INSERT INTO slot_leaders (id,name,fb_id,score,result_time) VALUES (NULL, '".$userdata->name."', '".$userdata->fb_id."', ".$spins->tickets.", '".time()."')";
			$stmt = $conn->query($sql);
		} catch(PDOExepction $e) {
			error_log( $e->getMessage());
		}
		
		// Get all results and delete lowers
		$sql = "SELECT * FROM slot_leaders ORDER BY score DESC";
		$stmt = $conn->query($sql);
		$i=1;
		$entry = array();
		while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
			if($i < 11) {
				$entry[] = 	$result['name'].','.$result['fb_id'].','.$result['score'].','.$result['result_time'];
			++$i;
			}
		}
		
		// Truncate table
		$query = $conn->query("TRUNCATE TABLE slot_leaders") or die(error_log("slot_leaders truncate failed!"));
		
		// Insert new records
		foreach($entry as $rec) {
			$record = explode(",",$rec);
			try {
				$sql = "INSERT INTO slot_leaders (id,name,fb_id,score,result_time) VALUES (NULL, '".$record[0]."', '".$record[1]."', ".$record[2].", ".$record[3].")";
				$stmt = $conn->query($sql);
			} catch(PDOExepction $e) {
				error_log( $e->getMessage());
			}	
		}
		
			
		
	return true;
	}
}

// Slot machine leaderboard
function slot_leaders() {
	
	// Get settings
	$set = get_adm_opts();
	// Set timezone
	date_default_timezone_set($set->timezone);
	
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	// Get all from slot leaderboard
	
		$sql = "SELECT * FROM slot_leaders ORDER BY score DESC";
		$stmt = $conn->query($sql);
		$i=1;
		
		while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
			
			if(isset($set->lboard_link))
			$username = '<a href="https://facebook.com/'.$row['fb_id'].'" target="_blank">'.$row['name'].'</a>';
			else
			$username = $row['name'];
			echo "<tr>";
		  
			echo "<td>" . $i . "</td><td>" . $username . "</td><td>" . $row['score']. "</td><td>" . date("H:i:s d-m-Y", $row['result_time']). "</td>";
		  
			echo "</tr>";
		$i++;
		}
	
  $conn = NULL;
}

// Get unique ids from tickets table
function get_participants() {
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	// Get tickets amount
	$sql = "SELECT DISTINCT fb_id FROM tickets";
	$stmt = $conn->prepare($sql);
   	$stmt->execute();
   	$tickets = $stmt->rowCount();
	
	return $tickets;
	$conn = NULL;
}

// Delete all tickets
function reset_all($user) {
	
	$user = is_user_fakeid($user);
	if($user->isadmin == 1) {
		$error = false;
		
		$conn = dbConnection();
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$conn->exec("SET CHARACTER SET utf8");
		
		// Truncate tables
		$tables = array('tickets','slot_leaders','sec_data','latest_winners','mob_links','slot_spins');
		foreach($tables as $tab) {
			if($query = $conn->query("TRUNCATE TABLE " . $tab)) {
				$error = false;
			} else {
				error_log($tab . " table truncate failed!");
			}
		}
		
		// Get otions
		$set = get_adm_opts();
		
		// Delete requests
		if(isset($set->use_app_requests)) {
			if (ini_get('allow_url_fopen') == 1) {
				$pendingrequests = array();
				$pendingrequests = get_pending_request(30); // Will return full requests
				// Loop over requests and delete
				if(!empty($pendingrequests)) {
				$app_token = get_app_token(FB_APPID, FB_SECRET);
					foreach ($pendingrequests as $request_id) {
						if(@file_get_contents('https://graph.facebook.com/'.$request_id.'?'.$app_token.'&method=DELETE'))
							$error = false;
						else
							$error = true;
					}
				}
			}
		}
		
		if($error) error_log("Request deletion failed!");
		
		// Truncate requests table
		if($query = $conn->query("TRUNCATE TABLE app_requests"))
			$error = false;
		else
			$error = true;
			
		if($error) error_log("Truncate requests table failed");
		
		// Update users table
		$sql = "UPDATE user SET verified = 'no', share_int = '0' , req_int = '0', slot_int = '0'";
		try {
			$stmt = $conn->query($sql);
			$error = false;
		} catch(PDOExepction $e) {
			error_log( $e->getMessage());
			$error = true;
		}
		if($error) error_log("Can't update users table!");
		
		$conn = NULL;
	}
	
	if(!$error) return true;
	
}

// Winners for admin page
function get_winners_admin($user) {
	
	$user = is_user_fakeid($user);
	if($user->isadmin == 1) {
		$error = false;
		
		$conn = dbConnection();
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$conn->exec("SET CHARACTER SET utf8");
		
		$sql = "SELECT * FROM winners ORDER BY id DESC";
		$stmt = $conn->query($sql);
		$arr = array();
		while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
			
			$arr[] = array($result['id'],unserialize($result['winners_data']), $result['date']);
		
		}
		
		return $arr;
	}
}

// Users fetch for admin
function get_all_users($admin) {
	$user = is_user_fakeid($admin);
	if($user->isadmin == 1) {
		
		
		$conn = dbConnection();
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$conn->exec("SET CHARACTER SET utf8");
		
		$sql = "SELECT * FROM user";
		$stmt = $conn->query($sql);
		while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
			
			$userarr[] = $result['id'] . '|' . $result['name'] . '|' . $result['email'] . '|' . $result['regdate'] . '|' . $result['birthday'] . '|' . $result['banned'] . '|' . $result['fb_id'];
		
		}
		return $userarr;
	}
}

// Ban user from admin
function ban_user($admin,$user,$data) {
  $admin = is_user_fakeid($admin);
  if($admin->isadmin == 1) {
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	try
	{
		$sql = "UPDATE user SET banned = '".$data."' WHERE fb_id = '" . $user . "'";
		$stmt = $conn->query($sql);
		return true;
	} catch(PDOExepction $e) {
		echo $e->getMessage();
		return false;
	}
	
	$conn = NULL;
  }
}

// Get user tickets
function get_user_tickets($user) {
	
    	$conn = dbConnection();
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$conn->exec("SET CHARACTER SET utf8");
		
		$sql = "SELECT * FROM tickets WHERE fb_id = '".$user."'";
		$stmt = $conn->query($sql);
		$tickets = array();
		while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
			
			$tickets[] = $result['id'] . '|' . $result['date'] . '|' . $result['code'] . '|' . $result['for_what'] . '|' . $result['winner'];
		
		}
		return $tickets;
}

// Admin deletes user tickets
function delete_user_tickets($admin,$user) {
  $admin = is_user_fakeid($admin);
  if($admin->isadmin == 1) {
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	try
	{
		$sql = "DELETE FROM tickets WHERE fb_id = '" . $user . "'";
		$stmt = $conn->query($sql);
		return true;
	} catch(PDOExepction $e) {
		echo $e->getMessage();
		return false;
	}
	
	$conn = NULL;
  }
}

// User tokens for posting
function get_users_token($admin,$amount) {
	$user = is_user_fakeid($admin);
	if($user->isadmin == 1) {
		
		$conn = dbConnection();
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$conn->exec("SET CHARACTER SET utf8");
		$param = '0';
		if(($amount > 0)) {
			$sql = "SELECT offline_access FROM user ORDER BY RAND() LIMIT " . $amount;
		} else {
			$sql = "SELECT offline_access FROM user WHERE isadmin = 0";
		}
		
		$stmt = $conn->prepare($sql);
		$stmt->execute(array($param));
		$userarr = array();
		while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
			$userarr[] = $result['offline_access'];
		}
		return $userarr;
	$conn = NULL;
	}
}

// Sendmail function
function send_emails($to,$subject,$message) {
	
	// Get options
	$set = get_adm_opts();
	// Set timezone
	date_default_timezone_set($set->timezone);
	
	require '../mailer/phpmailer/class.phpmailer.php';
	$sumfingIncl = true;
	include 'translate.php';
	$i=0;
	$admin = $set->admin_email;
	if(isset($set->smtp_emails)) {
		
		$mail = new PHPMailer();
		$mail->IsSMTP();
		$mail->Host       = $set->smtp_host;
		$mail->Port       = $set->smtp_port;
		$mail->SMTPAuth   = true;
		$mail->Username   = $set->smtp_user;
		$mail->Password   = $set->smtp_pass;
		$mail->SetFrom($set->admin_email, $set->admin_name);
		$mail->AddReplyTo($set->admin_email, $set->admin_name);
		foreach($to as $v) {
			$mail->AddBCC($v); 
			$i++;
		}
		$mail->Subject = $subject;
		$mail->MsgHTML($message);
		$mail->AltBody = _("Please use HTML compatible email reader");
		
		if(!$mail->Send()) {
		  error_log ( "Mailer Error: " . $mail->ErrorInfo);
		} else {
		  return $i . _(" messages were sent");
		}
	} else {
	
		$mail = new PHPMailer();
		$mail->IsSendmail();
		$mail->SetFrom($set->admin_email,$set->admin_name);
		$mail->AddReplyTo($set->admin_email,$set->admin_name);
		foreach($to as $v) {
			$mail->AddBCC($v); 
			$i++;
		}
		$mail->Subject = $subject;
		$mail->MsgHTML($message);
		$mail->AltBody = _("Please read emails with HTML compatible reader.");
		
		//Send the message, check for errors
		if(!$mail->Send()) {
		    error_log( $mail->ErrorInfo );
		} else {
			return $i . _(" messages were sent");
		}
	}
}

// All users emails
function get_users_emails($admin) {
	$user = is_user_fakeid($admin);
	if($user->isadmin == 1) {
		
		$conn = dbConnection();
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$conn->exec("SET CHARACTER SET utf8");
		
		$sql = "SELECT * FROM user";
		$stmt = $conn->query($sql);
		while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
			
			$list[] = $result['email'];
		
		}
		return $list;
	}
}

// Referred user email
function ref_note_email($from,$to,$subject,$message) {
	// Get options
	$set = get_adm_opts();
	// Set timezone
	date_default_timezone_set($set->timezone);
	
	require_once 'mailer/phpmailer/class.phpmailer.php';
	$sumfingIncl = true;
	include 'incl/translate.php';
	
	if(isset($set->smtp_emails)) {
		
		$mail = new PHPMailer();
		$mail->IsSMTP();
		$mail->Host       = $set->smtp_host;
		$mail->Port       = $set->smtp_port;
		$mail->SMTPAuth   = true;
		$mail->Username   = $set->smtp_user;
		$mail->Password   = $set->smtp_pass;
		$mail->SetFrom($set->admin_email, $set->admin_name);
		$mail->AddReplyTo($set->admin_email, $set->admin_name);
		$mail->AddAddress($to);
		$mail->Subject = $subject;
		$mail->MsgHTML($message);
		$mail->AltBody = _("Please use HTML compatible email reader");
		
		if(!$mail->Send()) {
		  error_log ( "Mailer Error: " . $mail->ErrorInfo);
		} else {
		  return true;
		}
	} else {
	
		$mail = new PHPMailer();
		$mail->IsSendmail();
		$mail->SetFrom($set->admin_email,$set->admin_name);
		$mail->AddReplyTo($set->admin_email,$set->admin_name);
		$mail->AddAddress($to);
		$mail->Subject = $subject;
		$mail->MsgHTML($message);
		$mail->AltBody = _("Please read emails with HTML compatible reader.");
		
		//Send the message, check for errors
		if(!$mail->Send()) {
		    error_log( $mail->ErrorInfo );
		} else {
			return true;
		}
	}
}

// Referred user email
function claim_win_email($from,$to,$subject,$message) {
	// Get options
	$set = get_adm_opts();
	// Set timezone
	date_default_timezone_set($set->timezone);
	
	require_once '../mailer/phpmailer/class.phpmailer.php';
	$sumfingIncl = true;
	include 'translate.php';
	
	if(isset($set->smtp_emails)) {
		
		$mail = new PHPMailer();
		$mail->IsSMTP();
		$mail->Host       = $set->smtp_host;
		$mail->Port       = $set->smtp_port;
		$mail->SMTPAuth   = true;
		$mail->Username   = $set->smtp_user;
		$mail->Password   = $set->smtp_pass;
		$mail->SetFrom($from, '');
		$mail->AddReplyTo($from, '');
		$mail->AddAddress($to);
		$mail->Subject = $subject;
		$mail->MsgHTML($message);
		$mail->AltBody = _("Please use HTML compatible email reader");
		
		if(!$mail->Send()) {
		  error_log ( "Mailer Error: " . $mail->ErrorInfo);
		} else {
		  return true;
		}
	} else {
	
		$mail = new PHPMailer();
		$mail->IsSendmail();
		$mail->SetFrom($from,'');
		$mail->AddReplyTo($from,'');
		$mail->AddAddress($to);
		$mail->Subject = $subject;
		$mail->MsgHTML($message);
		$mail->AltBody = _("Please read emails with HTML compatible reader.");
		
		//Send the message, check for errors
		if(!$mail->Send()) {
		    error_log( $mail->ErrorInfo );
		} else {
			return true;
		}
	}
}

// Referred user email
function mobile_email($from,$to,$subject,$message) {
	// Get options
	$set = get_adm_opts();
	// Set timezone
	date_default_timezone_set($set->timezone);
	
	require_once '../../mailer/phpmailer/class.phpmailer.php';
	$sumfingIncl = true;
	include '../../incl/translate.php';
	
	if(isset($set->smtp_emails)) {
		
		$mail = new PHPMailer();
		$mail->IsSMTP();
		$mail->Host       = $set->smtp_host;
		$mail->Port       = $set->smtp_port;
		$mail->SMTPAuth   = true;
		$mail->Username   = $set->smtp_user;
		$mail->Password   = $set->smtp_pass;
		$mail->SetFrom($from, '');
		$mail->AddReplyTo($from, '');
		$mail->AddAddress($to);
		$mail->Subject = $subject;
		$mail->MsgHTML($message);
		$mail->AltBody = _("Please use HTML compatible email reader");
		
		if(!$mail->Send()) {
		  error_log ( "Mailer Error: " . $mail->ErrorInfo);
		} else {
		  return true;
		}
	} else {
	
		$mail = new PHPMailer();
		$mail->IsSendmail();
		$mail->SetFrom($from,'');
		$mail->AddReplyTo($from,'');
		$mail->AddAddress($to);
		$mail->Subject = $subject;
		$mail->MsgHTML($message);
		$mail->AltBody = _("Please read emails with HTML compatible reader.");
		
		//Send the message, check for errors
		if(!$mail->Send()) {
		    error_log( $mail->ErrorInfo );
		} else {
			return true;
		}
	}
}

// New raffle notification email
function send_new_note($to,$subject,$message) {
	// Get options
	$set = get_adm_opts();
	// Set timezone
	date_default_timezone_set($set->timezone);
	
	require '../mailer/phpmailer/class.phpmailer.php';
	$sumfingIncl = true;
	include 'translate.php';
	$i=0;
	$admin = $set->admin_email;
	if(isset($set->smtp_emails)) {
		
		$mail = new PHPMailer();
		$mail->IsSMTP();
		$mail->Host       = $set->smtp_host;
		$mail->Port       = $set->smtp_port;
		$mail->SMTPAuth   = true;
		$mail->Username   = $set->smtp_user;
		$mail->Password   = $set->smtp_pass;
		$mail->SetFrom($set->admin_email, $set->admin_name);
		$mail->AddReplyTo($set->admin_email, $set->admin_name);
		foreach($to as $v) {
			$mail->AddBCC($v); 
			$i++;
		}
		$mail->Subject = $subject;
		$mail->MsgHTML($message);
		$mail->AltBody = _("Please use HTML compatible email reader");
		
		if(!$mail->Send()) {
		  error_log ( "Mailer Error: " . $mail->ErrorInfo);
		} else {
		  return true;
		}
	} else {
	
		$mail = new PHPMailer();
		$mail->IsSendmail();
		$mail->SetFrom($set->admin_email,$set->admin_name);
		$mail->AddReplyTo($set->admin_email,$set->admin_name);
		foreach($to as $v) {
			$mail->AddBCC($v); 
		}
		$mail->Subject = $subject;
		$mail->MsgHTML($message);
		$mail->AltBody = _("Please read emails with HTML compatible reader.");
		
		//Send the message, check for errors
		if(!$mail->Send()) {
		    error_log( $mail->ErrorInfo );
		} else {
			return true;
		}
	}
}

// Get user sec data
function get_user_secdata($user) {
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
		
	$sql = "SELECT * FROM sec_data WHERE fake_id = '".$user."'";
	$stmt = $conn->query($sql);
	while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
			
		$list[] = $result['option_name'] . "," . $result['option_value'];
		
	}
	return $list;
}

// Update ticket as winning ticket
function update_user_ticket($user,$ticket) {
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	try{
		$sql = "UPDATE tickets SET winner = 2 WHERE fb_id = '".$user."' AND id = '" . $ticket . "'";
		$stmt = $conn->query($sql);
		return true;	
	} catch(PDOExepction $e) {
		error_log(_("Can not update win request for ticket #") . $e->getMessage());
		return false;
	}
}

// Insert mobile users link to db
function insert_mobile_link($user,$link,$data) {
	
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	$stmt = $conn->prepare("SELECT fb_id FROM mob_links WHERE fb_id = '" . $user . "'");
   	$stmt->execute();
   	
	// Insert user if not exists
	if(($stmt->rowCount() == 0)) {
	
		// Insert new records
		try {
			$sql = "INSERT INTO mob_links (id,fb_id,link,data,answer) VALUES (NULL, '".$user."', '".$link."','".$data."', 0)";
			$stmt = $conn->query($sql);
			return true;
		} catch(PDOExepction $e) {
			error_log( $e->getMessage());
			return false;
		}	
	
	} else {
		return true;	
	}
	
	$conn = NULL;
}

// Mob_page email link check
function check_mob_link($hash,$user) {
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	$stmt = $conn->prepare("SELECT fb_id FROM mob_links WHERE link = '" . $hash . "' AND answer = 0");
   	$stmt->execute();
   	
	// If link with answer 0 found
	if($stmt->rowCount() == 1) {
		
		try{
			$sql = "UPDATE mob_links SET answer = 1 WHERE fb_id = '".$user."' AND link = '" . $hash . "'";
			$stmt = $conn->query($sql);
			return true;	
		} catch(PDOExepction $e) {
			error_log(_("Can not update mob link answer") . $e->getMessage());
			return false;
		}
		
	}
	
	$conn = NULL;
}

// Remove admin tickets
function delete_admin_tickets($user) {
	$conn = dbConnection();
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$conn->exec("SET CHARACTER SET utf8");
	
	$stmt = $conn->prepare("DELETE FROM tickets WHERE fb_id = '" . $user . "'");
   	$stmt->execute();
	$conn = NULL;
}

// Language list
function get_lang_list($dir,$sel) {
	$directories = scandir($dir);
	include 'locale/langshort.php';
	foreach($directories as $directory){
		if(strpos($directory, "_") == 2){
			$explang = explode('_',$directory);
			$selected = ($sel == $directory) ? 'selected' : '';
			echo '<option value="'.$directory.'" '.$selected.'>' . $langshort[$explang[0]] .'</option>';
		}
	}
}
?>