<?php

function cleanit($text)
{
	return htmlentities(strip_tags(stripslashes($text)), ENT_COMPAT, "UTF-8");
}

function insert_get_edocurl($a)
{
    global $config,$conn;
    $query="select title from docs where DID='".mysql_real_escape_string($a[did])."'";
    $executequery=$conn->execute($query);
    $turl = $config['baseurl']."/docs/".$a[did]."/".$executequery->fields[title];
	return $config['baseurl']."/login.php?redirect=".base64_encode($turl);
}

function insert_get_username_from_userid($var)
{
        global $conn;
        $query="SELECT username FROM members WHERE USERID='".mysql_real_escape_string($var[USERID])."'";
        $executequery=$conn->execute($query);
        $getusername = $executequery->fields[username];
		echo "$getusername";
}

function insert_assign_username_from_userid($var)
{
        global $conn;
        $query="SELECT username FROM members WHERE USERID='".mysql_real_escape_string($var[USERID])."'";
        $executequery=$conn->execute($query);
        $getusername = $executequery->fields[username];
		return "$getusername";
}

function insert_get_userid_from_did($var)
{
        global $conn;
        $query="SELECT USERID FROM docs WHERE DID='".mysql_real_escape_string($var[DID])."'";
        $executequery=$conn->execute($query);
        $getUSERID = $executequery->fields[USERID];
		return "$getUSERID";
}

function insert_get_advertisement($var)
{
        global $conn;
        $query="SELECT code FROM advertisements WHERE AID='".mysql_real_escape_string($var[AID])."' AND active='1' limit 1";
        $executequery=$conn->execute($query);
        $getad = $executequery->fields[code];
		echo strip_mq_gpc($getad);
}

function insert_get_title_from_did($var)
{
        global $conn;
        $query="SELECT title FROM docs WHERE DID='".mysql_real_escape_string($var[DID])."'";
        $executequery=$conn->execute($query);
        $gettitle = $executequery->fields[title];
		echo "$gettitle";
}

function verify_login_admin()
{
        global $config,$conn;
        if($_SESSION['ADMINID'] != "" && is_numeric($_SESSION['ADMINID']) && $_SESSION['ADMINUSERNAME'] != "" && $_SESSION['ADMINPASSWORD'] != "")
        {
			$query="SELECT * FROM administrators WHERE username='".mysql_real_escape_string($_SESSION['ADMINUSERNAME'])."' AND password='".mysql_real_escape_string($_SESSION['ADMINPASSWORD'])."' AND ADMINID='".mysql_real_escape_string($_SESSION['ADMINID'])."'";
        	$executequery=$conn->execute($query);
			
			if(mysql_affected_rows()==1)
			{
			
			}
			else
			{
				header("location:$config[adminurl]/index.php");
            	exit;
			}
			
        }
		else
		{
			header("location:$config[adminurl]/index.php");
            exit;
		}
}

function insert_get_doc_categories_name($var)
{
        global $conn;
        $query="SELECT categories FROM docs WHERE DID='".mysql_real_escape_string($var[DID])."'";
        $executequery=$conn->execute($query);
        $tempcategories = $executequery->fields[categories];
		
		$temp=explode("|",$tempcategories);
		for($i=1;$i<count($temp);$i++)
			$list.=" or CATID='".$temp[$i]."'";
       	$query="select name from categories_docs where CATID='$temp[0]' $list";
       	$executequery=$conn->execute($query);
		$results = $executequery->fields[name];
		echo "$results";
}

function insert_get_doc_categories_id($var)
{
        global $conn;
        $query="SELECT categories FROM docs WHERE DID='".mysql_real_escape_string($var[DID])."'";
        $executequery=$conn->execute($query);
        $tempcategories = $executequery->fields[categories];
		
		$temp=explode("|",$tempcategories);
		for($i=1;$i<count($temp);$i++)
			$list.=" or CATID='".$temp[$i]."'";
       	$query="select catid from categories_docs where CATID='$temp[0]' $list";
       	$executequery=$conn->execute($query);
		$results = $executequery->fields[catid];
		echo "$results";
}

function insert_get_doc_categories_list($a)
{
    global $conn;
	$CATID = intval($a['CATID']);
	$query="select name from categories_docs where CATID='".mysql_real_escape_string($CATID)."'";
	$executequery=$conn->execute($query);
	$cname = $executequery->fields['name'];
	return $cname;
}



function insert_get_doc_added_date($a)
{
	global $conn;
	$query="SELECT date_added FROM docs WHERE DID='".mysql_real_escape_string($a[did])."'";
	$executequery=$conn->execute($query);
	$list=explode('-',$executequery->fields[date_added]);
	print_r($list[2]);print_r('-');
	print_r($list[1]);print_r('-');
	print_r($list[0]);
}



function insert_get_doc_comment_added_time($a)
{
	global $conn;
	$query="SELECT time_added FROM docs_comments WHERE CID='$a[cid]'";
	$executequery=$conn->execute($query);
	$timeadded = $executequery->fields[time_added];
	echo date('Y-m-d', $timeadded);
}

function insert_get_profile_comment_added_time($a)
{
	global $conn;
	$query="SELECT time_added FROM members_comments WHERE CID='".mysql_real_escape_string($a[cid])."'";
	$executequery=$conn->execute($query);
	$timeadded = $executequery->fields[time_added];
	echo date('Y-m-d', $timeadded);
}

function seo_clean_titles($title)
{
	global $config;
	$title = str_replace ( array ('&Agrave;', '&agrave;', '&Aacute;', '&aacute;', '&Egrave;', '&egrave;', '&Eacute;', '&eacute;', '&Igrave;', '&igrave;', '&Iacute;', '&iacute;', '&Ntilde;', '&ntilde;', '&Ograve;', '&ograve;', '&Oacute;', '&oacute;', '&Ugrave;', '&ugrave;', '&Uacute;', '&uacute;', '&Uuml;', '&uuml;', '&Atilde;', '&sup3;', '&aelig;', '&thorn;', '&aacute;', '&eth;', '&uml;', '&ouml;', '&Ouml;'), array ( 'A', 'a', 'A', 'a', 'E', 'e', 'E', 'e', 'I', 'i', 'I', 'i', 'N', 'n', 'O', 'o', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'o', '', 'ae', 'th', 'a', 'd', 'o', 'o', 'O'), $title);
    $title = str_replace("&amp;", "&", $title);
    $title = preg_replace("/&([a-z]+);/", "", $title); 
    $title = str_replace(
            array(":", "?", ".", "!", "$", "^", "*", ",", ";", "'", '"', "%", "~", "@", "#", "[", "]", "<", ">", "\\", "/", "=", "+"), 
                        "", $title);
    $title = str_replace(array('_', " ", "&"), array("-", "-", "und"), $title);
    $title = htmlentities(strtolower($title));
    $title = str_replace ( array ('&auml;', '&ouml;', '&uuml;', '&szlig;'), array ( 'ae', 'oe', 'ue', 'ss'), $title);
    $title = preg_replace("/&([a-z]+);/", "", $title); 
    $results = rawurlencode($title);	
	return $results.$config['seo_title_include'];
} 

function insert_seo_clean_titles($var)
{
	return seo_clean_titles($var['title']);
}

function seo_clean_titles_sendmail($title)
{
	return seo_clean_titles($title);
}

function insert_get_doc_categories($a)
{
    global $config,$conn;
	$query = "select * from categories_docs order by name asc"; 
	$results = $conn->execute($query);
	$returnthis = $results->getrows();
	return $returnthis;
}

function insert_get_cat_docs($var)
{
    global $config,$conn;
	$query = "select DID,title,viewcount from docs WHERE categories='".mysql_real_escape_string($var[CATID])."' order by rand() limit 3"; 
	$results = $conn->execute($query);
	$returnthis = $results->getrows();
	return $returnthis;
}

function escape($data)
{
    if (ini_get('magic_quotes_gpc'))
	{
    	$data = stripslashes($data);
    }
    return mysql_real_escape_string($data);
}

function insert_doc_categories_count($a)
{
        global $conn;
		global $config;
        $query="SELECT count(*) AS total FROM docs WHERE categories like '%$a[catid]%' AND active='1'";
        $results=$conn->execute($query);
        $returnthis=$results->fields[total];
        return $returnthis;
}

function insert_get_featured_members($a)
{
    global $config,$conn;
	$query = "select USERID,username from members where status='1' AND featured='1' order by rand() limit 8"; 
	$results = $conn->execute($query);
	$returnthis = $results->getrows();
	return $returnthis;
}

function insert_get_search_phrases($var)
{
    global $config,$conn;
	$query = "select * from search_phrases WHERE type='".mysql_real_escape_string($var[type])."' order by searchcount desc limit $config[max_search_phrases]"; 
	$results = $conn->execute($query);
	$returnthis = $results->getrows();
	return $returnthis;
}

function insert_get_rating_stars($a)
{
	global $conn;
    global $config;
    $rating = $a['rating'];
    $count = floor($rating/2);
    $thecount = 0;
	$id = $a['id'];
	$starcount = "1";
	$type = "video";
	
	for($i=0;$i<$count;$i++)
	{
		$returnthis.="<li><a href=\"#\" title=\"".$starcount." Star\" id=\"star_".$type."_".$starcount."_$id\" class=\"full\">&nbsp;</a></li>";
		$thecount++;
		$starcount++;
	}
	
	$ratingcount = $rating/2;
	$ratingcount = $ratingcount - $count;
	
    if(($ratingcount >= 0.5) && ($ratingcount < 1))
    {
		$returnthis.="<li><a href=\"#\" title=\"".$starcount." Star\" id=\"star_".$type."_".$starcount."_$id\" class=\"half\">&nbsp;</a></li>";
		$thecount++;
		$starcount++;
	}
    elseif (($ratingcount > 0) && ($ratingcount < 0.5))
	{
		$returnthis.="<li><a href=\"#\" title=\"".$starcount." Star\" id=\"star_".$type."_".$starcount."_$id\">&nbsp;</a></li>";
		$thecount++;
		$starcount++;
	}
	
	for($i=$thecount;$i<5;$i++)
	{
		$returnthis.="<li><a href=\"#\" title=\"".$starcount." Star\" id=\"star_".$type."_".$starcount."_$id\">&nbsp;</a></li>";
		$starcount++;
	}
	
    if($rating > 0)
	{
		echo $returnthis; 
	}
	else
	{
		echo "<li><a href=\"#\" title=\"1 Star\" id=\"star_".$type."_1_$id\">&nbsp;</a></li><li><a href=\"#\" title=\"2 Star\" id=\"star_".$type."_2_$id\">&nbsp;</a></li><li><a href=\"#\" title=\"3 Star\" id=\"star_".$type."_3_$id\">&nbsp;</a></li><li><a href=\"#\" title=\"4 Star\" id=\"star_".$type."_4_$id\">&nbsp;</a></li><li><a href=\"#\" title=\"5 Star\" id=\"star_".$type."_5_$id\">&nbsp;</a></li>";
	}
}

function get_rating_stars($rating, $id)
{
	global $conn;
    global $config;
    $count = floor($rating/2);
    $thecount = 0;
	$starcount = "1";
	
	for($i=0;$i<$count;$i++)
	{
		$returnthis.="<li><span class=full>&nbsp;<\/span><\/li>\\n";
		$thecount++;
		$starcount++;
	}
	
	$ratingcount = $rating/2;
	$ratingcount = $ratingcount - $count;
	
    if(($ratingcount >= 0.5) && ($ratingcount < 1))
    {
		$returnthis.="<li><span class=half>&nbsp;<\/span><\/li>\\n";
		$thecount++;
		$starcount++;
	}
    elseif (($ratingcount > 0) && ($ratingcount < 0.5))
	{
		$returnthis.="<li><span>&nbsp;<\/span><\/li>\\n";
		$thecount++;
		$starcount++;
	}
	
	for($i=$thecount;$i<5;$i++)
	{
		$returnthis.="<li><span>&nbsp;<\/span><\/li>\\n";
		$starcount++;
	}
	
    if($rating > 0)
	{
		return $returnthis; 
	}
	else
	{
		return "<li><span>&nbsp;<\/span><\/li>\\n<li><span>&nbsp;<\/span><\/li>\\n<li><span>&nbsp;<\/span><\/li>\\n<li><span>&nbsp;<\/span><\/li>\\n<li><span>&nbsp;<\/span><\/li>\\n";
	}
}

function does_doc_exist($a)
{
	global $conn;
    global $config;
    $query="SELECT title FROM docs WHERE DID='".mysql_real_escape_string($a)."'";
    $executequery=$conn->execute($query);
    if ($executequery->recordcount()>0)
        return true;
    else
		return false;
}

function private_doc_access_check($sdid,$suserid)
{
	global $conn;
    global $config;
    $query="SELECT USERID,public FROM docs WHERE DID='".mysql_real_escape_string($sdid)."'";
    $executequery=$conn->execute($query);
	$vuserid = $executequery->fields['USERID'];
	$vpublic = $executequery->fields['public'];
    if ($vpublic == "0")
	{
		if ($suserid == $vuserid)
		{
        	return true;
		}
		else
		{
			$query="SELECT count(*) as total FROM friends WHERE USERID='".mysql_real_escape_string($vuserid)."' AND FRIENDID='".mysql_real_escape_string($suserid)."'";
    		$executequery=$conn->execute($query);
			$totalcount = $executequery->fields[total];
			if ($totalcount > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
    else
	{
		return true;
	}
}



function does_profile_exist($a)
{
	global $conn;
    global $config;
    $query="SELECT username FROM members WHERE USERID='".mysql_real_escape_string($a)."'";
    $executequery=$conn->execute($query);
    if ($executequery->recordcount()>0)
        return true;
    else
		return false;
}

function insert_get_member_avatar($var)
{
        global $config,$conn;
        $query="SELECT customavatar FROM members WHERE USERID='".mysql_real_escape_string($var[USERID])."'";
        $executequery=$conn->execute($query);
        $thecustomavatar = $executequery->fields[customavatar];
		
		$query="SELECT avatar FROM members WHERE USERID='".mysql_real_escape_string($var[USERID])."'";
        $executequery=$conn->execute($query);
        $theavatar = $executequery->fields[avatar];
		
		if($thecustomavatar == "1")
		{
			$avatarpath = $config['cavatarurl'];
		}
		else
		{
			$avatarpath = $config['avatarurl'];
		}
		
		echo $avatarpath."/".$theavatar;
}

function update_viewcount_doc($a)
{
        global $conn;
		$query = "UPDATE docs SET viewcount = viewcount + 1 WHERE DID='".mysql_real_escape_string($a)."'";
        $executequery=$conn->execute($query);
}

function update_viewcount_profile($a)
{
        global $conn;
		$query = "UPDATE members SET profileviews = profileviews + 1 WHERE USERID='".mysql_real_escape_string($a)."'";
        $executequery=$conn->execute($query);
}

function update_last_viewed_doc($a)
{
        global $conn;
		$query = "UPDATE docs SET last_viewed='".date("Y-m-d H:i:s")."' WHERE DID='".mysql_real_escape_string($a)."'";
        $executequery=$conn->execute($query);
}

function update_docs_you_viewed($a)
{
        global $conn;
		$query = "UPDATE members SET docsyouviewed = docsyouviewed + 1 WHERE USERID='".mysql_real_escape_string($a)."'";
        $executequery=$conn->execute($query);
}

function update_your_docs_viewed ($a)
{
        global $conn;
		$query = "UPDATE members SET yourdocsviewed  = yourdocsviewed  + 1 WHERE USERID='".mysql_real_escape_string($a)."'";
        $executequery=$conn->execute($query);
}

function session_verification()
{
    if ($_SESSION[USERID] != "")
	{
		if (is_numeric($_SESSION[USERID]))
		{
        	return true;
		}
    }
	else
		return false;
}

function insert_get_member_docs_count($var)
{
        global $conn;
        $query="SELECT count(*) as total FROM docs WHERE USERID='".mysql_real_escape_string($var[USERID])."' AND public='1' AND active='1'";
        $executequery=$conn->execute($query);
        $results = $executequery->fields[total];
		echo "$results";
}

function insert_get_member_comments_count($var)
{
        global $conn;
        $query="SELECT count(*) as total FROM docs_comments WHERE USERID='".mysql_real_escape_string($var[USERID])."'";
        $executequery=$conn->execute($query);
        $results = $executequery->fields[total];
		echo "$results";
}

function insert_get_doc_favorited_count($var)
{
        global $conn;
        $query="SELECT count(*) as total FROM docs_favorited WHERE DID='".mysql_real_escape_string($var[DID])."'";
        $executequery=$conn->execute($query);
        $results = $executequery->fields[total];
		echo "$results";
}

function insert_get_member_favorited_count($var)
{
        global $conn;
        $query="SELECT count(*) as total FROM docs_favorited WHERE USERID='".mysql_real_escape_string($var[USERID])."'";
        $executequery=$conn->execute($query);
        $results = $executequery->fields[total];
		echo "$results";
}

function insert_get_member_friends_count($var)
{
        global $conn;
        $query="SELECT count(*) as total FROM friends WHERE USERID='".mysql_real_escape_string($var[USERID])."'";
        $executequery=$conn->execute($query);
        $results = $executequery->fields[total];
		echo "$results";
}

function insert_get_member_subscribers_count($var)
{
        global $conn;
        $query="SELECT count(*) as total FROM members_subscribers WHERE subscriber='".mysql_real_escape_string($var[USERID])."'";
        $executequery=$conn->execute($query);
        $results = $executequery->fields[total];
		echo "$results";
}

function insert_get_member_subscribedto_count($var)
{
        global $conn;
        $query="SELECT count(*) as total FROM members_subscribers WHERE subscribee='".mysql_real_escape_string($var[USERID])."'";
        $executequery=$conn->execute($query);
        $results = $executequery->fields[total];
		echo "$results";
}

function insert_get_member_subscriptions_count($var)
{
        global $conn;
        $query="SELECT count(*) as total FROM members_subscribers WHERE subscribee='".mysql_real_escape_string($var[USERID])."'";
        $executequery=$conn->execute($query);
        $results = $executequery->fields[total];
		echo "$results";
}

function insert_get_subscribed_status($var)
{
        global $conn;
        $query="SELECT * FROM members_subscribers WHERE subscriber='".mysql_real_escape_string($var[USERID])."' AND subscribee='".mysql_real_escape_string($_SESSION[USERID])."'";
        $executequery=$conn->execute($query);
		$results = $executequery->getrows();
        $resultscount = count($results);
		if ($resultscount >= 1)
			return "true";
		else
			return "false";
}

function insert_get_friends_status($var)
{
        global $conn;
        $query="SELECT FID FROM friends WHERE USERID='".mysql_real_escape_string($var[USERID])."' AND FRIENDID='".mysql_real_escape_string($_SESSION[USERID])."'";
        $executequery=$conn->execute($query);
		$results = $executequery->getrows();
        $resultscount = count($results);
		if ($resultscount >= 1)
			return "true";
		else
			return "false";
}

function insert_get_member_profilepicture($var)
{
        global $conn;
        $query="SELECT profilepicture FROM members WHERE USERID='".mysql_real_escape_string($var[USERID])."' limit 1";
        $executequery=$conn->execute($query);
		$results = $executequery->fields[profilepicture];
		if ($results == "")
			return "noprofilepicture.gif";
		else
			return $results;
}

function insert_get_fav_doc_status($var)
{
        global $conn;
        $query="SELECT * FROM docs_favorited WHERE USERID='".mysql_real_escape_string($_SESSION[USERID])."' AND DID=$var[DID]";
        $executequery=$conn->execute($query);
		$results = $executequery->getrows();
        $resultscount = count($results);
		if ($resultscount >= 1)
			return "true";
		else
			return "false";
}

function insert_get_tags_doc($a)
{
        global $conn;
        $query="SELECT tags FROM docs WHERE DID='".mysql_real_escape_string($a[did])."'";
        $executequery=$conn->execute($query);
        $results = $executequery->fields[tags];
        $returnthis = explode(" ",$results);
        return $returnthis;
}

function insert_get_tags($a)
{
        $mtag = $a['tags'];
		$mtag = str_replace(",", " ", $mtag);
		$mtag = str_replace("  ", " ", $mtag);
		$returnthis = explode(" ",$mtag);
        return $returnthis;
}

function ajax_rate_doc($didx,$userrating)
{
	global $config,$conn;
    $query="SELECT ratingcount, rating, voter_id FROM docs WHERE DID='".mysql_real_escape_string($didx)."'";
    $executequery=$conn->execute($query);
    $voter_id = $executequery->fields[voter_id]; 
	$ratingcounttemp = $executequery->fields[ratingcount];
	$ratingtemp = $executequery->fields[rating];              
                
    $alreadyvoted = false;
	$only_vote_once = $config['only_vote_once'];
    if($only_vote_once == "1")
    {
    	$thisvoter = "|";
        $thisvoter .= $_SESSION[USERID];
        $thisvoter .= "|";
        $alreadyvoted = strstr($voter_id,$thisvoter);
    }              
                
    if(!$alreadyvoted)
	{
    	if($voter_id == "")
		{
        	$voter_id .= "|";
        }                
        $voter_id .= $_SESSION[USERID];
        $voter_id .= "|";
        $totaltemp = $ratingcounttemp * $ratingtemp;
		$newratingcount = $ratingcounttemp + 1;
        $newrating = ($totaltemp+$userrating)/$newratingcount;
                        
        $query3="UPDATE docs SET ratingcount=ratingcount+1, rating=$newrating, voter_id='$voter_id' WHERE DID='".mysql_real_escape_string($didx)."'";
		$conn->execute($query3);
        return true;
    }
    else
	{
    	return false;
    }
}

function generateCode($length) 
{
	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789";
    $code = "";
    $clen = strlen($chars) - 1;
    while (strlen($code) < $length) {
        $code .= $chars[mt_rand(0,$clen)];
    }
    return $code;
}

function mailme($sendto,$sendername,$from,$subject,$sendmailbody,$bcc="")
{
	global $SERVER_NAME;
	$subject = nl2br($subject);
	$sendmailbody = nl2br($sendmailbody);
	$sendto = $sendto;
	if($bcc!="")
	{
		$headers = "Bcc: ".$bcc."\n";
	}
	$headers = "MIME-Version: 1.0\n";
	$headers .= "Content-type: text/html; charset=utf-8 \n";
	$headers .= "X-Priority: 3\n";
	$headers .= "X-MSMail-Priority: Normal\n";
	$headers .= "X-Mailer: PHP/"."MIME-Version: 1.0\n";
	$headers .= "From: " . $from . "\n";
	$headers .= "Content-Type: text/html\n";
	mail("$sendto","$subject","$sendmailbody","$headers","-f $from");
}

function listdays($selected)
{
	$days = "";
    for($i=1;$i<=31;$i++)
    {
    	if($i == $selected)
		{
        	$days .= "<option value=\"$i\" selected>$i</option>";
        }
        else
		{
        	$days .= "<option value=\"$i\">$i</option>";
        }
    }
    return $days;
}

function listmonths($selected)
{
    $months = "";
    $allmonths = array("","January","February","March","April","May","June","July","August","September","October","November","December");
    for($i=1;$i<=12;$i++)
    {
        if($i == $selected)
		{
        	$months .= "<option value=\"$i\" selected>$allmonths[$i]</option>";
        }
        else
		{
        	$months .= "<option value=\"$i\">$allmonths[$i]</option>";
        }
    }
    return $months;
}

function listyears($selected)
{
        $years = "";
        $thisyear = date("Y");
        for($i=$thisyear-100+13;$i<=$thisyear-13;$i++)
        {
                if($i == $selected)
                        $years .= "<option value=\"$i\" selected>$i</option>";
                else
                        $years .= "<option value=\"$i\">$i</option>";
        }
        return $years;
}

function listcountries($selected)
{
    $country="";
    $countries = array("Afghanistan","Albania","Algeria","American Samoa","Andorra","Angola","Anguilla","Antartica","Antigua and Barbuda","Argentina","Armenia","Aruba","Ascension Island","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Botswana","Bouvet Island","Brazil","Brunei Darussalam","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cape Verde Islands","Cayman Islands","Chad","Chile","China","Christmas Island","Colombia","Comoros","Cook Islands","Costa Rica","Cote d Ivoire","Croatia/Hrvatska","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","East Timor","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Guiana","French Polynesia","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guadeloupe","Guam","Guatemala","Guernsey","Guinea","Guinea-Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Ireland","Isle of Man","Israel","Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea", "Kuwait", "Kyrgyzstan", "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte Island", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn Island", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion Island", "Romania", "Russian Federation", "Rwanda", "Saint Helena", "Saint Lucia", "San Marino", "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovak Republic", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia", "Spain", "Sri Lanka", "Suriname", "Svalbard", "Swaziland", "Sweden", "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Togo", "Tokelau", "Tonga Islands", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Tuvalu", "Uganda", "Ukraine", "United Kingdom", "United States", "Uruguay", "Uzbekistan", "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Western Sahara", "Western Samoa", "Yemen", "Yugoslavia", "Zambia","Zimbabwe");
    for($i=0;$i<count($countries);$i++)
    {
    	if($selected == $countries[$i])
        {
			$country .="<option value=\"$countries[$i]\" selected>$countries[$i]</option>";
		}
        else
		{
			$country .="<option value=\"$countries[$i]\">$countries[$i]</option>";
		}
	}
    return $country;
}

function getPostData($up_dir, $tmp_sid)
{
	$param_array = array();
	$buffer = "";
	$key = "";
	$value = "";
	$paramFileName = $up_dir . $tmp_sid . ".params";
	$fh = fopen($paramFileName, 'r') or kak("Error: Unable to open $paramFileName");
	
	while(!feof($fh))
	{
		$buffer = fgets($fh, 4096);
		list($key, $value) = explode('=', trim($buffer));
		$value = str_replace("~EQLS~", "=", $value);
		$value = str_replace("~NWLN~", "\r\n", $value);
		
		if(isset($key) && isset($value) && strlen($key) > 0 && strlen($value) > 0)
		{
			if(preg_match('/(.*)\[(.*)\]/i', $key, $match))
			{ 
				$param_array[$match[1]][$match[2]] = $value; 
			} 
			else
			{ 
				$param_array[$key] = $value; 
			}
		}
	}

	fclose($fh);
	
	if(isset($param_array['delete_param_file']) && $param_array['delete_param_file'] == 1)
	{
		for($i = 0; $i < 5; $i++)
		{
			if(unlink($paramFileName))
			{ 
				break; 
			}
			else
			{ 
				sleep(1); 
			}
		}
	}
			
	return $param_array;
}

function generate_doc_thumbs($did)
{
	global $config;
	$mydocimgnew=$config['thumbdir']."/".$did.".jpg";
	$myconvertimg = $config['imagedir']."/docconvert.gif";
	generatedocthumbs($myconvertimg,$mydocimgnew,$config[max_thumb_width],$config[max_thumb_height]);
}     

function generate_mini_thumbs($did)
{
	global $config;
	$mydocimgnew=$config['thumbdir']."/".$did."-t.jpg";
	$myconvertimg=$config['thumbdir']."/".$did.".jpg";
	generatedocthumbs($myconvertimg,$mydocimgnew,45,45);
}     


function generatedocthumbs($theconvertimg,$thedocimgnew,$thewidth,$theheight)
{
	global $config;
    $convertimg = $theconvertimg;
    $docimgnew = $thedocimgnew;

    $theimagesizedata = GetImageSize($convertimg);
    $docimgwidth = $theimagesizedata[0];
    $docimgheight = $theimagesizedata[1];
    $docimgformat = $theimagesizedata[2];
	
	$dest_width = $thewidth;
	$dest_height = $theheight;
	
    if($docimgformat == 2)
    {
        $docimgsource = @imagecreatefromjpeg($convertimg);
        $docimgdest = @imageCreateTrueColor($dest_width, $dest_height);
        ImageCopyResampled($docimgdest, $docimgsource, 0, 0, 0, 0, $dest_width, $dest_height, $docimgwidth, $docimgheight);
        imagejpeg($docimgdest, $docimgnew, 100);
        imagedestroy($docimgsource);
        imagedestroy($docimgdest);
    }
    elseif ($docimgformat == 3)
    {
        $docimgsource = imagecreatefrompng($convertimg);
        $docimgdest = imageCreateTrueColor($dest_width, $dest_height);
        ImageCopyResampled($docimgdest, $docimgsource, 0, 0, 0, 0, $dest_width, $dest_height, $docimgwidth, $docimgheight);
        imagepng($docimgdest, $docimgnew, 9);
        imagedestroy($docimgsource);
        imagedestroy($docimgdest);
    }
    else
    {
        $docimgsource = imagecreatefromgif($convertimg);
        $docimgdest = imageCreateTrueColor($dest_width, $dest_height);
        ImageCopyResampled($docimgdest, $docimgsource, 0, 0, 0, 0, $dest_width, $dest_height, $docimgwidth, $docimgheight);
        imagejpeg($docimgdest, $docimgnew, 100);
        imagedestroy($docimgsource);
        imagedestroy($docimgdest);
    }
}

function create_thumbnail2($path, $pid)
{
	for($i=1;$i<=1;$i++)
	{
		global $config;
		if (!file_exists($path)) return(false);
		if (preg_match('/(jpe?g|gif|png)$/i', $path, $matches) !== 1) return(false);
	
		$new_path = $config['thumbdir'].'/'.$pid.".jpg";
		list($width, $height) = getimagesize($path);
		$ratio = $height / $width;
	
		switch($matches[1])
		{
			case 'jpg':
			case 'jpeg':
				if (!function_exists('imagecreatefromjpeg')) return(false);
				$old_image = imagecreatefromjpeg($path);
				break;
			case 'gif':
				if (!function_exists('imagecreatefromgif')) return(false);
				$old_image = imagecreatefromgif($path);
				break;
			case 'png':
				if (!function_exists('imagecreatefrompng')) return(false);
				$old_image = imagecreatefrompng($path);
				break;
		}
	
		$new_width = $config['max_thumb_width'];	
		$new_height = $config['max_thumb_height'];
	
		$new_image = imagecreatetruecolor($new_width, $new_height);
		imagecopyresampled($new_image, $old_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
		ImageTrueColorToPalette($new_image, TRUE, 256);
		imagegif($new_image, $new_path);
	}
}

function escape_data($data) 
{
    if (ini_get('magic_quotes_gpc'))
	{
        $data = stripslashes($data);
    }
        return $data;
} 

function cloudtag($cloudquery, $wtag) 
{
	global $config;
	$tags  = array();
	$cloud = array();
	$query = mysql_query($cloudquery);
	$rows = mysql_num_rows($query);
	if ($rows > 0) 
	{
		while($t = mysql_fetch_array($query)) 
		{
			$tg = str_replace(",", "", $t[0]);
			$db = explode(' ', $tg);
			while(list($key, $value) = each($db))
			{
				$keyword[$value] += 1;
			}
		}

		if (is_array($keyword))
		{
			$minFont=12;
			$maxFont=28;
			$min = min(array_values($keyword));
			$max = max(array_values($keyword));
			$fix = ($max - $min == 0) ? 1 : $max - $min;
			foreach ($keyword as $tag => $count) 
			{
			  $tag = str_replace("+"," ",$tag);
				$size = $minFont + ($count - $min) * ($maxFont - $minFont) / $fix;
				$cloud[] = '<a style="font-size: '. floor($size) .'px;" href="'.$config[baseurl].'/search/'.$wtag.'/a/1/' . $tag .'" title="Tag: '. ucfirst($tag) .' was used '. $count .' times"><span>'. htmlspecialchars(stripslashes(ucfirst($tag))) . '</span></a>';
			}
			$shown = join("\n", $cloud) . "\n";
			return $shown;
		}
	} 
}
	
function insert_get_stripped_phrase3($a)
{
	$stripper = $a[details]; 
	$stripper = html_entity_decode($stripper);
	$stripper = preg_replace('~&#x0*([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $stripper);
   	$stripper = preg_replace('~&#0*([0-9]+);~e', 'chr(\\1)', $stripper);
	$stripper = escape_data($stripper);
	return $stripper;
}

function verify_valid_email($emailtocheck)
{	
	if(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $emailtocheck))
	{
		return false;
	}
	else
	{
		return true;
	}

}

function verify_email_unique($emailtocheck)
{
    global $config,$conn;
	$query = "select count(*) as total from members where email='".mysql_real_escape_string($emailtocheck)."' limit 1"; 
	$executequery = $conn->execute($query);
	$totalemails = $executequery->fields[total];
	if ($totalemails >= 1)
	{
		return false;
	}
	else
	{
		return true;
	}
}

function insert_get_profile_commentcount($a)
{
    global $config,$conn;
	$query = "select count(*) as total from members_comments where PROFILEID=$a[userid]"; 
	$results = $conn->execute($query);
	$returnthis = $results->fields[total];
	return $returnthis;
}

function insert_get_profile_friends($a)
{
    global $config,$conn;
	$query = "select * from friends where USERID=$a[userid] order by rand() limit 10"; 
	$results = $conn->execute($query);
	$returnthis = $results->getrows();
	return $returnthis;
}

function insert_get_time_to_days_ago($a)
{
	global $lang;
	$currenttime = time();
	$timediff = $currenttime - $a[time];
	$oneday = 60 * 60 * 24;
	$dayspassed = floor($timediff/$oneday);
	if ($dayspassed == "0")
	{
		return $lang['704'];
	}
	else
	{
		return $dayspassed." ".$lang['705'];
	}
}

function insert_get_stripped_phrase($a)
{
	$stripper = $a[details]; 
	$stripper = str_replace("\\n", "<br>", $stripper);
	$stripper = str_replace("\\r", "", $stripper);
	$stripper = str_replace("\\", "", $stripper);
	return $stripper;
}

function insert_get_stripped_phrase2($a)
{
	$stripper = $a[details]; 
	$stripper = str_replace("\\n", "\n", $stripper);
	$stripper = str_replace("\\r", "\r", $stripper);
	return $stripper;
}

function insert_get_member_pp_docs_count($var)
{
        global $conn;
        $query="SELECT count(*) as total FROM docs WHERE USERID='".mysql_real_escape_string($var[USERID])."' AND active='1'";
        $executequery=$conn->execute($query);
        $results = $executequery->fields[total];
		echo "$results";
}

function insert_echo_limit_desc($var)
{
	$limit = 17;
	$return = substr($var[desc], 0, $limit);
	$count = strlen($var[desc]);
	if($count > $limit )
	{
		$return .= "...";
	}
	echo $return;
}

function insert_get_static($var)
{
        global $conn;
        $query="SELECT $var[sel] FROM static WHERE ID='".mysql_real_escape_string($var[ID])."'";
        $executequery=$conn->execute($query);
        $returnme = $executequery->fields[$var[sel]];
		$returnme = strip_mq_gpc($returnme);
		echo "$returnme";
}

function verify_email_username($usernametocheck)
{
    global $config,$conn;
	$query = "select count(*) as total from members where username='".mysql_real_escape_string($usernametocheck)."' limit 1"; 
	$executequery = $conn->execute($query);
	$totalu = $executequery->fields[total];
	if ($totalu >= 1)
	{
		return false;
	}
	else
	{
		return true;
	}
}

?>