<?php
// +------------------------------------------------------------------------+
// | PHP Melody version 1.6.7 ( www.phpsugar.com )
// +------------------------------------------------------------------------+
// | PHP Melody IS NOT FREE SOFTWARE
// | If you have downloaded this software from a website other
// | than www.phpsugar.com or if you have received
// | this software from someone who is not a representative of
// | phpSugar, you are involved in an illegal activity.
// | ---
// | In such case, please contact: support@phpsugar.com.
// +------------------------------------------------------------------------+
// | Developed by: phpSugar (www.phpsugar.com) / support@phpsugar.com
// | Copyright: (c) 2004-2011 PhpSugar.com. All rights reserved.
// +------------------------------------------------------------------------+

function db_connect(){
	global $db_host, $db_user, $db_pass, $db_name;
	$connection = @mysql_connect($db_host, $db_user, $db_pass);
	if(!$connection)  
		return false;
	$db = @mysql_select_db($db_name, $connection);
	@mysql_query('SET NAMES utf8');
	@mysql_query('SET CHARACTER SET utf8');
	@mysql_query('SET COLLATION_CONNECTION="utf8_general_ci"');
	@mysql_query("SET @@global.sql_mode='MYSQL40'");
	if(!$db) { return false; }
	return $connection;
}

function magicSlashes($strString){
	return secure_sql($strString);
}

function safename($title)
{
	// replaces every unwanted character form a string with a dash "-"
	$title = str_replace("&", "and", $title);
	$arrStupid = array('feat.', 'feat', '.com', '(tm)', ' ', '*', "'s", '"', ",", ":", ";", "@", "#", "(", ")", "?", "!", "_", "$", "+", "=", "|", "'", '/', "~", "`s", "`", "\\", "^", "[", "]", "{", "}", "<", ">", "%", "");
	
	$title = htmlentities($title);
	$title = preg_replace('/&([a-zA-Z])(.*?);/', '$1', $title); // get rid of html entities
	$title = strtolower("$title");
	$title = str_replace(".", "", $title);
	$title = str_replace($arrStupid, "-", $title);
	$flag = 1;
	while ($flag)
	{
		$newtitle = str_replace("--", "-", $title);
		if ($title != $newtitle)
		{
			$flag = 1;
		}
		else
			$flag = 0;
		$title = $newtitle;
	}
	$len = strlen($title);
	if ($title[$len - 1] == "-")
	{
		$title = substr($title, 0, $len - 1);
	}
	return $title;
}



function fewchars($s, $lenght) 
{
	$str_to_count = html_entity_decode($s);
	if (mb_strlen($str_to_count, "UTF-8" ) <= $lenght)
	{
		return $s;
	}

	$s2 = mb_substr($str_to_count, 0, $lenght - 3, "UTF-8")."...";

	return $s2;
} 

function smarty_fewchars($params, &$smarty)
{
	if (empty($params['s']))
		return '';
	if (empty($params['length']))
		$params['length'] = 255;
	
	return fewchars($params['s'], $params['length']);
}

function load_categories($args = array())
{
	global $_video_categories, $_article_categories;
	
	$defaults = array('db_table' => 'pm_categories',
					  'order_by' => 'position',
					  'sort' => 'ASC',
					  'columns' => '*'
					);
	
	$options = array_merge($defaults, $args);
	extract($options);
	
	if ($db_table == 'pm_categories' && is_array($_video_categories))
	{
		return $_video_categories;
	}
	else if ($db_table == 'art_categories' && is_array($_article_categories))
	{
		return $_article_categories;
	}	
	
	if ($columns != '*' && strpos($columns, 'id') === false)
	{
		$columns = 'id, '.$columns;
	}
	
	$sql = "SELECT $columns FROM $db_table 
			ORDER BY $order_by $sort";
	
	$result = mysql_query($sql);
	if ( ! $result)
	{
		return false;
	}
	
	$categories = array();
	
	while ($row = mysql_fetch_assoc($result))
	{
		$categories[$row['id']] = $row;
	}
	mysql_free_result($result);
	
	if ($db_table == 'pm_categories') 
	{
		$_video_categories = $categories;
	}
	else
	{
		$_article_categories = $categories;
	}
	
	return $categories;
}

function categories_dropdown_display_option($parent, &$all_children, $level = 0, $options)
{
	$output = '';
	
	if ( ! $parent)
		return '';
	
	$value_attr_db_col = ($options['value_attr_db_col'] == '') ? 'id' : $options['value_attr_db_col']; 
	
	$padding = str_repeat($options['spacer'], $level);

	$output .= '<option value="'. $parent[$value_attr_db_col] .'" ';
	if ( ! is_array($options['selected']))
	{
		$output .= ($options['selected'] == $parent[$value_attr_db_col]) ? 'selected="selected"' : '';
	}
	else
	{
		// multiple selected items for DDCL
		if (in_array($parent[$value_attr_db_col], $options['selected']))
		{
			$output .= 'selected="selected"';
		}
	}
	$output .= ($options['option_attr_id'] != '') ? ' id="'. $options['option_attr_id'] .'" ' : '';
	$output .= '>'. $padding .' '. htmlentities($parent['name'],ENT_COMPAT,'UTF-8') .'</option>';
	$output .= "\n";
	
	if (isset($all_children[$parent['id']]))
	{
		foreach ($all_children[$parent['id']] as $k => $child)
		{
			$output .= categories_dropdown_display_option($child, $all_children, $level+1, $options);
		}
		unset($all_children[$parent['id']]);
	}
	
	return $output;
	
}

function categories_dropdown($args = array())
{
	global $lang;
	
	$output = '';
	
	$defaults = array(
		'db_table' => 'pm_categories',
		'attr_name' => 'category',
		'attr_class' => 'category_dropdown',
		'attr_id' => 'category_dropdown',
		'other_attr' => '',
		'selected' => 0, 
		'select_all_option' => true,
		'first_option_text' => $lang['select'],
		'first_option_value' => '-1',
		'no_options_text' => 'No categories',
		'order_by' => 'position',
		'sort' => 'ASC',
		'parents_only' => false,
		'options_only' => false,
		'value_attr_db_col' => 'id',
		'spacer' => '&nbsp;&nbsp;&nbsp;',
		'option_attr_id' => ''
	);
	$empty = array();
	
	$options = array_merge($defaults, $args);
	extract($options);
	
	$parents = $parent_ids = $children = array();
	
	$categories = load_categories($options);
	$count = count($categories);

	if($count > 0)
	{
		foreach ($categories as $c_id => $c)
		{
			if ($c['parent_id'] == 0)
			{
				$parents[] = $c;
				$parent_ids[] = $c['id'];
			}
			else
			{
				$children[$c['parent_id']][] = $c;
			}
		}
	}
	
	if ( ! $options_only)
	{
		$output .= "<select name='$attr_name' id='$attr_id' class='$attr_class' $other_attr>\n";
	}
	
	if ($select_all_option)
	{
		$first_opt_selected = (empty($selected)) ? 'selected="selected"' : '';
		$output .= "<option value='$first_option_value' $first_opt_selected>$first_option_text</option>\n";
	}

	if ($count)
	{
		foreach ($parents as $k => $p)
		{
			if ($parents_only == true)
			{
				$output .= categories_dropdown_display_option($p, $empty, 0, $options);
			}
			else
			{
				$output .= categories_dropdown_display_option($p, $children, 0, $options);
			}
			
		}
	}
	
	if (count($children) > 0 && ( ! $parents_only))
	{
		foreach ($children as $parent_id => $orphans)
		{
			foreach ($orphans as $k => $orphan)
			{
				$output .= categories_dropdown_display_option($orphan, $empty, 0, $options);
			}
		}
	}
	
	if ( ! $options_only)
	{
		$output .= "</select>\n";
	}
	
	return $output;
}

function list_categories_display_item($item, &$all_children, $level = 0, $options)
{
	$li_class = $caturl = $output = $li_item = '';

	if ( ! $item)
		return;
	
	$padding = str_repeat($options['spacer'], $level);
		
	// href
	if(_SEOMOD == 1) 
	{
		$caturl = _URL."/browse-". $item['tag'] ."-videos-1-date.html";
	}
	else
	{
		$caturl = _URL."/category.php?cat=". $item['tag'];
	}
	
	$sub_cats = '';

	if (isset($all_children[$item['id']]) && ($level < $options['max_levels'] || $options['max_levels'] == 0))
	{
		$sub_cats .= "\n";
		
		foreach ($all_children[$item['id']] as $k => $child)
		{
			if ( ! isset($newlevel))
			{
				$newlevel = true;
				$subcats_ul_class = ($child['id'] == $options['selected'] || $options['expand_items'] == true) ? 'visible_li' : 'hidden_li';
				$sub_cats .= "$padding<ul class='$subcats_ul_class'>\n";
			}
			$sub_cats .= list_categories_display_item($child, $all_children, $level+1, $options);
		}
		unset($all_children[$item['id']]);
	}
	
	// li class
	if ($item['id'] == $options['selected'])
	{
		if ($item['parent_id'] == 0)
		{
			$li_class = 'selectedcat';
		}
		else 
		{
			$li_class = 'selectedsubcat';
		}
	}
	else 
	{
		$li_class = '';
	}
	
	if ($options['selected_grandfather'] > 0)
	{
		if ($item['id'] == $options['selected_grandfather'])
		{
			if ($item['parent_id'] == 0)
			{
				$li_class = 'selectedcat';
			}
			else 
			{
				$li_class = 'selectedsubcat';
			}
		}
	}
		
	// li
	$output .= $padding .'<li class="'. $li_class .'"><a href="'. $caturl .'">'. htmlentities($item['name'],ENT_COMPAT,'UTF-8') .'</a>';
	$output .= $sub_cats;
	
	if (isset($newlevel) && $newlevel)
	{
		$output .= "$padding</ul>\n";
	}
		
	$output .= "$padding</li>\n";
	
	return $output;
}

function list_categories($parent = 0, $selected = 0, $args = array()) // deprecated: $parent 
{
	$output = '';
	
	$defaults = array(
		'db_table' => 'pm_categories',
		'selected' => 0, 
		'order_by' => 'position',
		'sort' => 'ASC',
		'selected_grandfather' => 0, 
		'spacer' => "\t",
		'max_levels' => 1,
		'ul_wrapper' => true
	);
	
	$options = array_merge($defaults, $args);
	$options['selected'] = ( ! is_object($selected)) ? $selected : 0;
	extract($options);
	
	$parents = $parent_ids = $children = array();
	$categories = load_categories($options);
	
	foreach ($categories as $c_id => $c)
	{
		if ($c['parent_id'] == 0)
		{
			$parents[] = $c;
			$parent_ids[] = $c['id'];
		}
		else
		{
			$children[$c['parent_id']][] = $c;
		}
	}

	// find "grandfather" of selected child category
	if (count($parent_ids) > 0 && $selected > 0 && ( ! in_array($selected, $parent_ids)))
	{
		$options['selected_grandfather'] = $selected;

		$counter = 0;
		$exit_limit = count($parent_ids) * 3;
		while (( ! in_array($options['selected_grandfather'], $parent_ids)) && $counter < $exit_limit)
		{
			$find = $options['selected_grandfather'];
			foreach ($children as $pid => $children_arr)
			{
				$found = false;
			
				if (count($children_arr) > 0)
				{
					foreach ($children_arr as $k => $child)
					{
						if ($child['id'] == $find)
						{
							$found = true;
							$options['selected_grandfather'] = $child['parent_id'];
							break;
						}
					}
					if ($found)
					{
						break;
					}
				}
			}
			
			$counter++;
		}
	}
	
	foreach ($parents as $k => $p)
	{
		$options['expand_items'] = ($options['selected_grandfather'] == $p['id']) ? true : false;
		$output .= list_categories_display_item($p, $children, 0, $options);
	}

	if (count($children) > 0 && $options['max_levels'] == 0)
	{
		foreach ($children as $parent_id => $orphans)
		{
			foreach ($orphans as $k => $orphan)
			{
				$orphan['parent_id'] = 0;
				$output .= list_categories_display_item($orphan, $empty, 0, $options);
			}
		}
	}
	
	//	wrapper
	if ($ul_wrapper)
	{
		return "<ul id='ul_categories'>\n$output\n</ul>";
	}
	
	return $output;
}

function list_subcategories($parent = 0, $selected) 
{ 
	if (empty($parent))
	{
		return '';
	}

	$subcategories = '';
	$url = '';
	
	$categories = load_categories();
	
	foreach ($categories as $c_id => $c)
	{
		if ($c['parent_id'] == $parent)
		{
			if (_SEOMOD == 1)
			{
				$url = _URL."/browse-".$c['tag']."-videos-1-date.html";
			}
			else
			{
				$url = _URL."/category.php?cat=".$c['tag'];
			}
			$subcategories .= ($c['id'] == $selected) ? '<li class="selectedcat">' : '<li>';
			$subcategories .= '<a href="'. $url .'">'. $c['name'] .' ('. $c['total_videos'] .')</a>';
			$subcategories .= '</li>';
		}
	}
	return $subcategories;
}

function get_all_children($parent_id, &$children, &$all_descendents)
{
	$all_descendents[] = $parent_id;
	if (isset($children[$parent_id]))
	{
		foreach ($children[$parent_id] as $k => $child)
		{
			get_all_children($child['id'], $children, $all_descendents);
		}
		unset($children[$parent_id]);
	}	
}

function top_videos($sortby = "views", $limit = 7)
{
	global $config;

	$sql	= '';
	$query	= '';

	if ('' == $sortby)
	{
		$mode = 'views';
	}
	if ('' == $limit)
	{
		$limit = 7;
	}
	
	switch ($sortby)
	{
		default:
		case 'views':
		
			$sql = "SELECT * 
					FROM pm_videos 
					ORDER BY site_views DESC  
					LIMIT ".$limit;
		break;
		
		case 'rating':
		
			if (count_entries('pm_ratings', '', '') >= $limit)
			{
				$uniq_ids = '';
				$sql = "SELECT id, total_value/total_votes AS Score 
						FROM pm_ratings 
						WHERE total_votes >= (SELECT AVG(total_votes) 
											  FROM pm_ratings) 
						ORDER BY Score DESC 
						LIMIT ". $limit;

				$query 	=  @mysql_query($sql);
				if ( ! $query)
				{
					return '';
				}
				$total_results 	= @mysql_num_rows($query);
				$ratings 		= array();
				
				while ($row = mysql_fetch_assoc($query))
				{
					$uniq_ids .= "'". $row['id'] ."', ";
					$ratings[ $row['id'] ] = $row['Score'];
				}
				$uniq_ids = substr($uniq_ids, 0, -2);
				@mysql_free_result($query);
			
				if ($total_results < $limit)
				{
					$new_limit = $limit - $total_results;
					
					$sql = "SELECT id, total_value/total_votes AS Score 
						FROM pm_ratings 
						WHERE id NOT IN(". $uniq_ids .") 
						ORDER BY Score DESC 
						LIMIT ". $new_limit;
						
					$query =  @mysql_query($sql);
					$total_results 	= @mysql_num_rows($query);
					if ($total_results > 0)
					{
						$uniq_ids .= ', ';
						while ($row = mysql_fetch_assoc($query))
						{
							$uniq_ids .= "'". $row['id'] ."', ";
							$ratings[ $row['id'] ] = $row['Score'];
						}
						$uniq_ids = substr($uniq_ids, 0, -2);
					}
					
					@mysql_free_result($query);
				}

				$sql = "SELECT * 
						FROM pm_videos 
						WHERE uniq_id IN (".$uniq_ids.")";

				$query = @mysql_query($sql);
				if ( ! $query)
				{
					return '';
				}
				while ($row = @mysql_fetch_assoc($query))
				{
					$videos[ $row['uniq_id'] ] = $row;
				}
				
				/*
				 *	Output
				 */
				$results = '';	
				$i = 1;

				foreach ($ratings as $uniq_id => $score)
				{
					$results .= '<div class="item">';
					$results .= '<a href="'. makevideolink($videos[ $uniq_id ]['uniq_id'], $videos[ $uniq_id ]['artist'], $videos[ $uniq_id ]['video_title']) .'">';
					$results .= '<img src="'. show_thumb($videos[ $uniq_id ]['uniq_id']) .'" 
								alt="'. $videos[ $uniq_id ]['video_title'] .'" 
								class="imag" width="72" height="53" align="left" /></a>';
					$results .= '<span class="';
					$results .= ($i % 2 == 0) ? 'artist_name' : 'artist_name_1';
					$results .= '">'. fewchars($videos[ $uniq_id ]['artist'], 29) .'</span>';
					$results .= '<a href="'. makevideolink($videos[ $uniq_id ]['uniq_id'], $videos[ $uniq_id ]['artist'], $videos[ $uniq_id ]['video_title']) .'" class="song_name" 
								title="'. str_replace('"', '&quot;', $videos[ $uniq_id ]['video_title']) .'">
								'. fewchars($videos[ $uniq_id ]['video_title'], 25) .'</a>';
					$results .= '</div>';
					$i++;
				}
				return $results;
			}
			else
			{
				$sql = "SELECT * 
					FROM pm_videos 
					ORDER BY site_views DESC  
					LIMIT ".$limit;
			}
		break;
		case "chart":
			$sql = "SELECT pm_videos.*, pm_chart.uniq_id 
					FROM pm_chart JOIN pm_videos ON (pm_chart.uniq_id = pm_videos.uniq_id) 
					ORDER BY pm_chart.views DESC 
					LIMIT ".$limit;
		
		break;
	}
	
	$query = @mysql_query($sql);
	if ( ! $query)
	{
		return '';
	}
	
	$results = '';	
	$i = 1;
	while ($row = mysql_fetch_assoc($query))
	{
		$results .= '<div class="item">';
		$results .= '<a href="'. makevideolink($row['uniq_id'], $row['artist'], $row['video_title']) .'">';
		$results .= '<img src="'. show_thumb($row['uniq_id']) .'" 
					alt="'. $row['video_title'] .'" 
					class="imag" width="72" height="53" align="left" /></a>';
		$results .= '<span class="';
		$results .= ($i % 2 == 0) ? 'artist_name' : 'artist_name_1';
		$results .= '">'. fewchars($row['artist'], 90) .'</span>';
		$results .= '<a href="'. makevideolink($row['uniq_id'], $row['artist'], $row['video_title']) .'" class="song_name" 
					title="'. str_replace('"', '&quot;', $row['video_title']) .'">
					'. fewchars($row['video_title'], 30) .'</a>';
		$results .= '</div>';
		$i++;
	}
	return $results;
}

function request_video($unique_id = '', $page = "detail", $autoplay = false)
{
	global $config;
	
	$old_src_id = 0;
	$video 		= array();
	
	if($unique_id == '')
	{
		return 0;
	}
	
	if(ctype_alnum($unique_id) === false)
	{
		return 0;
	}
	
	$unique_id = secure_sql($unique_id);
	
	$sql = "SELECT pm_videos.*, pm_videos_urls.mp4, pm_videos_urls.direct 
			FROM pm_videos 
			LEFT JOIN pm_videos_urls 
				   ON (pm_videos.uniq_id = pm_videos_urls.uniq_id) 
			WHERE pm_videos.uniq_id = '". $unique_id ."'";

	$result =  @mysql_query($sql);
	if ( ! $result)
	{
		return 0;
	}
	
	if (mysql_num_rows($result) > 0)
	{
		$video = mysql_fetch_assoc($result);
	}
	else
	{
		return 0;
	}
	
	mysql_free_result($result);
	
	$sql = "SELECT * 
			FROM pm_ratings 
			WHERE id = '". $unique_id ."'";
	$result =  @mysql_query($sql);
	if ( ! $result)
	{
		$video['rating'] = 0;
	}
	
	if (mysql_num_rows($result) > 0)
	{
		$row = mysql_fetch_assoc($result);
		mysql_free_result($result);
		
		$video['rating'] = round($row['total_value'] / $row['total_votes'], 1);
	}
	
	$video['artist'] 		= stripslashes($video['artist']);
	$video['video_title']	= stripslashes($video['video_title']);
	$video['added']			= time_since($video['addded']);
	$video['submitted']		= ($video['submitted'] == 'bot') ? 'admin' : $video['submitted'];
	
	$video_sources = fetch_video_sources();
	
	$video['video_player']	= $config['video_player'];
	
	if ($video['source_id'] == 3)
	{
		$config['video_player'] = 'jwplayer';
		$video['video_player'] = 'jwplayer';
	}
	
	switch ($config['video_player'])
	{
		case 'jwplayer':
		case 'flvplayer':
	
			if ($video_sources[ $video['source_id'] ]['flv_player_support'] == 0 || 
				$video_sources[ $video['source_id'] ]['user_choice'] == 'embed')
			{
				$video['video_player']	= 'embed';
			}

		break;
		
		case 'embed':
			
			if ($video_sources[ $video['source_id'] ]['embed_player_support'] == 0)
			{
				$video['video_player']	= 'flvplayer';
			}
			
		break;
	}
	
	if ($video['source_id'] == 0)
	{
		$sql = "SELECT * 
				FROM pm_embed_code 
				WHERE uniq_id = '". $video['uniq_id'] ."'";

		$result = mysql_query($sql);
		$row = mysql_fetch_assoc($result);
		mysql_free_result($result);
		
		$video['video_player'] = 'embed';
		$video['embed_code'] = $row['embed_code'];
	}
	
	if ($video['source_id'] == 1 || $video['source_id'] == 2)
	{
		$ext = strtolower(array_pop(explode('.', $video['url_flv'])));
		$old_src_id = $video['source_id'];
		switch ($ext)
		{
			case 'mov':
			case '3gp':
			case '3g2':
			case 'm4a':
			//case 'm4v':
				
				$video['video_player']  = 'embed';
				$video['source_id'] 	= $video_sources['quicktime']['source_id'];
				$video['url_flv'] = _URL .'/videos.php?vid='. $video['uniq_id'];
				
			break;
			
			case 'wmv':
			case 'asf':
			case 'wma':
				
				$video['video_player']  = 'embed';
				$video['source_id'] 	= $video_sources['windows media player']['source_id'];
				$video['url_flv'] = _URL .'/videos.php?vid='. $video['uniq_id'];
				//$video['url_flv'] = _VIDEOS_DIR . $video['url_flv'];
				
			break;
			
			case 'mp3':
				
				$video['video_player']  = 'embed';
				$video['source_id'] = $video_sources['mp3']['source_id'];
				$video['url_flv'] = _URL .'/videos.php?vid='. $video['uniq_id'];
			
			break;
			
			case 'mkv':
			case 'divx':
			case 'avi':
				
				$video['video_player']  = 'embed';
				$video['source_id'] 	= $video_sources['divx']['source_id'];
				$video['url_flv'] = _URL .'/videos.php?vid='. $video['uniq_id'];
				
			break;
		}
	}
	
	if ($video['source_id'] == $video_sources['mp3']['source_id'])
	{
		$video['url_flv'] = _URL .'/videos.php?vid='. $video['uniq_id'];
		$video['video_player']  = 'embed';
	}
	
	if ($video['source_id'] == 3 && $video['direct'] == '')
	{
		$video['direct'] = 'http://www.youtube.com/watch?v='. $video['yt_id'];
	}
	
	if ($video['yt_thumb'] != '')
	{
		if (strpos($video['yt_thumb'], 'http') !== false)
		{
			$video['preview_image'] = $video['yt_thumb'];
		}
		else
		{
			$video['preview_image'] = _THUMBS_DIR . $video['yt_thumb'];
		}
	}
	
	if ($video['video_player'] == 'embed')
	{
		if ($video['source_id'] > 0)
		{
			$embed_code = $video_sources[ $video['source_id'] ]['embed_code'];
		}
		else
		{
			$embed_code = $video['embed_code'];
		}
		
		if ($video['source_id'] == $video_sources['sevenload']['source_id'] && strlen($video['yt_id']) > 7)
		{
			$video['yt_id'] = substr($video['yt_id'], 0, 7);
		}
		
		$embed_code = str_replace("%%yt_id%%", $video['yt_id'], $embed_code);
		$embed_code = str_replace("%%player_bgcolor%%", _BGCOLOR, $embed_code);
		$embed_code = str_replace("%%player_timecolor%%", _TIMECOLOR, $embed_code);
		$video['url_flv'] = str_replace("&", "&amp;", $video['url_flv']);
		$embed_code = str_replace("%%url_flv%%", $video['url_flv'], $embed_code);
		$embed_code = str_replace("%%direct%%", $video['direct'], $embed_code);
		$embed_code = str_replace("%%use_hq_vids%%", $config['use_hq_vids'], $embed_code);
		$embed_code = str_replace("%%yt_thumb%%", $video['preview_image'], $embed_code);
		
		
		if ($autoplay == true)	//	Override autoplay
		{
			$embed_code = str_replace("%%player_autoplay%%", '1', $embed_code);
		}
		else
		{
			if ($page == 'embed')
			{
				$embed_code = str_replace("%%player_autoplay%%", '0', $embed_code);
			}
			else
			{
				$embed_code = str_replace("%%player_autoplay%%", $config['player_autoplay'], $embed_code);
			}
		}
		
		if ($video['source_id'] == 17 && $video['direct'] != '')	//	trilulilu.ro
		{
			$temp = '';
			$temp = rtrim($video['direct'], "/");
			$temp = str_replace(array('http://', 'www.'), "", $temp);
			
			@preg_match('/^trilulilu\.ro\/(.*?)\/([a-zA-Z0-9]+)$/i', $temp, $matches);
			$embed_code = str_replace("%%username%%", $matches[1], $embed_code);
		}
		
		$embed_code = str_replace( array("\n", "\r", "'"), array(' ', ' ', '"'), $embed_code);
		
		switch ($page)
		{
			case 'index':
				
				$embed_code = str_replace("%%player_w%%", _PLAYER_W_INDEX, $embed_code);
				$embed_code = str_replace("%%player_h%%", _PLAYER_H_INDEX, $embed_code);
				$embed_code = str_replace("%%player_wmode%%", 'transparent', $embed_code);
				
			break;
			
			case 'favorites':
				
				$embed_code = str_replace("%%player_w%%", _PLAYER_W_FAVS, $embed_code);
				$embed_code = str_replace("%%player_h%%", _PLAYER_H_FAVS, $embed_code);
				$embed_code = str_replace("%%player_wmode%%", 'transparent', $embed_code);
				
			break;
			
			case 'embed':
				
				$embed_code = str_replace("%%player_w%%", _PLAYER_W_EMBED, $embed_code);
				$embed_code = str_replace("%%player_h%%", _PLAYER_H_EMBED, $embed_code);
				$embed_code = str_replace("%%player_wmode%%", 'window', $embed_code);
							
			break; 
			
			default:
			case 'detail':
			
				$embed_code = str_replace("%%player_w%%", _PLAYER_W, $embed_code);
				$embed_code = str_replace("%%player_h%%", _PLAYER_H, $embed_code);
				$embed_code = str_replace("%%player_wmode%%", 'window', $embed_code);
				
			break;
		}		
		
		$embed_code = str_replace("%%site_url%%", _URL, $embed_code);
		
		$video['embed_code'] = $embed_code;
		
		if ($old_src_id > 0)
		{
			$video['source_id'] = $old_src_id;
		}
	}
	
	$video['site_views_formatted'] = pm_number_format($video['site_views']);
	
	return $video;
}

function update_view_count($video_id) // @since 1.6.5
{
	$updated = false;
	$session_list = array();
	$cookie_list = array();

	$fn_encode = 'base64_encode'; //(function_exists('gzcompress')) ? 'gzcompress' : 'base64_encode';
	$fn_decode = 'base64_decode'; //(function_exists('gzuncompress')) ? 'gzuncompress' : 'base64_decode';

	if ($_COOKIE['watched_video_list'])
	{
		$cookie_list = (array) explode(',', $fn_decode($_COOKIE['watched_video_list']));
	}

	if ( ! in_array('watched', $_SESSION))
	{
		@session_register('watched');
		$_SESSION['watched'] = '';
	}
	
	$session_list = (array) unserialize($_SESSION['watched']);

	$list = array_merge($cookie_list, $session_list);

	if ( ! in_array($video_id, $list))
	{
		$sql = "UPDATE pm_videos 
				SET site_views = site_views+1, 
					lastwatched = '". time() ."' 
				WHERE id = '". $video_id ."'";
		$result = @mysql_query($sql);
		$session_list[] = $cookie_list[] = $video_id;
		$_SESSION['watched'] = serialize($session_list);
		@setcookie('watched_video_list', $fn_encode(implode(',', $cookie_list)), time() + 86400, COOKIE_PATH); // keep for 24 hours
		$updated = true;
	}
	return $updated;
}

function list_videos($how = 'added', $limit = '5') { // newest, top views, etc etc etc

	$query = mysql_query("SELECT * FROM pm_videos ORDER BY $how DESC LIMIT $limit");
	$result = '';	
	while($row = mysql_fetch_array($query)) {
		
		$results .= "
		<div class=\"item\">
		<a href=\"". makevideolink($row['uniq_id'], $row['artist'], $row['video_title']) ."\"><img src=\"".show_thumb($row['uniq_id'])."\" alt=\"".$row['video_title']."\" class=\"imag\" width=\"107\" height=\"72\" /></a>
		<a href=\"". makevideolink($row['uniq_id'], $row['artist'], $row['video_title']) ."\" class=\"song_name\">
		<span class=\"artist_name\">".fewchars($row['artist']." - ".$row['video_title'], 30)."</span>
		</a>
		<span class=\"item_views\">". pm_number_format($row['site_views']) ." views</span>
		</div>";
	
	}
	return $results;
}

function show_more($what_kind = 'related', $categories = '1', $limit = 5) 
{ 
	global $lang;
	
	$categories	= secure_sql( trim($categories) );
	$query	= '';
	$result	= '';
	$sql	= '';
	
	if($what_kind != 'related' && $what_kind != 'same_artist' && $what_kind != 'best_in_category')
		$what_kind = 'related';		//	default value
	
	switch($what_kind)
	{
		case 'related':
			$sql = "SELECT * 
					FROM pm_videos 
					WHERE category = '".$categories."' 
					ORDER BY RAND() 
					LIMIT ".$limit;
		break;
		
		case 'same_artist':
			$sql = "SELECT * 
					FROM pm_videos 
					WHERE artist='".$categories."' 
					ORDER BY added DESC 
					LIMIT ".$limit;
		break;
		
		case 'best_in_category':
			if(strstr($categories, ",")) 
			{
				$temp = explode(",", $categories);
				$categories = trim($temp[0]);
			}
			$sql = "SELECT pm_videos.*, pm_ratings.*
					FROM pm_videos 
					JOIN pm_ratings ON ( pm_videos.uniq_id = pm_ratings.id ) 
					WHERE (category LIKE '%,$categories,%' 
						   OR category LIKE '%,$categories' 
						   OR category LIKE '$categories,%' 
						   OR category LIKE '$categories')
					ORDER BY total_votes DESC , total_value DESC 
					LIMIT ".$limit;
		break;
	}

	$query = @mysql_query($sql);
	
	// backup 
	if (mysql_num_rows($query) == 0 && $what_kind == 'best_in_category')
	{
		$sql = "SELECT * 
				FROM pm_videos 
				WHERE category = '".$categories."' 
				ORDER BY site_views DESC  
				LIMIT ".$limit;
		$query = @mysql_query($sql);
	}
	
	$result = '';
	if(@mysql_num_rows($query) > 0)
	{
		while($row = mysql_fetch_array($query))
		{
			$results .= "
			<div class=\"item\">
			<a href=\"".makevideolink($row['uniq_id'], $row['artist'], $row['video_title'])."\"><img src=\"".show_thumb($row['uniq_id'])."\" alt=\"".$row['video_title']."\" class=\"imag\" width=\"116\" height=\"87\" /></a>
			<span class=\"artist_name\">".$row['artist']."</span>
			<a href=\"".makevideolink($row['uniq_id'], $row['artist'], $row['video_title'])."\" class=\"song_name\">".$row['video_title']."</a>
			</div>";
		}
		mysql_free_result($query);
	}
	else
	{
		$results .= "
			<div class=\"item\">
			".$lang['top_videos_msg1']."
			</div>";
	}
	
	return $results;
}

function get_catid($tag) 
{
	$categories = load_categories();
	foreach ($categories as $c_id => $c)
	{
		if ($c['tag'] == $tag)
		{
			return $c_id;
		}
	}
	return false;
}
function get_catname($tag) 
{
	$categories = load_categories();
	foreach ($categories as $c_id => $c)
	{
		if ($c['tag'] == $tag)
		{
			return $c['name'];
		}
	}
	return '';
}


function getheaders($url,$format=0) {
   $url_info=parse_url($url);
   $port = isset($url_info['port']) ? $url_info['port'] : 80;
   $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);
   if($fp) {
	   if(!$url_info['path']){
					 $url_info['path'] = "/";
				 }
				 if($url_info['path'] && !$url_info['host']){
					$url_info['host'] = $url_info['path'];
					$url_info['path'] = "/";
				 }
				 if( $url_info['host'][(strlen($url_info['host'])-1)] == "/" ){
					$url_info['host'][(strlen($url_info['host'])-1)] = "";
				 }
				 if(!$url_array[scheme]){
					 $url_array[scheme] = "http"; //we always use http links
					}
				 $head = "HEAD ".@$url_info['path'];
				 if( $url_info['query'] ){
					 $head .= "?".@$url_info['query'];
					}
	   $head .= " HTTP/1.0\r\nHost: ".@$url_info['host']."\r\n\r\n";
				 fputs($fp, $head);
	   while(!feof($fp)) {
		   if($header=trim(fgets($fp, 1024))) {
			   if($format == 1) {
				   $h2 = explode(':',$header);
				   // the first element is the http header type, such as HTTP/1.1 200 OK,
				   // it doesn't have a separate name, so we have to check for it.
				   if($h2[0] == $header) {
					   $headers['status'] = $header;
				   }
				   else {
					   $headers[strtolower($h2[0])] = trim($h2[1]);
				   }
			   }
			   else {
				   $headers[] = $header;
			   }
		   }
	   }
	   return $headers;
   }
   else {
	   return false;
   }
}

function make_youtube_player($y_id, $length, $width = '496', $height = '401', $auto_play = '1') {
	//	@deprecated
}

function make_youtube_player2($uniq_id, $name, $width = 496, $height = 401, $auto_play = 'false') {	
	//	@deprecated
}

function generate_embed_code($uniq_id = '')
{
	$embed_code = '';
	$backlink 	= '';
	
	if ($uniq_id == '')
		return '';
	
	$video = request_video($uniq_id, 'embed', true);

	if ( ! is_array($video))
	{
		return '';
	}
	
	$embed_code = "";
	$embed_code .= '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"';
	$embed_code .= ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"';
	$embed_code .= ' width="'. _PLAYER_W_EMBED .'" height="'. _PLAYER_H_EMBED . '"';
	$embed_code .= '>';
	$embed_code .= '<param name="scale" value="noscale" />';
	$embed_code .= '<param name="allowFullScreen" value="true" />';
	$embed_code .= '<param name="allowScriptAccess" value="always" />';
	$embed_code .= '<param name="allowNetworking" value="all" />';
	$embed_code .= '<param name="bgcolor" value="#'. _BGCOLOR .'" />';
	
	if ($video['video_player'] == 'flvplayer')
	{
		// object params
		$embed_code .= '<param name="movie" value="'. _URL .'/fpembed-'. $video['uniq_id'] .'.swf" />';
 
		// embed tag
		$embed_code .= '<embed src="'. _URL .'/fpembed-'. $video['uniq_id'] .'.swf';
		$embed_code .= '" width="'. _PLAYER_W_EMBED .'" height="'. _PLAYER_H_EMBED . '"';
		$embed_code .= ' scale="noscale" bgcolor="#'. _BGCOLOR .'"';
		$embed_code .= ' type="application/x-shockwave-flash" allowFullScreen="true" allowScriptAccess="always" ';
		$embed_code .= ' allowNetworking="all" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="window">';
		$embed_code .= '</embed>';
		$embed_code .= '</object>';
	}
	else if ($video['video_player'] == 'jwplayer')
	{
		$jw_flashvars = '';
		if ($video['source_id'] == 3)
		{
			$jw_flashvars .= '&file='. urlencode($video['direct']);
			$jw_flashvars .= '&type=youtube';
		}
		else
		{
			$jw_flashvars .= '&file='. urlencode(_URL ."/videos.php?vid=". $video['uniq_id']);
			$jw_flashvars .= '&type=video';
		}
		$jw_flashvars .= '&config='. urlencode(_URL ."/jwembed.xml");
		
		// object params
		$embed_code .= '<param name="movie" value="'. _URL .'/jwplayer.swf" />';
		$embed_code .= '<param name="flashVars" value="'. $jw_flashvars .'" />';
		
		// embed tag
		$embed_code .= '<embed src="'. _URL .'/jwplayer.swf" ';
		$embed_code .= ' width="'. _PLAYER_W_EMBED .'" height="'. _PLAYER_H_EMBED . '"';
		$embed_code .= ' scale="noscale" bgcolor="'. _BGCOLOR .'"';
		$embed_code .= ' type="application/x-shockwave-flash" allowFullScreen="true" ';
		$embed_code .= ' allowScriptAccess="always" wmode="window" ';
		$embed_code .= ' flashvars="'. $jw_flashvars .'">';
		$embed_code .= '</embed>';
		$embed_code .= '</object>';
	}
	else
	{
		// overwrite
		$embed_code = $video['embed_code'];	
	}

	$backlink = '<p style="margin:3px 0px;"><a href="'. makevideolink($video['uniq_id'], $video['artist'], $video['video_title']) .'" target="_blank">';
	$backlink .= $video['artist'] .' - '. $video['video_title'];
	$backlink .= '</a></p>';
	
	$embed_code = str_replace( array("\n", "\r", "\t"), '', $embed_code);
	$embed_code .= $backlink;
	
	return $embed_code;
}

function make_voth() {

	global $config;
	
	$video_id = '';
	
	$sql = "SELECT uniq_id 
			FROM pm_videos 
			WHERE featured = '1' 
			ORDER BY rand() 
			LIMIT 1";
	$result =  @mysql_query($sql);
	
	if (@mysql_num_rows($result) == 0)
	{
		$sql = "SELECT uniq_id 
				FROM pm_videos 
				ORDER BY rand() 
				LIMIT 1";
		
		$result = @mysql_query($sql);
		$row 	= @mysql_fetch_assoc($result);
		$video_id = $row['uniq_id'];
		mysql_free_result($result);
	}
	else
	{
		$row = mysql_fetch_assoc($result);
		mysql_free_result($result);
		
		$video_id = $row['uniq_id'];
	}
	
	return $video_id;
}
function show_more_featured($mvotd = '', $limit = 3) {
	//	todo
}
function show_voth_title() {	
	//	@deprecated
}

function return_bytes($val) 
{
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    switch($last) {
    	default: 
			$val = (int) $val;
		break;
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }
    return $val;
}

function readable_filesize($bytes)
{
	$filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
	return $bytes ? round($bytes/pow(1024, ($i = floor(log($bytes, 1024)))), 2) . $filesizename[$i] : '0 Bytes';
}

function today() {
	$thour=date('H');
	$tmin=date('i');
	$tsec=date('s');
	$tmonth=date('n');
	$tday=date('d');
	$tyear=date('Y');
	//convert it to unix timestamp
	$today=mktime($thour,$tmin,$tsec,$tmonth,$tday,$tyear);
	return $today;
}
function ezDate($d) {
	
		global $lang;
	$ts = time() - strtotime(str_replace("-","/",$d));
	
	if($ts > 31536000) 
	{
		$val = round($ts/31536000,0);
		$span = ($val == 1) ? 'year' : 'years';
	}
	elseif($ts > 2419200)
	{
		$val = round($ts/2419200,0);
		$span = ($val == 1) ? 'month' : 'months';
	}
	elseif($ts > 604800) 
	{
		$val = round($ts/604800,0);
		$span = ($val == 1) ? 'week' : 'weeks';
	}
	elseif($ts > 86400)
	{
		$val = round($ts/86400,0);
		$span = ($val == 1) ? 'day' : 'days';
	}
	elseif($ts > 3600)
	{
		$val = round($ts/3600,0);
		$span = ($val == 1) ? 'hour' : 'hours';
	}
	elseif($ts > 60)
	{
		$val = round($ts/60,0).' '.$lang['minute'];
		$span = ($val == 1) ? 'minute' : 'minutes';
	}
	else 
	{
		$val = $ts;
		$span = ($val == 1) ? 'second' : 'seconds';
	}
	$val .= ' '.$lang[$span];

	return $val;
}
function time_since($original) {
	global $lang;
    // array of time period chunks
    $chunks = array(
        array(60 * 60 * 24 * 365 , $lang['year']),
        array(60 * 60 * 24 * 30 , $lang['month']),
        array(60 * 60 * 24 * 7, $lang['week']),
        array(60 * 60 * 24 , $lang['day']),
        array(60 * 60 , $lang['hour']),
        array(60 , $lang['minute']),
    );
    $chunks2 = array(
		$lang['years'],
		$lang['months'],
		$lang['weeks'],
		$lang['days'],
		$lang['hours'],
		$lang['minutes']
	);
	
    $today = time(); /* Current unix time  */
    $since = $today - $original;
    
    // $j saves performing the count function each time around the loop
    for ($i = 0, $j = count($chunks); $i < $j; $i++) {
       
        $seconds = $chunks[$i][0];
        $name = $chunks[$i][1];
        $type = $chunks2[$i];
        // finding the biggest chunk (if the chunk fits, break)
        if (($count = floor($since / $seconds)) != 0) {
            break;
        }
    }

    $print = ($count == 1) ? '1 '.$name : $count." ".$type;
    
    if ($i + 1 < $j) {
        // now getting the second item
        $seconds2 = $chunks[$i + 1][0];
        $name2 = $chunks[$i + 1][1];
		$type2 = $chunks2[$i + 1];
		
        // add second item if it's greater than 0
        if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
             $print .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 ".$type2;
        }
    }
	
    return $print;
}
function sec2min($sec) 
{
    $minutes = intval(($sec / 60) % 60); 
    $seconds = intval($sec % 60); 
	$time = $minutes." min. ".$seconds." sec.";
    return $time;
}
function is_real_email_address($email){
	$regex = "/^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i";
	if( ! @preg_match($regex, $email))
		return 0;	// not valid
	return 1;	// valid
}
function count_entries($table, $field, $field_equal) { // Usage 1 = table name 2 = field to search 3 = what to match

	if(!empty($field) && isset($field_equal)) {
	$query = @mysql_query("SELECT COUNT(*) as total FROM $table WHERE $field = '".$field_equal."'");
	} else {
	$query = @mysql_query("SELECT COUNT(*) as total FROM $table");
	}
	$result = @mysql_fetch_assoc($query);
	
	return $result['total'];
}

function send_a_mail($var_array, $destinationmail, $mailsubject, $template, $special_sender = '') {
	
	global $config;
	
	$mail = new PHPMailer();
	$mail->SetLanguage("en", "include/");
	if (_ISSMTP == 1) 
	{
		$mail->IsSMTP();
	}
	if ($config['mail_server'] != '')
	{
		$mail->Host 	= $config['mail_server'];
		$mail->SMTPAuth = true;
		$mail->Port 	= $config['mail_port'];
		$mail->Username = $config['mail_user'];
		$mail->Password = $config['mail_pass'];
		$mail->From 	= ('' != $special_sender) ? $special_sender : $config['contact_mail'];
		$mail->FromName = ('' != $special_sender) ? $special_sender : html_entity_decode(_SITENAME, ENT_QUOTES);
	}
	else if (defined('_MAIL_HOST'))
	{
		$mail->Host 	= _MAIL_HOST; 
		$mail->SMTPAuth = true;
		$mail->Port 	= _MAIL_PORT;
		$mail->Username = _MAIL_USER;
		$mail->Password = _MAIL_PASS;
		$mail->FromName = _MAIL_FROM_NAME;
		$mail->From 	= ('' != $special_sender) ? $special_sender : _MAIL_FROM;
	}
	$mail->CharSet = "UTF-8";
	$mail->AddAddress($destinationmail); 
	$mail->IsHTML(true); 
	$mail->Subject = $mailsubject;
	
	// insert template 
	$filename = $template;
	$fd = fopen ($filename, "r");
	$mailcontent = fread ($fd, filesize ($filename));
	
	foreach ($var_array as $key=>$value)
	{
		$mailcontent = str_replace("%%$value[0]%%", $value[1],$mailcontent );
	}
	$mailcontent = stripslashes($mailcontent);
	fclose ($fd);
							
	$mail->Body=$mailcontent;
	if ( ! $mail->Send())
	{
		$result = $mail->ErrorInfo;
	}
	else 
	{
		$result = TRUE;
	}

	return $result;
}
// ** FOR REGISTRATION ** //
function prepare_for_mysql($value){
	return htmlspecialchars(magicSlashes(trim($value)));
}

function validate_email($email) {
	
	global $conn_id;
	
	if( empty($conn_id) ) {
		$conn_id = db_connect();
	}
	$rows = 0;
	if( !is_real_email_address($email))
		return 1;	// invalid characters;

	$sql = "SELECT email FROM pm_users WHERE email = '" . str_replace("\'", "''", $email) . "'";
	$result = @mysql_query($sql, $conn_id);
	if(!$result) { 
		return false;
	}
	$rows = @mysql_num_rows($result); 
	@mysql_free_result($result);
	if($rows > 0) 
		return 2;	// already in use
return false;
}
 
function check_username($username) {
	/*
	  this function checks the validity of $username. 
	  	1.	checks if the string is at least 3 characters long
	  	2.	checks if it is alpha-numeric
	  	3.	checks if it already exists in DB
	 -> Returns False if the $username is OK
	*/  
	global $conn_id;
	if( empty($conn_id) ) {
		$conn_id =  db_connect();
	}
	$username = magicSlashes(trim($username));
	$rows = 0;
	if(strlen(stripslashes($username)) < 3)
	 	return 1; // too short or empty
		
	$alpha_num = str_replace(" ", "", $username);
	if( !ctype_alnum($alpha_num))
		return 2; // invalid characters -> non-alpha-numeric
	
	$sql = "SELECT username FROM pm_users WHERE LOWER(username) = '".htmlspecialchars(strtolower($username))."'";
	$result = @mysql_query($sql, $conn_id);
	if(!$result) { 
	  	return false;
	}
	$rows = @mysql_num_rows($result);
	@mysql_free_result($result);
	if($rows > 0)
		return 3; // already in use
return false;	
}
// ** END FOR REGISTRATION ** //
function word_wrap_pass($message)
{
	$wrapAt = 45;
	$tempText = '';
	$finalText = '';
	$curCount = $tempCount = 0;
	$longestAmp = 9;
	$inTag = false;
	$ampText = '';
	$len = strlen($message);

	for ($num=0;$num<$len;$num++)
	{
		$curChar = $message{$num};

		if ($curChar == '<')
		{
			for ($snum=0;$snum<strlen($ampText);$snum++)
			{
				addWrap($ampText{$snum},$ampText{$snum+1},$wrapAt,$finalText,$tempText,$curCount,$tempCount);
			}
			$ampText = '';
			$tempText .= '<';
			$inTag = true;
		}
		elseif ($inTag && $curChar == '>')
		{
			$tempText .= '>';
			$inTag = false;
		}
		elseif ($inTag)
		{
			$tempText .= $curChar;
		}
		elseif ($curChar == '&')
		{
			for ($snum=0;$snum<strlen($ampText);$snum++)
			{
				addWrap($ampText{$snum},$ampText{$snum+1},$wrapAt,$finalText,$tempText,$curCount,$tempCount);
			}
			$ampText = '&';
		}
		elseif (strlen($ampText) < $longestAmp && $curChar == ';' && function_exists('html_entity_decode') &&
		       (strlen(html_entity_decode("$ampText;")) == 1 || preg_match('/^&#[0-9]+$/',$ampText)))
		{
			addWrap($ampText.';',$message{$num+1},$wrapAt,$finalText,$tempText,$curCount,$tempCount);
			$ampText = '';
		}
		elseif (strlen($ampText) >= $longestAmp || $curChar == ';')
		{
			for ($snum=0;$snum<strlen($ampText);$snum++)
			{
				addWrap($ampText{$snum},$ampText{$snum+1},$wrapAt,$finalText,$tempText,$curCount,$tempCount);
			}
			addWrap($curChar,$message{$num+1},$wrapAt,$finalText,$tempText,$curCount,$tempCount);
			$ampText = '';
		}
		elseif (strlen($ampText) != 0 && strlen($ampText) < $longestAmp)
		{
			$ampText .= $curChar;
		}
		else
		{
			addWrap($curChar,$message{$num+1},$wrapAt,$finalText,$tempText,$curCount,$tempCount);
		}
	}

	return $finalText . $tempText;
}

function addWrap($curChar,$nextChar,$maxChars,&$finalText,&$tempText,&$curCount,&$tempCount) {
	$wrapProhibitedChars = "([{!;,\\/:?}])";

	if ($curChar == ' ' || $curChar == "\n")
	{
		$finalText .= $tempText . $curChar;
		$tempText = '';
		$curCount = 0;
		$curChar = '';
	}
	elseif ($curCount >= $maxChars)
	{
		$finalText .= $tempText . ' ';
		$tempText = '';
		$curCount = 1;
	}
	else
	{
		$tempText .= $curChar;
		$curCount++;
	}

	// the following code takes care of (unicode) characters prohibiting non-mandatory breaks directly before them.

	// $curChar isn't a " " or "\n"
	if ($tempText != '' && $curChar != '')
	{
		$tempCount++;
	}
	// $curChar is " " or "\n", but $nextChar prohibits wrapping.
	elseif ( ($curCount == 1 && strstr($wrapProhibitedChars,$curChar) !== false) || 
	         ($curCount == 0 && $nextChar != '' && $nextChar != ' ' && $nextChar != "\n" && strstr($wrapProhibitedChars,$nextChar) !== false))
	{
		$tempCount++;
	}
	// $curChar and $nextChar aren't both either " " or "\n"
	elseif (!($curCount == 0 && ($nextChar == ' ' || $nextChar == "\n")))
	{
		$tempCount = 0;
	}

	if ($tempCount >= $maxChars && $tempText == '')
	{
		$finalText .= '&nbsp;';
		$tempCount = 1;
		$curCount = 2;
	}

	if ($tempText == ''  && $curCount > 0)
	{
		$finalText .= $curChar;
	}
}

function search_bad_words($input) {
	
	$filtered_input = $input;
	
	$phrases = explode("\r\n", file_get_contents('blacklist.txt'));
	
	if (count($phrases) > 0)
	{
		foreach ($phrases as $k => $phrase)
		{
			$filtered_input = str_ireplace($phrase, '', $filtered_input);
		}
	}

	return $filtered_input;
}
	

function RemoveCurseWords($original) 
{
	$patterns = explode("\r\n",file_get_contents("censor_words.txt"));
	$finalremove = $original;
	$piece_front = "";
	$piece_back = "";
	$piece_replace = "***";

    for ($x = 0; $x < count($patterns); $x++) 
	{
    	$safety=0; 
        while (@strstr(strtolower($finalremove), strtolower($patterns[$x]))) 
		{
	        $safety = $safety + 1;
	        if ($safety >= 100) { break; }
	
	        $occ = strpos(strtolower($finalremove), strtolower($patterns[$x]));
	        $piece_front = substr($finalremove, 0, $occ);
	        $piece_back = substr($finalremove, ($occ + strlen($patterns[$x])));
	        $finalremove = $piece_front . $piece_replace . $piece_back;
        }
    }
	return $finalremove;
}
$allowedTags = '<b><i><br>';
$stripAttrib = 'javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|'.
				'onblur|onchange|onfocus|onload|onsubmit|style|font|'.
               'onmousemove|onmouseout|onkeypress|onkeydown|onkeyup|object|object';
function removeEvilAttributes($tagSource)
{
   global $stripAttrib;
   return stripslashes(preg_replace("/$stripAttrib/i", 'forbidden', $tagSource));
}
function removeEvilTags($source)
{
   global $allowedTags;
   $source = RemoveCurseWords(strip_tags($source, $allowedTags));
   return preg_replace('/<(.*?)>/ie', "'<'.removeEvilAttributes('\\1').'>'", $source);
}

function show_comments($vid, $user_power, $page = 1) {

	global $template_f, $config, $lang;
	
	$sql	= '';
	$row 	= array();
	$from	= 0;
	$limit	= 10;
	$output	= '';
	$total_comments = 0;
	$comments  = array();
	$adjacents = 1;
	
	$vid 	= secure_sql($vid);
	$page = (int) $page;
	
	if (empty($page))
	{
		$page = 1;
	}
	
	$limit = $config['comments_page'];	//	comments per page
	$from  = $page * $limit - ($limit);
	
	$sql  = "SELECT COUNT(*) as total_comments 
			FROM pm_comments 
			WHERE uniq_id = '". $vid ."' 
			  AND approved = '1'";
	
	$result = mysql_query($sql);
	if ( ! $result)
	{
		return 'empty';
	}
	$row = mysql_fetch_assoc($result);
	$total_comments = $row['total_comments'];
	
	mysql_free_result($result);
	
	$sql = "SELECT * 
			FROM pm_comments 
			WHERE uniq_id = '". $vid ."' 
			  AND approved = '1' 
			ORDER BY added DESC 
			LIMIT ". $from .", ". $limit;
	
	$result = mysql_query($sql);
	if ( ! $result)
	{
		return 'empty';
	}
	
	if (mysql_num_rows($result) > 0) 
	{
		while ($row = mysql_fetch_array($result)) 
		{
			$comments[] = $row;
		}
		mysql_free_result($result);
		
		$inc_id = 0;
		foreach ($comments as $key => $comment)
		{
			$i 	  = 1;
			$k 	  = 1;
			$user 	= array();
			$banned = array();
			$avatar_url = '';
			
			if ($comment['user_id'] == 0)
			{
				$avatar_url = _URL .'/'. _UPFOLDER .'/avatars/no_avatar.gif';
			}
			else
			{
				$sql = "SELECT id, gender, avatar, power  
						FROM pm_users 
						WHERE username = '".secure_sql($comment['username'])."'";
				$result = @mysql_query($sql);
				if ( ! $result)
				{
					$avatar_url = _URL .'/'. _UPFOLDER .'/avatars/no_avatar.gif';
				}
				else
				{
					$user = mysql_fetch_assoc($result);
					mysql_free_result($result);
					
					if (empty($user['avatar']) || $user['avatar'] == 'no_avatar.gif')
					{
						$avatar_url = _URL .'/'. _UPFOLDER .'/avatars/'. $user['gender'] .'.gif';
					}
					else
					{
						$avatar_url = _URL .'/'. _UPFOLDER .'/avatars/'. $user['avatar'];
					}
				}
				
				$banned = banlist($comment['user_id']);
				
			}	//	end if comment[user_id] == 0
			
			
			$inc_id++;
			$output .= '<li id="comment-'. $inc_id .'">';
			$output .= "\r\n";
			$output	.= '<div class="comment-head">';
			$output .= '<img src="'. $avatar_url .'" alt="'. $comment['username'] .'" border="0" width="48" height="48" class="avatar_img" />';
			$output .= "\r\n";
			
			if($comment['user_id'] == 0)
			{
				$output .= '<div class="comment-author">'. $comment['username'] .'</div>';
			}
			else
			{
				$output .= '<div class="comment-author"><a href="'. _URL .'/profile.'. _FEXT .'?u='. $comment['username'] .'"';
				$output .= 'rel="nofollow">';
				
				if($banned['user_id'] == $comment['user_id'])
				{
					$output .= '<del>'. $comment['username'] .'</del>';
				}
				else
				{
					$output .= $comment['username'];
				}
				
				$output .= '</a></div>';
			}
			$output .= '<div class="comment-date">'. time_since($comment['added']) .' '. $lang['ago'] .'</div>';
			$output .= "</div><br />\r\n";
			$output .= $comment['comment'];
			
			$mod_can = mod_can();
			
			if($user_power == U_ADMIN || ($user_power == U_MODERATOR && $mod_can['manage_comments']))
			{
				$output .= '<div class="row_actions">';
				
				$output .= '<span id="users-'. $inc_id .'">';
				
				if($comment['user_id'] > 0 && $user['power'] != U_ADMIN && $user_power != $comment['user_id'])
				{
					if($user_power == U_MODERATOR && !$mod_can['manage_users'])
					{
						$output .= '';
					}
					else if($banned['user_id'] == $comment['user_id'])
					{
						$output .= '<a href="#" onclick="ajax_request(\'users\', \'&do=allow&uid='. $comment['user_id'] .'\', \'#users-'. $inc_id .'\', \'html\', true); return false;"';
						$output .= ' class="ban_user" title="Remove user ban">Remove ban</a>';
					}
					else
					{
						$output .= '<a href="#" onclick="ajax_request(\'users\', \'&do=ban&uid='. $comment['user_id'] .'\', \'#users-'. $inc_id .'\', \'\', true); return false;"';
						$output .= ' class="ban_user" title="Ban this user">Ban user</a>';
					}
				}
				else
				{
					$output .= '<span class="ipaddress">IP: '. $comment['user_ip'] .'</span>'; 
				}
				$output .= '</span>'; //	end span id="users-N"
				$output .= ' ';
				
				$output .= '<a href="#" onclick="onpage_delete_comment(\''. $comment['id'] .'\', ';
				$output .= '\''. $comment['uniq_id'] .'\', \'#comment-'. $inc_id .'\'); return false;" ';
				$output .= ' class="delete_comment" id="comment-'. $inc_id .'" title="Delete this comment">Delete</a>';
				$output .= '</div>';	
				
			}
			
			$output .= "\r\n";
			$output .= '</li>';
			$output .= "\r\n";
		}	//	end foreach
		
		/*	Pagination START	*/
		if ($total_comments > $limit)
		{
			
			$output .= '<br />';

			$pagination = '';
			$counter 	= 0;
			$prev 	 	= $page - 1;
			$next 	 	= $page + 1;
			$lastpage	= ceil($total_comments / $limit);
			$lpm1 	 	= $lastpage - 1;
			
			$pagination .= '<div class="pagination">';
			$pagination .= "\r\n";
			//	Previous button
			if ($page > 1)
			{
				$pagination .= '<a href="#" onclick="ajax_request(\'comments\', \'&do=show_comments&page='. $prev .'&vid='. $comment['uniq_id'] .'\', \'#comments_ol\', \'html\', true); return false;">&laquo; '. $lang['prev'] .'</a>';
			}
			else
			{
				$pagination .= '<span class="disabled">&laquo; '. $lang['prev'] .'</span>';
			}
			
			if ($lastpage < 7 + ($adjacents * 2))	//not enough pages to bother breaking it up
			{	
				for ($counter = 1; $counter <= $lastpage; $counter++)
				{
					if ($counter == $page)
					{
						$pagination .= '<span class="current">'. $counter .'</span>';
					}
					else
					{
						$pagination .= '<a href="#" onclick="ajax_request(\'comments\', \'do=show_comments&page='. $counter .'&vid='. $comment['uniq_id'] .'\', \'#comments_ol\', \'html\', true); return false;">'. $counter .'</a>';
					}
				}

			}
			elseif($lastpage >= 7 + ($adjacents * 2))
			{
				//close to beginning; only hide later pages
				if($page < 2 + ($adjacents * 3))		
				{
					for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
					{
						if ($counter == $page)
						{
							$pagination .= '<span class="current">'. $counter .'</span>';
						}
						else
						{
							$pagination .= '<a href="#" onclick="ajax_request(\'comments\', \'do=show_comments&page='. $counter .'&vid='. $comment['uniq_id'] .'\', \'#comments_ol\', \'html\', true); return false;">'. $counter .'</a>';
						}
					}
					$pagination .= '...';
					$pagination .= '<a href="#" onclick="ajax_request(\'comments\', \'do=show_comments&page='. $lpm1 .'&vid='. $comment['uniq_id'] .'\', \'#comments_ol\', \'html\', true); return false;">'. $lpm1 .'</a>';
					$pagination .= '<a href="#" onclick="ajax_request(\'comments\', \'do=show_comments&page='. $lastpage .'&vid='. $comment['uniq_id'] .'\', \'#comments_ol\', \'html\', true); return false;">'. $lastpage .'</a>';
				}

				// in middle; hide some front and some back
				elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
				{
					$pagination .= '<a href="#" onclick="ajax_request(\'comments\', \'do=show_comments&page=1&vid='. $comment['uniq_id'] .'\', \'#comments_ol\', \'html\', true); return false;">1</a>';
					$pagination .= '<a href="#" onclick="ajax_request(\'comments\', \'do=show_comments&page=2&vid='. $comment['uniq_id'] .'\', \'#comments_ol\', \'html\', true); return false;">2</a>';
					$pagination .= '...';
					for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
					{
						if ($counter == $page)
						{
							$pagination .= '<span class="current">'. $counter .'</span>';
						}
						else
						{
							$pagination .= '<a href="#" onclick="ajax_request(\'comments\', \'do=show_comments&page='. $counter .'&vid='. $comment['uniq_id'] .'\', \'#comments_ol\', \'html\', true); return false;">'. $counter .'</a>';
						}
					}
					$pagination .= '...';
					$pagination .= '<a href="#" onclick="ajax_request(\'comments\', \'do=show_comments&page='. $lpm1 .'&vid='. $comment['uniq_id'] .'\', \'#comments_ol\', \'html\', true); return false;">'. $lpm1 .'</a>';
					$pagination .= '<a href="#" onclick="ajax_request(\'comments\', \'do=show_comments&page='. $lastpage .'&vid='. $comment['uniq_id'] .'\', \'#comments_ol\', \'html\', true); return false;">'. $lastpage .'</a>';
				}
				//close to end; only hide early pages
				else
				{
					$pagination .= '<a href="#" onclick="ajax_request(\'comments\', \'do=show_comments&page=1&vid='. $comment['uniq_id'] .'\', \'#comments_ol\', \'html\', true); return false;">1</a>';
					$pagination .= '<a href="#" onclick="ajax_request(\'comments\', \'do=show_comments&page=2&vid='. $comment['uniq_id'] .'\', \'#comments_ol\', \'html\', true); return false;">2</a>';
					$pagination .= '...';
					for ($counter = $lastpage - (1 + ($adjacents * 3)); $counter <= $lastpage; $counter++)
					{
						if ($counter == $page)
						{
							$pagination .= '<span class="current">'. $counter .'</span>';
						}
						else
						{
							$pagination .= '<a href="#" onclick="ajax_request(\'comments\', \'do=show_comments&page='. $counter .'&vid='. $comment['uniq_id'] .'\', \'#comments_ol\', \'html\', true); return false;">'. $counter .'</a>';
						}
					}
				}
			}

			//next button
			if ($page < $counter - 1) 
			{
				$pagination .= '<a href="#" onclick="ajax_request(\'comments\', \'do=show_comments&page='. $next .'&vid='. $comment['uniq_id'] .'\', \'#comments_ol\', \'html\', true); return false;">'. $lang['next'] .' &raquo;</a>';
			}
			else
			{
				$pagination .= '<span class="disabled">'. $lang['next'] .' &raquo;</span>';
			}
			$pagination .= '</div>';
			
			$output .= "\r\n";
			$output .= $pagination;
			$output .= "\r\n";
		}
		/*	Pagination END	*/
	} 
	else
	{
		$output = 'empty';
	}
	
	return $output;
}

function countryid2name($id) {
	$query = mysql_query("SELECT * FROM pm_countries WHERE countryid = '".$id."'");
	$result = mysql_fetch_array($query);
	return $result['country'];
}
function make_cats($cat_ids) {
	
	$categories = load_categories(array('db_table' => 'pm_categories'));
	
	$selected = explode(',', $cat_ids);
	
	foreach ($selected as $k => $v)
	{
		$selected[$k] = (int) $v;
	}
	
	$links = '';
	
	foreach ($categories as $c_id => $c)
	{
		if (in_array($c_id, $selected))
		{
			if(_SEOMOD == 1)
			{
				$links .= "<a href=\""._URL."/browse-".$c['tag']."-videos-1-date.html\">".$c['name']."</a> ";
			}
			else
			{
				$links .= "<a href=\""._URL."/category.php?cat=".$c['tag']."\">".$c['name']."</a> ";
			}
		}
	}

	return $links;
}

function show_thumb($uniq_id, $t_id = 1)
{
	if(_THUMB_FROM == 1) 	//	Outsource
	{
		$q = mysql_query("SELECT yt_id, yt_thumb, source_id FROM pm_videos WHERE uniq_id = '".$uniq_id."'");
		$r = mysql_fetch_array($q);
		
		if(($r['source_id'] == 1) || ($r['yt_thumb'] != '' && strstr($r['yt_thumb'], "http://") === false))	//	thumbnail is hosted locally
		{
			if($r['source_id'] == 1 && $r['yt_thumb'] == '')
			{
				//	default thumbnail
				$thumb_url = _NOTHUMB;
			}
			elseif($r['yt_thumb'] != '' && strstr($r['yt_thumb'], "http://") === false)
			{
				if(!file_exists(_THUMBS_DIR_PATH . $r['yt_thumb']))
				{
					$thumb_url = _NOTHUMB;
				}
				else
				{
					$thumb_url = _THUMBS_DIR . $r['yt_thumb'];
				}
			}
			else
			{
				$thumb_url = $r['yt_thumb'];
			}
		}
		else
		{
			if($r['yt_thumb'] == '')
			{
				if($r['source_id'] == 3)
				{
					//	fix for videos imported in older versions using remote thumbails
					$thumb_url =  _YOUTUBETHUB."/".$r['yt_id']."/default.jpg";
				}
				else
				{
					$thumb_url = _NOTHUMB;
				}
			}
			else
			{
				$thumb_url = $r['yt_thumb'];
			}
		}
	}
	else 	//	Localhost
	{
		if(!file_exists(_THUMBS_DIR_PATH . $uniq_id . "-" . $t_id . ".jpg"))
		{
			$thumb_url = _NOTHUMB;
		}
		else
		{
			$thumb_url = _THUMBS_DIR . $uniq_id . "-" . $t_id . ".jpg";
		}
	}
	return $thumb_url;
}

function check_template($name) {
	// CHECK IF FOLDER EXISTS
	$template_dir = ABSPATH . "/templates/".$name;
	
	if(is_dir($template_dir)) {
	// CHECK FOR FILES
		$index = $template_dir."/index.tpl";
		$detail = $template_dir."/detail.tpl";
		$browse = $template_dir."/browse.tpl";
		if(file_exists($index) && file_exists($detail) && file_exists($browse)) {
		return TRUE;		
		}
		else { 
		return FALSE;
		}
	} elseif(!is_dir($template_dir)) {
	return FALSE;
	}	
}
function dropdown_templates() {

$path = ABSPATH ."/templates";
$dh = opendir($path);
$form_file = '';
while (($file = readdir($dh)) !== false) {
    if($file != "." && $file != "..") {
		
		if(check_template($file)) {
		$form_file .= "<option value=\"".$file."\">".$file."</option> \n";
		}
    }
}
closedir($dh);
return $form_file;
}
function secure_sql( $value )
	{
	if( get_magic_quotes_gpc() )
	{
	$value = stripslashes( $value );
	}
	if( function_exists( "mysql_real_escape_string" ) )
	{
	$value = mysql_real_escape_string( $value );
	}
	else
	{
	$value = addslashes( $value );
	}
	return $value;
}

function specialchars( $text, $and_quotes = 0 ) {

   if( $and_quotes == 1 || $and_quotes === true )
   {
      $text = str_replace('"', '&quot;', $text);
      $text = str_replace("'", '&#039', $text);
   }
   $text = str_replace('<', '&lt;', $text);
   $text = str_replace('>', '&gt;', $text);
   return $text;
}

function makevideolink($uniq_id, $artist = '', $video_title = '')
{
	$r = array();
	
	if (_SEOMOD == 1) 
	{
		if ('' != $artist && '' != $video_title)
		{
			$r['artist'] = $artist;
			$r['video_title'] = $video_title;
		}
		else
		{
			$query 	= @mysql_query("SELECT artist, video_title FROM pm_videos WHERE uniq_id = '".$uniq_id."'");
			$r 		= mysql_fetch_array($query);
			mysql_free_result($query);
		}
		$artist = sanitize_title($r['artist']);
		//$artist = safename($artist); // @since 1.6.5
		$song 	= sanitize_title($r['video_title']);
		//$song 	= safename($song);	// @since 1.6.5
		
		$return = _URL .'/'. $artist .'/'. $song .'-video_'. $uniq_id .'.html';
	} 
	else 
	{
		$return = _URL .'/musicvideo.php?vid='.$uniq_id;
	}
	
	return $return;
}

// GET THE DOMAIN NAME
function get_dn($url) { 
	preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
	$host = $matches[1];
	// get last two segments of host name
	preg_match('/[^.]+\.[^.]+$/', $host, $matches);
	return $matches[0];
}

function retrieve_vid($url) {
	// establish the source: Youtube
	$source = get_dn($url);
	
	if($source == 'youtube.com') {
		$url = parse_url($url);
		$url = $url['query'];
		$url = explode('&', $url, 2);
		$vid = substr($url[0], 2);
	}

	return $vid;
}
function islive($timestamp) {
	$second = 1;
	$minute = $second*60;
	$time = time();
	$difference = $time-$timestamp;
	$mcount = 0;
	for($mcount = 0; $difference>$minute;
	$mcount++) {
	$difference = $difference - $minute;
	}
	if($mcount >= 3) 
	return TRUE;
	else
	return FALSE;
}
function videosplaying($limit = 4) { // SHOW THE CURRENTLY PLAYING VIDEOS
	$time_diff = time();
	$time_diff -= (3 * 60);
	$query = mysql_query("SELECT * FROM pm_videos WHERE lastwatched > ".$time_diff." ORDER BY lastwatched DESC LIMIT $limit");
	$countresults = mysql_num_rows($query);
	$results = '';
	while($row = mysql_fetch_array($query)) {
		$results .= "
		<li class=\"item\">
		<a href=\"".makevideolink($row['uniq_id'], $row['artist']. $row['video_title'])."\"><img src=\"".show_thumb($row['uniq_id'])."\" alt=\"".$row['video_title']."\" class=\"imag\" width=\"85\" height=\"63\" border=\"1\" /></a>
		<br />
		<a href=\"".makevideolink($row['uniq_id'], $row['artist']. $row['video_title'])."\" title=\"".$row['video_title']."\">".fewchars($row['video_title'], 20)."</a>
		</li>";
	}
	if($countresults == 1)
	{
		$results .= "<li></li>";
	}
	if($countresults >= 1)
	return $results;
	else
	return 0;
}
function generate_smart_pagination($page = 1, $totalitems, $limit = 15, $adjacents = 1, $targetpage = "/", $pagestring = "&page=", $seomod = 0)
{
	global $lang;
	
	if(!$adjacents) $adjacents = 1;
	if(!$limit) $limit = 15;
	if(!$page) $page = 1;
	if(!$targetpage) $targetpage = "/";
	
	$prev = $page - 1;
	$next = $page + 1;
	$lastpage = ceil($totalitems / $limit);
	$lpm1 = $lastpage - 1;
	//	this function will replace the existing "page=N" with it's own page number when building the links
	//	so let's check if there is any "page=" in the original $pagestring. If non found, add one to help things out
	if($seomod == 1)
	{
		$pagestring1 = preg_replace('/browse-(.*?)-videos-([0-9]*)-/', 'browse-$1-videos-1-', $targetpage);
		$pagestring2 = preg_replace('/browse-(.*?)-videos-([0-9]*)-/', 'browse-$1-videos-2-', $targetpage);
		$pagestringlpm1 = preg_replace('/browse-(.*?)-videos-([0-9]*)-/', 'browse-$1-videos-'.$lpm1.'-', $targetpage);
		$pagestringlast = preg_replace('/browse-(.*?)-videos-([0-9]*)-/', 'browse-$1-videos-'.$lastpage.'-', $targetpage);	
	}
	else
	{
		if(strpos($pagestring, 'page=', 0) === FALSE)
			$pagestring .= "&page=";
		
		$pagestring1 = preg_replace('/page=([0-9]*)/', 'page=1', $pagestring);
		$pagestring2 = preg_replace('/page=([0-9]*)/', 'page=2', $pagestring);
		$pagestringlpm1 = preg_replace('/page=([0-9]*)/', 'page='.$lpm1, $pagestring);
		$pagestringlast = preg_replace('/page=([0-9]*)/', 'page='.$lastpage, $pagestring);
	}	
		$pagination = "";
		if($lastpage > 1)
		{	
			$pagination .= "<div class=\"pagination\"";
			if($margin || $padding)
			{
				$pagination .= " style=\"";
				if($margin)
					$pagination .= "margin: $margin;";
				if($padding)
					$pagination .= "padding: $padding;";
				$pagination .= "\"";
			}
			$pagination .= ">";
	
			//previous button
			if ($page > 1)
			{
				if($seomod == 1)
				{
					$url_query = preg_replace('/browse-(.*?)-videos-([0-9]*)-/', 'browse-$1-videos-'.$prev.'-', $targetpage);
					$pagination .= "<a href=\"$url_query\">&laquo; ".$lang['prev']."</a>";
				}
				else
				{
					$url_query = preg_replace('/page=([0-9]*)/', 'page='.$prev, $pagestring);
					$pagination .= "<a href=\"$targetpage?$url_query\">&laquo; ".$lang['prev']."</a>";
				}
			}
			else
					$pagination .= "<span class=\"disabled\">&laquo; ".$lang['prev']."</span>";
			
			//pages	
			if ($lastpage < 7 + ($adjacents * 2))	//not enough pages to bother breaking it up
			{	
				for ($counter = 1; $counter <= $lastpage; $counter++)
				{
					if ($counter == $page)
						$pagination .= "<span class=\"current\">$counter</span>";
					else
					{
						if($seomod == 1)
						{
							$url_query = preg_replace('/browse-(.*?)-videos-([0-9]*)-/', 'browse-$1-videos-'.$counter.'-', $targetpage); 
							$pagination .= "<a href=\"$url_query\">$counter</a>";
						}
						else
						{
							$url_query = preg_replace('/page=([0-9]*)/', 'page='.$counter, $pagestring);
							$pagination .= "<a href=\"$targetpage?$url_query\">$counter</a>";
						}
					}					
				}
			}
			elseif($lastpage >= 7 + ($adjacents * 2))	//enough pages to hide some
			{
				//close to beginning; only hide later pages
				if($page < 2 + ($adjacents * 3))		
				{
					for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
					{
						if ($counter == $page)
							$pagination .= "<span class=\"current\">$counter</span>";
						else
						{
							if($seomod == 1)
							{
								$url_query = preg_replace('/browse-(.*?)-videos-([0-9]*)-/', 'browse-$1-videos-'.$counter.'-', $targetpage); 
								$pagination .= "<a href=\"$url_query\">$counter</a>";
							}
							else
							{
								$url_query = preg_replace('/page=([0-9]*)/', 'page='.$counter, $pagestring);
								$pagination .= "<a href=\"$targetpage?$url_query\">$counter</a>";
							}
//							$url_query = preg_replace('/page=([0-9]*)/', 'page='.$counter, $pagestring);
//							$pagination .= "<a href=\"$targetpage?$url_query\">$counter</a>";	
						}				
					}
					$pagination .= "...";
					if($seomod == 1)
					{					
						$pagination .= "<a href=\"$pagestringlpm1\">$lpm1</a>";
						$pagination .= "<a href=\"$pagestringlast\">$lastpage</a>";		
					}
					else
					{
						$pagination .= "<a href=\"$targetpage?$pagestringlpm1\">$lpm1</a>";
						$pagination .= "<a href=\"$targetpage?$pagestringlast\">$lastpage</a>";		
					}
				}
				//in middle; hide some front and some back
				elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
				{
					if($seomod == 1)
					{					
						$pagination .= "<a href=\"$pagestring1\">1</a>";
						$pagination .= "<a href=\"$pagestring2\">2</a>";		
					}
					else
					{
						$pagination .= "<a href=\"$targetpage?$pagestring1\">1</a>";
						$pagination .= "<a href=\"$targetpage?$pagestring2\">2</a>";
					}				
					$pagination .= "...";
					for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
					{
						if ($counter == $page)
							$pagination .= "<span class=\"current\">$counter</span>";
						else
						{
							if($seomod == 1)
							{
								$url_query = preg_replace('/browse-(.*?)-videos-([0-9]*)-/', 'browse-$1-videos-'.$counter.'-', $targetpage);  
								$pagination .= "<a href=\"$url_query\">$counter</a>";
							}
							else
							{
								$url_query = preg_replace('/page=([0-9]*)/', 'page='.$counter, $pagestring);
								$pagination .= "<a href=\"$targetpage?$url_query\">$counter</a>";
							}						
//							$url_query = preg_replace('/page=([0-9]*)/', 'page='.$counter, $pagestring);
//							$pagination .= "<a href=\"$targetpage?$url_query\">$counter</a>";
						}
					}
					$pagination .= "...";
					if($seomod == 1)
					{					
						$pagination .= "<a href=\"$pagestringlpm1\">$lpm1</a>";
						$pagination .= "<a href=\"$pagestringlast\">$lastpage</a>";		
					}
					else
					{
						$pagination .= "<a href=\"$targetpage?$pagestringlpm1\">$lpm1</a>";
						$pagination .= "<a href=\"$targetpage?$pagestringlast\">$lastpage</a>";		
					}					
//					$pagination .= "<a href=\"$targetpage?$pagestringlpm1\">$lpm1</a>";
//					$pagination .= "<a href=\"$targetpage?$pagestringlast\">$lastpage</a>";		
				}
				//close to end; only hide early pages
				else
				{
					if($seomod == 1)
					{					
						$pagination .= "<a href=\"$pagestring1\">1</a>";
						$pagination .= "<a href=\"$pagestring2\">2</a>";		
					}
					else
					{
						$pagination .= "<a href=\"$targetpage?$pagestring1\">1</a>";
						$pagination .= "<a href=\"$targetpage?$pagestring2\">2</a>";
					}				
					$pagination .= "...";
					for ($counter = $lastpage - (1 + ($adjacents * 3)); $counter <= $lastpage; $counter++)
					{
						if ($counter == $page)
							$pagination .= "<span class=\"current\">$counter</span>";
						else
						{
							if($seomod == 1)
							{
								$url_query = preg_replace('/browse-(.*?)-videos-([0-9]*)-/', 'browse-$1-videos-'.$counter.'-', $targetpage); 
								$pagination .= "<a href=\"$url_query\">$counter</a>";
							}
							else
							{
								$url_query = preg_replace('/page=([0-9]*)/', 'page='.$counter, $pagestring);
								$pagination .= "<a href=\"$targetpage?$url_query\">$counter</a>";
							}
						}
					}
				}
			}
			
			//next button
			if ($page < $counter - 1) 
			{
				if($seomod == 1)
				{
					$url_query = preg_replace('/browse-(.*?)-videos-([0-9]*)-/', 'browse-$1-videos-'.$next.'-', $targetpage);  
					$pagination .= "<a href=\"$url_query\">".$lang['next']." &raquo;</a>";
				}
				else
				{
					$url_query = preg_replace('/page=([0-9]*)/', 'page='.$next, $pagestring);
					$pagination .= "<a href=\"$targetpage?$url_query\">".$lang['next']." &raquo;</a>";
				}				
			}
			else
				$pagination .= "<span class=\"disabled\">".$lang['next']." &raquo;</span>";				
			$pagination .= "</div>\n";
		}
//	}	
	return $pagination;
}

function sanitize_title($title) {
	$title = strip_tags($title);
	// Preserve escaped octets.
	$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
	// Remove percent signs that are not part of an octet.
	$title = str_replace('%', '', $title);
	// Restore octets.
	$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);

	$title = remove_accents($title);
	if (seems_utf8($title)) {
		if (function_exists('mb_strtolower')) {
			$title = mb_strtolower($title, 'UTF-8');
		}
		$title = utf8_uri_encode($title, 200);
	}

	$title = strtolower($title);
	$title = preg_replace('/&.+?;/', '', $title); // kill entities
	$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
	$title = preg_replace('/\s+/', '-', $title);
	$title = preg_replace('|-+|', '-', $title);
	$title = trim($title, '-');

	return $title;
}
function remove_accents($string) {
	if ( !preg_match('/[\x80-\xff]/', $string) )
		return $string;
	if (seems_utf8($string)) {
		$chars = array(
		chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
		chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
		chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
		chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
		chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
		chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
		chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
		chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
		chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
		chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
		chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
		chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
		chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
		chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
		chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
		chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
		chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
		chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
		chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
		chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
		chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
		chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
		chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
		chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
		chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
		chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
		chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
		chr(195).chr(191) => 'y',
		chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
		chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
		chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
		chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
		chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
		chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
		chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
		chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
		chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
		chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
		chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
		chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
		chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
		chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
		chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
		chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
		chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
		chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
		chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
		chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
		chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
		chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
		chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
		chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
		chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
		chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
		chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
		chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
		chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
		chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
		chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
		chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
		chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
		chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
		chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
		chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
		chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
		chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
		chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
		chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
		chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
		chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
		chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
		chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
		chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
		chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
		chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
		chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
		chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
		chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
		chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
		chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
		chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
		chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
		chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
		chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
		chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
		chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
		chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
		chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
		chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
		chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
		chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
		chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
		chr(226).chr(130).chr(172) => 'E',
		chr(194).chr(163) => '');
		$string = strtr($string, $chars);
	} else {
		// Assume ISO-8859-1 if not UTF-8
		$chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
			.chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
			.chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
			.chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
			.chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
			.chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
			.chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
			.chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
			.chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
			.chr(252).chr(253).chr(255);
		$chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
		$string = strtr($string, $chars['in'], $chars['out']);
		$double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
		$double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
		$string = str_replace($double_chars['in'], $double_chars['out'], $string);
	}
	return $string;
}

function seems_utf8($Str) {
	for ($i=0; $i<strlen($Str); $i++) {
		if (ord($Str[$i]) <0x80) continue; # 0bbbbbbb
		elseif ((ord($Str[$i]) & 0xE0) == 0xC0) $n=1; # 110bbbbb
		elseif ((ord($Str[$i]) & 0xF0) == 0xE0) $n=2; # 1110bbbb
		elseif ((ord($Str[$i]) & 0xF8) == 0xF0) $n=3; # 11110bbb
		elseif ((ord($Str[$i]) & 0xFC) == 0xF8) $n=4; # 111110bb
		elseif ((ord($Str[$i]) & 0xFE) == 0xFC) $n=5; # 1111110b
		else return false; # Does not match any model
		for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
			if ((++$i == strlen($Str)) || ((ord($Str[$i]) & 0xC0) != 0x80))
			return false;
		}
	}
	return true;
}

function utf8_uri_encode( $utf8_string, $length = 0 ) {
	$unicode = '';
	$values = array();
	$num_octets = 1;
	for ($i = 0; $i <strlen( $utf8_string ); $i++ ) {
		$value = ord( $utf8_string[ $i ] );
		if ( $value < 128 ) {
			if ( $length && ( strlen($unicode) + 1> $length ) )
				break;
			$unicode .= chr($value);
		} else {
			if ( count( $values ) == 0 ) $num_octets = ( $value <224 ) ? 2 : 3;
			$values[] = $value;
			if ( $length && ( (strlen($unicode) + ($num_octets * 3))> $length ) )
				break;
			if ( count( $values ) == $num_octets ) {
				if ($num_octets == 3) {
					$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
				} else {
					$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
				}
				$values = array();
				$num_octets = 1;
			}
		}
	}
	return $unicode;
}

function get_video_tags($uniq_id = '', $make_links = 1)
{
	$sql = "SELECT * FROM pm_tags WHERE uniq_id = '".$uniq_id."' ORDER BY tag_id ASC";
	$result = mysql_query($sql);
	$tags = array();
	$id = 0;
	while($row = mysql_fetch_assoc($result))
	{
		$id = $row['tag_id'];
		$tags[$id] = $row;
		if($make_links != 0)
		{
			if(_SEOMOD == 1)
			{
				$tags[$id]['href'] = "<a href=\""._URL."/tags/".$row['safe_tag']."/\">".$row['tag']."</a>";
			}
			else
			{
				$tags[$id]['href'] = "<a href=\""._URL."/tag.php?t=".$row['safe_tag']."\">".$row['tag']."</a>";
			}
		}
	}
	return $tags;
}

function safe2tag($safe_tag = '')
{
	$safe_tag = stripslashes($safe_tag);
	$sql = "SELECT * FROM pm_tags WHERE safe_tag = '".secure_sql($safe_tag)."'";
	$result = mysql_query($sql);
	if(!$result)
		return false;
	$row = mysql_fetch_assoc($result);
	return $row['tag'];
}
function safe_tag($tag)
{
	$remove_chars = array('"', "'", "?", "!");//, "#", "%");
	//$tag = str_replace($remove_chars, '', $tag);
	$tag = sanitize_title($tag);
	
	return $tag;
}
function tag_cloud($randomize = 0, $limit = 15, $shuffle = 1)
{
	$max_size = 20;
	$min_size = 11;
	
	$sql = "SELECT tag_id, tag, safe_tag, COUNT(*) as numvids FROM pm_tags GROUP BY safe_tag";
	if($randomize == 0)
		$sql .= " ORDER BY numvids DESC";
	else
		$sql .= " ORDER BY tag_id DESC";
	if($limit != 0)
		$sql .= " LIMIT ".$limit;

	$result = mysql_query($sql);
	$tags = array();
	if($result)
	{
		$max = 0;
		$min = 10000;
		while($row = mysql_fetch_assoc($result))
		{
			if($row['numvids'] > $max)
			{
				$max = $row['numvids'];
			}
			if($row['numvids'] < $min)
			{
				$min = $row['numvids'];
			}
			$tags[ $row['tag_id'] ] = $row;
		}
		
		$spread = $max - $min;
		if($spread == 0)
			$spread = 1;
		$step = ($max_size - $min_size) / ($spread);
		foreach($tags as $tag_id => $tag)
		{
			$size = round($min_size + (($tag['numvids'] - $min) * $step));
			
			if(_SEOMOD)
				$tags[ $tag_id ]['href'] = "<a href=\""._URL."/tags/".$tag['safe_tag']."/\" class=\"tag_cloud_link\" style=\"font-size:".$size."px;\">".$tag['tag']."</a> ";
			else
				$tags[ $tag_id ]['href'] = "<a href=\""._URL."/tag.php?t=".$tag['safe_tag']."\" class=\"tag_cloud_link\" style=\"font-size:".$size."px;\">".$tag['tag']."</a> ";		
		}
	}
	if($shuffle == 1)
	{
		shuffle($tags);
	}
	return $tags;
}

function log_error($log_msg, $area, $msg_type) 
{

	if(!empty($log_msg)) 
	{
		$sql = "INSERT INTO pm_log (log_msg, area, msg_type, added) VALUES ('".$log_msg."', '".$area."', '".$msg_type."', '".time()."')";
		$result = mysql_query($sql);
	}
	return true;
}

// Optimized by Trace (http://www.phpsugar.com/forum/memberlist.php?mode=viewprofile&u=5965)
function add_to_chart($uniq_id)
{
	if ('' == $uniq_id)
		return true;
	$sql = "INSERT INTO pm_chart (uniq_id, views, views_this) VALUES ('".$uniq_id."', 1, 1) ON DUPLICATE KEY UPDATE views = views+1, views_this = views_this+1";
	mysql_query($sql);
	return true;
}

// Optimized by Trace (http://www.phpsugar.com/forum/memberlist.php?mode=viewprofile&u=5965)
function get_chart($limit = 50, $mode = 'advanced')
{
	$sql = " SELECT pm_chart.uniq_id, pm_chart.views, pm_videos.artist, pm_videos.video_title, pm_videos.description, pm_videos.added 
			FROM pm_chart 
			LEFT JOIN pm_videos ON ( pm_chart.uniq_id = pm_videos.uniq_id ) 
			ORDER BY pm_chart.views DESC";
	if($limit > 0)
		$sql .= " LIMIT ".$limit;
		
	$result = mysql_query($sql);
	
	if($result !== false)
	{
		$vids = array();
		while($row = mysql_fetch_assoc($result))
		{
			$vids[$row['uniq_id']] = $row;
		}
	}
	return (is_array($vids)) ? $vids : array();
}

// Optimized by Trace (http://www.phpsugar.com/forum/memberlist.php?mode=viewprofile&u=5965)
function reset_chart()
{
	//Reset the chart
	mysql_query('LOCK TABLES pm_chart'); //Lock it just to make sure
	mysql_query('UPDATE pm_chart SET views = views_this + views_last + views_seclast, views_seclast = views_last, views_last = views_this, views_this = 0'); //Move views to the right
	mysql_query('DELETE FROM pm_chart WHERE views < 5'); //Some cleaning
	mysql_query('UNLOCK TABLES pm_chart'); //Unlock tables
	update_config('chart_last_reset', time());
	
	return true;
}

function count_days( $timestamp_1, $timestamp_2 )
{

	$gd_a = getdate( $timestamp_1 );
	$gd_b = getdate( $timestamp_2 );
	$a_new = mktime( 12, 0, 0, $gd_a['mon'], $gd_a['mday'], $gd_a['year'] );
	$b_new = mktime( 12, 0, 0, $gd_b['mon'], $gd_b['mday'], $gd_b['year'] );
	return round( abs( $a_new - $b_new ) / 86400 );
}

function unspecialchars($text, $and_quotes = 0) {

   if( $and_quotes == 1 || $and_quotes === true )
   {
      $text = str_replace('&quot;', '"', $text);
      $text = str_replace('&#039', "'", $text);
   }
   $text = str_replace('&lt;', '<', $text);
   $text = str_replace('&gt;', '>', $text);
   return $text;
}

function generate_activation_key($length = 9)
{
	$charset = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789";
	$code = '';
	$charset_len = strlen($charset);
	
	for($i = 0; $i < $length; $i++)
	{
		$code .= $charset{ rand(0, $charset_len) };	
	}
	return $code;
}

function fetch_video_sources()
{
	$sql = "SELECT * FROM pm_sources";
	$result = mysql_query($sql);
	if(!$result)
		return false;
	$src = array();
	$id = 0;
	while($row = mysql_fetch_assoc($result))
	{
		$id = $row['source_id'];
		$src[ $id ] = $row;
	}
	foreach($src as $id => $source)
	{
		$src[$source['source_name']] = $source;
	}
	
	return $src;
}

function stats()

{
	global $config;
	
	$stats 	= array();
	$r		= array();
	$sql	= '';
	$result	= '';
	$now	= time();
	$sevend	= ((60 * 60) * 24) * 7;
	$fivem	= 60 * 5;
	
	//	total number of videos
	$stats['videos'] = pm_number_format($config['total_videos']);
	
	//	videos added last week
	$sql = "SELECT COUNT(*) as total FROM pm_videos WHERE added > '". ($now - $sevend) . "'";
	$result = @mysql_query($sql);
	$r 	= @mysql_fetch_assoc($result);
	$stats['videos_last_week'] = pm_number_format($r['total']);
	@mysql_free_result($result);
	
	//	total number of users
	$sql = "SELECT COUNT(id) as total FROM pm_users";
	$result = @mysql_query($sql);
	$r 	= @mysql_fetch_assoc($result);
	$stats['users'] = pm_number_format($r['total']);
	@mysql_free_result($result);
		
	//	online users
	$sql = "SELECT COUNT(*) as total FROM pm_users WHERE last_signin > '". ($now - $fivem) ."'";
	$result = @mysql_query($sql);
	$r 	= @mysql_fetch_assoc($result);
	$stats['online_users'] = pm_number_format($r['total']);
	@mysql_free_result($result);

	return $stats;
}
if (!function_exists('json_encode'))
{
  function json_encode($a = false)
  {
    if (is_null($a)) return 'null';
    if ($a === false) return 'false';
    if ($a === true) return 'true';
    if (is_scalar($a))
    {
      if (is_float($a))
      {
        // Always use "." for floats.
        return floatval(str_replace(",", ".", strval($a)));
      }

      if (is_string($a))
      {
        static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
        return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
      }
      else
        return $a;
    }
    $isList = true;
    for ($i = 0, reset($a); $i < count($a); $i++, next($a))
    {
      if (key($a) !== $i)
      {
        $isList = false;
        break;
      }
    }
    $result = array();
    if ($isList)
    {
      foreach ($a as $v) $result[] = json_encode($v);
      return '[' . join(',', $result) . ']';
    }
    else
    {
      foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
      return '{' . join(',', $result) . '}';
    }
  }
}

/*
	This function returns an array containing all the info about the user's Favorite Videos
*/
function request_user_playlist($user_id)
{
	if( ! is_numeric($user_id))
	{
		return false;
	}
	
	$content	= array();
	$all_vids	= array();
	
	$sql = "SELECT * 
			FROM pm_favorites 
			WHERE user_id = '".$user_id."'";	
	$result = @mysql_query($sql);
	if(!$result)
	{
		return false;
	}
	while($row = mysql_fetch_assoc($result))
	{
		$all_vids[] = $row['uniq_id'];
	}
	
	$total_videos = mysql_num_rows($result);
	mysql_free_result($result);
	
	if($total_videos > 0)
	{
		foreach($all_vids as $k => $uniq_id)
		{
			$content[ $uniq_id ] = request_video($uniq_id, 'favorites', false);
		}
	}

	return $content;
}

function report_video($uniq_id, $r_type, $reason, $username)
{
	if ($uniq_id == '')
		return '';
	
	$sql = "SELECT COUNT(*) as total_found FROM pm_reports 
			WHERE entry_id = '". secure_sql($uniq_id) ."'";
	$result = mysql_query($sql);
	if ( ! $result)
	{
		return false;
	}
	$row = mysql_fetch_assoc($result);
	mysql_free_result($result);
	
	if ($row['total_found'] == 0)
	{
		$sql = "INSERT INTO pm_reports 
						(r_type, entry_id, reason, submitted, added) 
				VALUES ('". $r_type ."', '". $uniq_id ."', '". $reason ."', '". $username ."', '". time() ."')";
		$result = mysql_query($sql);
		if ( ! $result)
		{
			return false;
		}
	}
	return true;
}

function get_config($name = '')
{
	$config = array();
	$row = array();
	
	$sql = "SELECT * 
			FROM pm_config";
	if ('' != $name)
	{
		$sql .= " WHERE name = '". $name ."'";
	}
	
	$result = @mysql_query($sql);
	while ($row = @mysql_fetch_assoc($result))
	{
		$config[$row['name']] = $row['value'];
	}
	@mysql_free_result($result);
	
	if (count($config) < 3 && $name == '')
	{
		$sql = "SELECT * FROM pm_config WHERE id = '1'";
		$result = @mysql_query($sql);
		$config = @mysql_fetch_assoc($result);
		@mysql_free_result($result);
	}
	
	if ('' != $name)
		return $config[$name];

	return $config;
}

function update_config($name, $value, $overwrite = true)
{
	global $config;
	
	if (!array_key_exists($name, $config))
	{
		return array('Setting variable <code>"'. $name .'"</code> not found', 0);
	}
	
	$value = trim($value);
	$value = secure_sql($value);
	
	$sql = "UPDATE pm_config 
			SET value = '". $value ."' 
			WHERE name = '". $name ."'";
	$result = mysql_query($sql);
	if ( ! $result)
	{
		return array(mysql_error(), mysql_errno());
	}
	
	if ($overwrite == true)
	{
		$config[$name] = $value;
	}
	
	return true;
}

if ( ! function_exists('mb_strlen'))
{
	function mb_strlen($str, $encoding) 
	{
		if ($encoding == 'UTF-8') 
		{
			return preg_match_all('%(?:
					  [\x09\x0A\x0D\x20-\x7E] 
					| [\xC2-\xDF][\x80-\xBF]
					|  \xE0[\xA0-\xBF][\x80-\xBF]
					| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}
					|  \xED[\x80-\x9F][\x80-\xBF]
					|  \xF0[\x90-\xBF][\x80-\xBF]{2}
					| [\xF1-\xF3][\x80-\xBF]{3}
					|  \xF4[\x80-\x8F][\x80-\xBF]{2}
					)%xs', $str, $out);
		} 
		else
		{
			return strlen($str);
		}
	}
}
if ( ! function_exists('mb_substr'))
{
	function mb_substr($str, $start, $length, $enconding)
	{
		return substr($str, $start, $length);
	}
}
if ( ! function_exists('str_ireplace'))
{
	function str_ireplace($search, $replace, $subject)
	{
		//return str_replace($search, $replace, $subject);
		$search = str_replace( array('/', "'"), array('\/', "\'"), $search);
		$return  = preg_replace('/'. $search .'/is', $replace, $subject);
		return $return;
	}
}


function add_meta($item_id, $item_type, $meta_key, $meta_value, $check = false)
{
	if (!$item_id || !$item_type || !$meta_key)
	{
		return false;
	}
	
	if ($check)
	{
		$buff = get_meta($item_id, $item_type, $meta_key);
		if (count($buff) > 0)
		{
			update_meta($item_id, $item_type, $meta_key, $meta_value);
			return true;
		}
	}
	
	$meta_key = stripslashes($meta_key);
	$meta_key = trim($meta_key);
	$meta_key = str_replace(' ', '-', $meta_key);
	$meta_key = secure_sql($meta_key);
	
	$meta_value = stripslashes($meta_value);
	$meta_value = trim($meta_value);
	$meta_value = secure_sql($meta_value);	
	
	$sql = "INSERT INTO pm_meta	(item_id, item_type, meta_key, meta_value) 
			VALUES ('". $item_id ."', '". $item_type ."', '". $meta_key ."', '". $meta_value ."')";
	$result = mysql_query($sql);
	
	return true;
}

function update_meta($item_id, $item_type, $meta_key, $meta_value)
{
	if (!$item_id || !$item_type || !$meta_key)
	{
		return false;
	}
	
	$meta_key = stripslashes($meta_key);
	$meta_key = trim($meta_key);
	$meta_key = str_replace(' ', '-', $meta_key);
	$meta_key = secure_sql($meta_key);
	
	// first, check if meta key exists
	$sql = "SELECT meta_key 
			FROM pm_meta 
			WHERE item_id = '". $item_id ."' 
			  AND item_type = '". $item_type ."' 
			  AND meta_key = '". $meta_key ."' ";
	$result = mysql_query($sql);
	if (mysql_num_rows($result) == 0)
	{
		add_meta($item_id, $item_type, $meta_key, $meta_value);
		return true; 
	}
	mysql_free_result($result);
	
	$meta_value = stripslashes($meta_value);
	$meta_value = trim($meta_value);
	$meta_value = secure_sql($meta_value);
	
	$sql = "UPDATE pm_meta 
			   SET meta_value = '". $meta_value ."' 
			WHERE item_id = '". $item_id ."' 
			  AND item_type = '". $item_type ."' 
			  AND meta_key = '". $meta_key ."'";
	
	mysql_query($sql);

	return true;
}

function delete_meta($item_id, $item_type, $meta_key = '')
{
	if (!$item_id || !$item_type)
	{
		return false;
	}
	
	$single = ('' != $meta_key) ? true : false;
	
	$sql = "DELETE FROM pm_meta 
			WHERE item_id = '". $item_id ."' 
			  AND item_type = '". $item_type ."' ";
	$sql .= ($single) ? " AND meta_key = '". $meta_key ."' " : '';
	$result = mysql_query($sql);
	
	return true;
}

function get_meta($item_id, $item_type, $meta_key = '')
{
	$meta = array();
	$single = ('' != $meta_key) ? true : false;

	$sql = "SELECT meta_key, meta_value  
			FROM pm_meta 
			WHERE item_id = '". $item_id ."' 
			  AND item_type = '". $item_type ."' ";
	
	$sql .= ($single) ? " AND meta_key = '". $meta_key ."' " : '';
	
	$result = mysql_query($sql);
	
	if ($single)
	{
		$row = mysql_fetch_assoc($result);
		$meta[$row['meta_key']] = $row['meta_value'];
	}
	else if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_assoc($result))
		{
			// group by meta_key 
			$meta['*'][$row['meta_key']][] = $row['meta_value'];
			
			// will overwrite the value for duplicate keys
			$meta[$row['meta_key']] = $row['meta_value'];
		}
	}
	else
	{
		$meta = array();
	}
	mysql_free_result($result);
	
	return $meta; 
}

function resize_then_crop($filein, $fileout, $imagethumbsize_w, $imagethumbsize_h, $red, $green, $blue, $allowed_type = array())
{
	// $allowed_type = array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg');
	$percent = 0.5;
	// Get new dimensions
	$image_info	= getimagesize($filein);
	
	$width		= $image_info[0];
	$height		= $image_info[1];
	$new_width 	= $width * $percent;
	$new_height	= $height * $percent;
	
	if(is_array($allowed_type) && count($allowed_type) > 0)
	{
		if(!in_array($image_info['mime'], $allowed_type))
		{
			return false;
		}
	}
	
	if(preg_match("/.jpg/i", "$filein"))
	{
	   $format = 'image/jpeg';
	}
	if (preg_match("/.gif/i", "$filein"))
	{
	   $format = 'image/gif';
	}
	if(preg_match("/.png/i", "$filein"))
	{
	   $format = 'image/png';
	}
	
	switch($format)
	{
	    case 'image/jpeg':
			$image = imagecreatefromjpeg($filein);
	    break;
		
	    case 'image/gif';
	    	$image = imagecreatefromgif($filein);
	    break;
		
	    case 'image/png':
			$image = imagecreatefrompng($filein);
	    break;
		
		default:
			$image = '';
		break;
	}
	
	if (!$image)
	{
		return false;
	}
	
	$width	= $imagethumbsize_w;
	$height	= $imagethumbsize_h;
	
	list($width_orig, $height_orig) = getimagesize($filein);
	
	if ($width_orig < $height_orig) 
	{
		$height = ($imagethumbsize_w / $width_orig) * $height_orig;
	} 
	else 
	{
		$width = ($imagethumbsize_h / $height_orig) * $width_orig;
	}
	
	if ($width < $imagethumbsize_w)
	{
		$width = $imagethumbsize_w;
		$height = ($imagethumbsize_w/ $width_orig) * $height_orig;;
	}
	
	if ($height < $imagethumbsize_h)
	{
		$height = $imagethumbsize_h;
		$width = ($imagethumbsize_h / $height_orig) * $width_orig;
	}
	
	$thumb		= imagecreatetruecolor($width , $height);
	$bgcolor	= imagecolorallocate($thumb, $red, $green, $blue);   
	ImageFilledRectangle($thumb, 0, 0, $width, $height, $bgcolor);
	imagealphablending($thumb, true);
	
	imagecopyresampled($thumb, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
	$thumb2 = imagecreatetruecolor($imagethumbsize_w , $imagethumbsize_h);
	
	// true color for best quality
	$bgcolor = imagecolorallocate($thumb2, $red, $green, $blue);   
	ImageFilledRectangle($thumb2, 0, 0,	$imagethumbsize_w , $imagethumbsize_h , $white);
	imagealphablending($thumb2, true);
	
	$w1 = ($width / 2) - ($imagethumbsize_w / 2);
	$h1 = ($height / 2) - ($imagethumbsize_h / 2);
	
	imagecopyresampled($thumb2, $thumb, 0,0, $w1, $h1, $imagethumbsize_w , $imagethumbsize_h ,$imagethumbsize_w, $imagethumbsize_h);
	
	if ($fileout != "")
	{
		imagegif($thumb2, $fileout); //write to file
	}
	
	return true;
}

// wrapper for number_format function
function pm_number_format($number)
{
	return number_format($number, 0, '.', ',');
}

?>