<?php

/*======================================================================*\
|| #################################################################### ||
|| # Drag'nDrop Shop 1.8                                              # ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright 2014 JAKWEB All Rights Reserved.                       # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| #   ----------- Drag'nDrop Shop IS NOT FREE SOFTWARE -----------   # ||
|| #                      http://www.jakweb.ch                        # ||
|| #################################################################### ||
\*======================================================================*/

// Redirect to something...
function jak_redirect($url)
{
    header('Location: '.$url);
    exit;
}

// Get a secure mysql input
function smartsql($value)
{
	global $jakdb;
	if (get_magic_quotes_gpc()) {
	$value = stripslashes($value);
	}
    if (!is_int($value)) {
        $value = $jakdb->real_escape_string($value);
    }
    return $value;
}

// Get the setting variable as well the default variable as array
function jak_get_setting($group) 
{
	global $jakdb;
    $sql = 'SELECT varname, value, defaultvalue FROM '.DB_PREFIX.'setting WHERE groupname = "'.smartsql($group).'"';
    $result = $jakdb->query($sql);
    while ($row = $result->fetch_assoc()) {
        $setting[] = array('varname' => $row['varname'], 'value' => $row['value'], 'defaultvalue' => $row['defaultvalue']);
    }
    return $setting;
}

// Get the data only per ID (e.g. edit single user, edit category)
function jak_get_data($id, $table) 
{
		
	global $jakdb;
    $sql = 'SELECT * FROM '.$table.' WHERE id = "'.smartsql($id).'"';
    $result = $jakdb->query($sql);
    while ($row = $result->fetch_assoc()) {
            // collect each record into $jakdata
            $jakdata = $row;
        }
    return $jakdata;
}

// Check if row exist
function jak_row_exist($id, $table)
{
		global $jakdb;
		$sql = 'SELECT id FROM '.$table.' WHERE id = "'.smartsql($id).'" LIMIT 1';
        $result = $jakdb->query($sql);
        if ($jakdb->affected_rows > 0) {
        	return true;
		}
}

// Verify paramaters
function verifyparam($name, $regexp, $default = null)
{
	if (isset($_GET[$name])) {
		$val = $_GET[$name];
		if (preg_match($regexp, $val))
			return $val;

	} else if (isset($_POST[$name])) {
		$val = $_POST[$name];
		if (preg_match($regexp, $val))
			return $val;

	} else {
		if (isset($default))
			return $default;
	}
	echo "<html><head></head><body>Wrong parameter used or absent: " . $name . "</body></html>";
	exit;
}

// Check if the lang folder for buttons exist
function folder_lang_button($lang) 
{
	return file_exists('./img/buttons/'.$lang.'/');
}

// Get the real IP Address
function get_ip_address() {
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
                    return $ip;
                }
            }
        }
    }
}

function get_tag($tag,$xml)
{
	preg_match_all('/<'.$tag.'>(.*)<\/'.$tag.'>$/imU',$xml,$match);
	return $match[1];
}

// Is search bot
function is_bot()
{	
	$botlist = array("Teoma", "alexa", "froogle", "Gigabot", "inktomi",
	"looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory",
	"Ask Jeeves", "TECNOSEEK", "InfoSeek", "WebFindBot", "girafabot",
	"crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp",
	"msnbot", "appie", "FAST", "WebBug", "Spade", "ZyBorg", "rabaz",
	"Baiduspider", "Feedfetcher-Google", "TechnoratiSnoop", "Rankivabot",
	"Mediapartners-Google", "Sogou web spider", "WebAlta Crawler","TweetmemeBot",
	"Butterfly","Twitturls","Me.dium","Twiceler");

	foreach($botlist as $bot)
	{
		if(strpos($_SERVER['HTTP_USER_AGENT'],$bot)!==false)
		return true;	// Is a bot
	}

	return false;	// Not a bot
}

// Get blog(s) out the database
function jak_get_shop_front() 
{
	global $jakdb;
	
    $sql = 'SELECT t1.id, t1.title FROM '.DB_PREFIX.'shop AS t1 WHERE active = 1 ORDER BY ecorder ASC';
    $result = $jakdb->query($sql);
    while ($row = $result->fetch_assoc()) {
    		
    		// There should be always a varname in categories and check if seo is valid
    		if (JAK_SHOPURL) {
    			$seo = JAK_base::jakCleanurl($row['title']);
    		}
    		$parseurl = JAK_rewrite::jakParseurl(JAK_PLUGIN_VAR_ECOMMERCE, 'i', $row['id'], $seo, '');
    		
            // collect each record into $jakdata
            $jakdata[] = array('id' => $row['id'], 'title' => $row['title'], 'parseurl' => $parseurl);
           }
        
        
    return $jakdata;
}
// Get total from a table
function jak_get_total($jakvar, $jakvar1, $jakvar2, $jakvar3)
{
	if (empty($jakvar1) && !empty($jakvar3)) {
		$sqlwhere = ' WHERE '.$jakvar3.' = 1';
	} elseif (!empty($jakvar1) && !empty($jakvar3)) {
		$sqlwhere = ' WHERE '.$jakvar2.' = "'.smartsql($jakvar1).'" AND '.$jakvar3.' = 1';
	} elseif (!empty($jakvar1) && empty($jakvar3)) {
		$sqlwhere = ' WHERE '.$jakvar2.' = "'.smartsql($jakvar1).'"';
	} else {
		$sqlwhere = '';
	}
		global $jakdb;
		$result = $jakdb->query('SELECT COUNT(*) as totalAll FROM '.$jakvar.$sqlwhere.'');
		$row = $result->fetch_assoc();
		
		return $row['totalAll'];
}
function jak_next_page($page, $title, $table, $id, $jakvar4, $jakvar5, $approve)
{
	if (!empty($title)) {
		$second = ' ,'.$title;
	}
	if (!empty($jakvar4)) {
		$third = ' AND '.$jakvar4.' = "'.smartsql($jakvar5).'"';
	}
	if (!empty($approve)) {
		$fourth = ' AND '.$approve.' = 1';
	}
	global $jakdb;
	$sql = 'SELECT id'.$second.' FROM '.$table.' WHERE '.$id.' > '.smartsql($page).$third.$fourth.' ORDER BY id ASC LIMIT 1';
	$result = $jakdb->query($sql);
	if ($jakdb->affected_rows > 0) {
		$row = $result->fetch_assoc();
	    $jakdata = $row;
	    return $jakdata;
	} else
	    return false;
}

function jak_previous_page($page, $title, $table, $id, $jakvar4, $jakvar5, $approve)
{
	if (!empty($title)) {
		$second = ' ,'.$title;
	}
	if (!empty($jakvar4)) {
		$third = ' AND '.$jakvar4.' = "'.smartsql($jakvar5).'"';
	}
	if (!empty($approve)) {
		$fourth = ' AND '.$approve.' = 1';
	}
	global $jakdb;
	$sql = 'SELECT id'.$second.' FROM '.$table.' WHERE '.$id.' < '.smartsql($page).$third.$fourth.' ORDER BY id DESC LIMIT 1';
	$result = $jakdb->query($sql);
	if ($jakdb->affected_rows > 0) {
	    $row = $result->fetch_assoc();
	    $jakdata = $row;
	    return $jakdata;
	} else
	    return false;

}
function jak_write_vote_hits_cookie($table, $id, $cookie)
{
	if (isset($_COOKIE[$cookie])) {

	$cookiearray = explode(',', $_COOKIE[$cookie]);
		
	if (in_array($table.'-'.$id, $cookiearray)) {
		$getCORE = $_COOKIE[$cookie];
	} else {
		$getCORE = $_COOKIE[$cookie].','.$table.'-'.$id;
	}
	
	} else {
		$getCORE = $table.'-'.$id;
	}
	
		return setcookie($cookie, $getCORE, time() + 60 * 60 * 24, JAK_COOKIE_PATH);
}
function jak_cookie_voted_hits($table, $id, $cookie)
{

	if (!isset($cookie)) {
		return true;
	}
	
	$cookiearray = explode(',', $cookie);
		
	if (in_array($table.'-'.$id, $cookiearray)) {
		return false;
	} else {
		return true;
	}

}
// only full words
function jak_cut_text($jakvar,$jakvar1,$jakvar2) {
	if (empty($jakvar1)) {
		$jakvar1 = 160;
	}
    $jakvar = trim($jakvar);
    $jakvar = strip_tags($jakvar);
    $txtl = strlen($jakvar);
    if($txtl > $jakvar1) {
        for($i=1;$jakvar[$jakvar1-$i]!=" ";$i++) {
            if($i == $jakvar1) {
                return substr($jakvar,0,$jakvar1).$jakvar2;
            }
        }
        $jakdata = substr($jakvar,0,$jakvar1-$i+1).$jakvar2;
    } else {
    	$jakdata = $jakvar;
    }
    return $jakdata;
}
// Check if row exist with custom field
function jak_field_not_exist($check, $table, $field)
{
		global $jakdb;
		$sql = 'SELECT id FROM '.$table.' WHERE LOWER('.$field.') = "'.smartsql($check).'" LIMIT 1';
        $result = $jakdb->query($sql);
        if ($jakdb->affected_rows > 0) return true;
}
function undoRegisterGlobals()
{
	if (ini_get("register_globals")) {
		$array = array("_REQUEST", "_SESSION", "_SERVER", "_ENV", "_FILES");
		foreach ($array as $value) {
			foreach ((array)$GLOBALS[$value] as $key => $var) {
				if (isset($GLOBALS[$key]) and $var === $GLOBALS[$key]) unset($GLOBALS[$key]);
			}
		}
	}
}

function undoMagicQuotes($value)
{

	if (!is_array($value)) return stripslashes($value);
	else array_map("undoMagicQuotes", $value);
	return $value;
}
// Check coupon code and usergroup and permission
function jak_shop_coupon_check($code)
{
		global $jakdb;
		// Get SQL
		$result = $jakdb->query('SELECT type, discount, freeshipping, products FROM '.DB_PREFIX.'shop_coupon WHERE code = "'.smartsql($code).'" AND status = 1 AND datestart < "'.time().'" AND dateend > "'.time().'" AND used < total LIMIT 1');
        
	    if ($jakdb->affected_rows > 0) {
	    	return true;
	    } else {
	    	return false;
	    }
        
}

// Load the version from jakcms
function jak_load_xml_from_curl($url) {

	if (function_exists('curl_version')) {
    
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	    $output = curl_exec($ch);
	    curl_close($ch);
	    	
	    return $output;
    
    } else {
    	return false;
    }
}
// Load the version from Gecko CMS
function jak_load_xml_from_url($jakvar) {

	if ($jakvar) return simplexml_load_string(jak_load_xml_from_curl($jakvar));
}
?>