<?PHP
/*
=====================================================
 DataLife Engine - by SoftNews Media Group 
-----------------------------------------------------
 http://www.pc-soft.ru/
-----------------------------------------------------
 Copyright (c) 2004,2006 SoftNews Media Group
=====================================================
 Äàííûé êîä çàùèùåí àâòîðñêèìè ïðàâàìè
=====================================================
 Ôàéë: functions.inc.php
-----------------------------------------------------
 Íàçíà÷åíèå: Îñíîâíûå ôóíêöèè
=====================================================
*/
if(!defined('DATALIFEENGINE'))
{
  die("Hacking attempt!");
}

function formatsize($file_size){
    if($file_size >= 1073741824)
        {$file_size = round($file_size / 1073741824 * 100) / 100 . " Gb";}
    elseif($file_size >= 1048576)
        {$file_size = round($file_size / 1048576 * 100) / 100 . " Mb";}
    elseif($file_size >= 1024)
        {$file_size = round($file_size / 1024 * 100) / 100 . " Kb";}
    else{$file_size = $file_size . " b";}
return $file_size;
}

class microTimer {
    function start() {
        global $starttime;
        $mtime = microtime ();
        $mtime = explode (' ', $mtime);
        $mtime = $mtime[1] + $mtime[0];
        $starttime = $mtime;
    }
    function stop() {
        global $starttime;
        $mtime = microtime ();
        $mtime = explode (' ', $mtime);
        $mtime = $mtime[1] + $mtime[0];
        $endtime = $mtime;
        $totaltime = round (($endtime - $starttime), 5);
        return $totaltime;
    }
}

function get_real_time()
{
	list($seconds, $microSeconds) = explode(' ', microtime());
	return ((float)$seconds + (float)$microSeconds);
}

///////////////////////////////////////////////////////
// Function:    Flooder
// Description: Flood Protection Function

function flooder($ip){
    global $config, $db;

$this_time = time() + ($config['date_adjust']*60) - $config['flood_time'];
$db->query("DELETE FROM " . PREFIX . "_flood where id < '$this_time'");

$sql_flood = "SELECT * FROM " . PREFIX . "_flood where id > '$this_time' and ip = '$ip'";

if ($db->num_rows($db->query($sql_flood)) > 0) $result = TRUE; else $result = FALSE;

    return $result;
}

///////////////////////////////////////////////////////
// Function:    query_string
// Description: Format the Query_String

function query_string($q_string, $strips, $type="get"){
    foreach($strips as $key){
        $strips[$key] = TRUE;
    }
    $var_value = explode("&", $q_string);

    foreach($var_value as $var_peace){
        $parts = explode("=", $var_peace);
        if($strips[$parts[0]] != TRUE and $parts[0] != ""){
            if($type == "post"){
                $my_q .= "<input type=\"hidden\" name=\"".$parts[0]."\" value=\"".$parts[1]."\" />\n";
            }else{
                $my_q .= "$var_peace&amp;";
            }
        }
    }

if( substr($my_q, -5) == "&amp;" ){ $my_q = substr($my_q, 0, -5); }

return $my_q;
}

////////////////////////////////////////////////////////
// Function:     insertSmilies
// Description: insert smilies for adding into news/comments

function insertSmilies($insert_location, $break_location = FALSE)
{
    global $config;
	$i = 0;
	$output = "";

    $smilies = explode(",", $config['smilies']);
    foreach($smilies as $smile)
    {
        $i++; $smile = trim($smile);

        $output .= "<a href=\"#\" onClick=\"insertext(':$smile:','$insert_location'); return false;\"><img style=\"border: none;\" alt=\"$smile\" src=\"".$config['http_home_url']."engine/data/emoticons/$smile.gif\" /></a>";
       	if($i%$break_location == 0 and $break_location)
		{
			$output .= "<br />";
		}else{ $output .= "&nbsp;"; }
    }
    return $output;
}

////////////////////////////////////////////////////////
// Function:    ToTranslit
// Description: Transliteration cyrillic symbols

function totranslit($var)
{
        $NpjLettersFrom = "àáâãäåçèêëìíîïðñòóôöû";
        $NpjLettersTo   = "abvgdeziklmnoprstufcy";
        $NpjBiLetters = array( 
      "é" => "jj", "¸" => "jo", "æ" => "zh", "õ" => "kh", "÷" => "ch", 
      "ø" => "sh", "ù" => "shh", "ý" => "je", "þ" => "ju", "ÿ" => "ja",
      "ú" => "", "ü" => "",
                              );

        $NpjCaps  = "ÀÁÂÃÄÅ¨ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÜÚÛÝÞß";
        $NpjSmall = "àáâãäå¸æçèéêëìíîïðñòóôõö÷øùüúûýþÿ";

	  $var = trim(strip_tags($var));
      $var = preg_replace( "/\s+/ms", "_", $var );
      $var = strtr( $var, $NpjCaps, $NpjSmall );
      $var = strtr( $var, $NpjLettersFrom, $NpjLettersTo );
      $var = strtr( $var, $NpjBiLetters );

      $var = preg_replace("/[^a-z0-9_]+/mi", "", $var);
	  $var = strtolower ( $var );

  return $var;
}

////////////////////////////////////////////////////////
// Function:    LangDate
// Description: Changing of date by cyrillic equivalents
function langdate($langdateformat, $langdatetimestamp){
  global $langdateshortweekdays, $langdatemonths, $langdateweekdays, $langdateshortmonths;
  $langdateformat = preg_replace("/(?<!\\\\)D/", $langdateshortweekdays[date("w", $langdatetimestamp)], $langdateformat);
  $langdateformat = preg_replace("/(?<!\\\\)F/", $langdatemonths[date("n", $langdatetimestamp) - 1], $langdateformat);
  $langdateformat = preg_replace("/(?<!\\\\)l/", $langdateweekdays[date("w", $langdatetimestamp)], $langdateformat);
  $langdateformat = preg_replace("/(?<!\\\\)M/", $langdateshortmonths[date("n", $langdatetimestamp) - 1], $langdateformat);

  return date($langdateformat, $langdatetimestamp);
}

////////////////////////////////////////////////////////
// Function: 	word_filter
// Description: Filter comments, add news and/or edit news
function word_filter($source) {
	$all_words = file(ENGINE_DIR.'/data/wordfilter.db.php');

if (!empty($all_words)) {
	foreach($all_words as $word_line)
	{
		$word_arr = explode("|", $word_line);

		$find[] = "'".$word_arr[1]."'";
		$replace[] = $word_arr[2];

	}

	$source = preg_replace($find,$replace,$source);
}
	return $source;
}
////////////
// Declare the function
function msgbox($title, $text){
global $tpl;

$tpl->load_template('info.tpl');

$tpl->set('{error}', $text);
$tpl->set('{title}', $title);

  $tpl->compile('info');
  $tpl->clear();
}


function ShowRating ($id, $rating, $vote_num){
global $is_logged, $member_id, $config, $lang, $db;


$excellent = $lang['excellent'];
$good = $lang['good'];
$fair = $lang['fair'];
$poor = $lang['poor'];
$useless = $lang['useless'];

$rated = "<div id='ratig-layer'><form name=\"rating\"  id='rating' method=\"post\">\n";

$rated .= "<b>$lang[raten]</b> ";

if ($rating < 1)
{

$rated .= $lang['noraten'];

} else
{
$rating = round(($rating /  $vote_num), 0);

if ($rating == 1) {
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rate1.gif\" border=\"0\"  align=\"absmiddle\" alt=\"$lang[rated] $useless\">\n";
}elseif ($rating == 2) {
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rate2.gif\" border=\"0\" align=\"absmiddle\" alt=\"$lang[rated] $poor\">\n";
}elseif ($rating == 3) {
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rate3.gif\" border=\"0\" align=\"absmiddle\" alt=\"$lang[rated] $fair\">\n";
}elseif ($rating == 4) {
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rate4.gif\" border=\"0\" align=\"absmiddle\" alt=\"$lang[rated] $good\">\n";
}elseif ($rating == 5) {
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rate5.gif\" border=\"0\" align=\"absmiddle\" alt=\"$lang[rated] $excellent\">\n";
}
$rated  .= " ($lang[voten] $vote_num)";
}

if ($_SERVER['REMOTE_ADDR']) $ip = $_SERVER['REMOTE_ADDR'];
else $ip = "not detected";

if ($rating){
if ($is_logged) $where = "member = '{$member_id['name']}'";
else $where = "ip ='{$ip}'";
$sql_result = $db->query("SELECT news_id FROM " . PREFIX . "_logs where news_id ='$id' AND {$where}");
$row = $db->get_row($sql_result);
}

if ($row['news_id']){

$rated  .= "<br>$lang[rdenied]";

}else {
// Select box
$rated  .= "<br><div style=\"margin-top:5px;\"><b>$lang[yrate] </b>";
		$options = array("$excellent", "$good", "$fair", "$poor", "$useless");


        $rated  .= "<select class=rating name=\"go_rate\" id=\"go_rate\">\n";

		for ($i = 0; $i < count($options); $i++) { $this_rate = 5-$i;
		  $rated  .= "<option value = \"$this_rate\">$options[$i]</option>\n";
}
 		$rated  .= "</select>\n";
    	$rated  .= "<input type=\"hidden\" name=\"doaction\" value=\"rate\">\n";
    	$rated  .= "<input type=\"hidden\" name=\"news_id\" id=\"news_id\" value=\"$id\">\n";
        $rated  .= "<input class=rating type=\"submit\" onClick=\"doRate(); return false;\" value=\"$lang[entrat]\"></div>\n";
        
}


$rated  .= "</form></div>\n";


return $rated;
}


function ShortRating ($rating, $vote_num){
global $config, $lang;

$rated = "";

$excellent = $lang['excellent'];
$good = $lang['good'];
$fair = $lang['fair'];
$poor = $lang['poor'];
$useless = $lang['useless'];

if ($rating < 1){
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rating0.gif\" border=\"0\"  align=\"absmiddle\" alt=\"$lang[noraten]\">\n";

} else {
$rating = round(($rating /  $vote_num), 0);

if ($rating == 1) {
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rating1.gif\" border=\"0\"  align=\"absmiddle\" alt=\"$lang[rated] $useless\">\n";
}elseif ($rating == 2) {
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rating2.gif\" border=\"0\" align=\"absmiddle\" alt=\"$lang[rated] $poor\">\n";
}elseif ($rating == 3) {
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rating3.gif\" border=\"0\" align=\"absmiddle\" alt=\"$lang[rated] $fair\">\n";
}elseif ($rating == 4) {
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rating4.gif\" border=\"0\" align=\"absmiddle\" alt=\"$lang[rated] $good\">\n";
}elseif ($rating == 5) {
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rating5.gif\" border=\"0\" align=\"absmiddle\" alt=\"$lang[rated] $excellent\">\n";
}
}

return $rated;
}


function userrating ($name){
global $config, $lang, $db;
$rated = "";

$sql_result = $db->query("SELECT SUM(rating), SUM(vote_num) FROM " . PREFIX . "_post where autor ='$name'");

$row = $db->get_array($sql_result);

if (!$row[0]){
$rated = $lang['unorat'];

} else {
$rating = round(($row[0] /  $row[1]), 0);

if ($rating == 1) {
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rate1.gif\" border=\"0\"  align=\"absmiddle\" alt=\"$lang[urated]\">\n";
}elseif ($rating == 2) {
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rate2.gif\" border=\"0\" align=\"absmiddle\" alt=\"$lang[urated]\">\n";
}elseif ($rating == 3) {
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rate3.gif\" border=\"0\" align=\"absmiddle\" alt=\"$lang[urated]\">\n";
}elseif ($rating == 4) {
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rate4.gif\" border=\"0\" align=\"absmiddle\" alt=\"$lang[urated]\">\n";
}elseif ($rating == 5) {
    $rated  .= "<img src=\"".$config['http_home_url']."engine/skins/images/rate5.gif\" border=\"0\" align=\"absmiddle\" alt=\"$lang[urated]\">\n";
}
}

return $rated;
}

function CategoryNewsSelection($categoryid = 0, $parentid = 0, $nocat = TRUE, $sublevelmarker = '', $returnstring = '')
{ 
	global $cat_info, $user_group, $member_id;

	$allow_list = explode (',', $user_group[$member_id['user_group']]['allow_cats']);
	$spec_list = explode (',', $user_group[$member_id['user_group']]['cat_add']);

	if($parentid == 0) {
		if ($nocat) $returnstring .= '<option value="0"></option>';
	} else  {
		$sublevelmarker .= '&nbsp;&nbsp;&nbsp;';
	}

	if (count($cat_info)) {

		foreach ($cat_info as $cats) {
			if ($cats['parentid'] == $parentid) $root_category[] = $cats['id'];
		}

		if (count($root_category)) {
			foreach ($root_category as $id) {

				if ($allow_list[0] == "all" OR in_array($id, $allow_list)) {

					if ($spec_list[0] == "all" OR in_array($id, $spec_list)) $color = "dark"; else $color = "red";
					$returnstring .= "<option style=\"color: {$color}\" value=\"".$id.'" ';
					if (is_array ($categoryid)) {
						foreach ($categoryid as $element) {
							if($element == $id) $returnstring .= 'selected';
						}
					}	elseif ($categoryid == $id) {
						$returnstring .= 'selected';
					}
					$returnstring .= '>'.$sublevelmarker.$cat_info[$id]['name'].'</option>';
				}
				$returnstring = CategoryNewsSelection($categoryid, $id, $nocat, $sublevelmarker, $returnstring);
			}
		}
	}
	return $returnstring;
}

function get_ID ($cat_info, $category){
  foreach ($cat_info as $cats) {
   if ($cats['alt_name'] == $category) return $cats['id'];
  }
return false;
}

function set_vars ($file, $data){

	$filename = ENGINE_DIR.'/cache/system/'.$file.'.php';

    $fp = fopen($filename, 'wb+');
    fwrite($fp, serialize($data) );
    fclose($fp);

	@chmod($filename, 0666);
}

function get_vars ($file){
	$filename = ENGINE_DIR.'/cache/system/'.$file.'.php';

    if (!@filesize($filename)){
    	return false;
    }

	return unserialize(file_get_contents($filename));

}

function filesize_url($url){
   return ($data = @file_get_contents($url)) ? strlen($data) : false;
}

function dle_cache($prefix, $cache_id=false, $member_prefix=false){
  global $config, $is_logged, $member_id;

	if ($config['allow_cache'] != "yes") return false;

	if ($is_logged) $end_file = $member_id['user_group']; else $end_file = "0";

	if ($cache_id == false) {
	$filename = ENGINE_DIR.'/cache/'.$prefix.'.tmp';	
	} else {
	$cache_id = totranslit ($cache_id);

		if ($member_prefix)
	$filename = ENGINE_DIR."/cache/".$prefix."_".$cache_id."_".$end_file.".tmp";
		else
	$filename = ENGINE_DIR."/cache/".$prefix."_".$cache_id.".tmp";

	}

    if (!@filesize($filename)){
    	return false;
    }

	$cache = gzuncompress (file_get_contents($filename));

return $cache;
}

function create_cache($prefix, $cache_text, $cache_id=false, $member_prefix=false){
  global $config, $is_logged, $member_id;

		if ($config['allow_cache'] != "yes") return false;

	if ($is_logged) $end_file = $member_id['user_group']; else $end_file = "0";


	if ($cache_id == false) {
	$filename = ENGINE_DIR.'/cache/'.$prefix.'.tmp';	
	} else {
	$cache_id = totranslit ($cache_id);

		if ($member_prefix)
	$filename = ENGINE_DIR."/cache/".$prefix."_".$cache_id."_".$end_file.".tmp";
		else
	$filename = ENGINE_DIR."/cache/".$prefix."_".$cache_id.".tmp";

	}

	$cache_text = gzcompress($cache_text, 1);

    $fp = fopen($filename, 'wb+');
    fwrite($fp, $cache_text);
    fclose($fp);

	@chmod($filename, 0666);

}

function clear_cache($cache_area = false){
global $config;

	if ($cache_area){
	$filename = ENGINE_DIR.'/cache/'.$cache_area.'.tmp';
	@unlink($filename);
	} else {
	$fdir = opendir(ENGINE_DIR.'/cache');
    while ($file = readdir($fdir)){
        if ($file != '.' and $file != '..' and $file != '.htaccess' and $file != 'system'){
	                @unlink(ENGINE_DIR.'/cache/'.$file);

      	  }
  	  }
	}
}
function ChangeSkin($dir, $skin){


        $templates_list = array();

        $handle = opendir($dir);

           while (false !== ($file = readdir($handle))){
				if(is_dir("./templates/$file") and ($file != "." and $file!="..")){
            $templates_list[] = $file;
        }
          }
        closedir($handle);

	$skin_list = "<form method=post action=\"$PHP_SELF\"><select onchange=\"submit()\" name=skin_name>";

        foreach($templates_list as $single_template){
			if ($single_template == $skin) $selected = " selected"; else $selected = "";
            $skin_list .= "<option value=\"$single_template\"".$selected.">$single_template</option>";
        }
        $skin_list .= '</select><input type=hidden name=action_skin_change value=yes></form>';

return $skin_list;
} 

function custom_print ($custom_category, $custom_template, $aviable, $custom_from, $custom_limit, $custom_cache, $do){
global $db, $is_logged, $member_id, $xf_inited, $cat_info, $config, $user_group;


	$do = $do ? $do : "main";
	$aviable = explode ('|', $aviable);

	if(!(in_array($do, $aviable)) AND ($aviable[0] != "global")) return "";

	$custom_category  = mysql_escape_string(str_replace(',', '|', $custom_category));
	$custom_from = intval($custom_from);
	$custom_limit = intval($custom_limit);
	$thisdate = date ("Y-m-d H:i:s", (time()+ $config['date_adjust']*60));
	$content = false;

	$tpl = new dle_template;
	$tpl->dir = TEMPLATE_DIR;

	if ($custom_cache == "yes") $config['allow_cache'] = "yes"; else $config['allow_cache'] = false;
	if ($is_logged AND ($user_group[$member_id['user_group']]['allow_edit'] AND !$user_group[$member_id['user_group']]['allow_all_edit'])) $config['allow_cache'] = false;

	$content = dle_cache("custom", $custom_category.$custom_template.$custom_from, true);

	if ($content) { return $content; }
	else {
	$allow_list = explode (',', $user_group[$member_id['user_group']]['allow_cats']);
	if ($allow_list[0] != "all") $stop_list = "category regexp '[[:<:]](".implode ('|', $allow_list).")[[:>:]]' AND "; else $stop_list = "";

	if ($user_group[$member_id['user_group']]['allow_short']) $stop_list = "";

    $sql_select = "SELECT id, autor, date, short_story, full_story, xfields, title, category, alt_name, comm_num, allow_comm, allow_rate, rating, vote_num, news_read FROM " . PREFIX . "_post where {$stop_list}category regexp '[[:<:]]($custom_category)[[:>:]]' AND approve = '1' AND date < '$thisdate' order by ".$config['news_sort']." ".$config['news_msort']." LIMIT ".$custom_from.",".$custom_limit;
	include(ENGINE_DIR.'/modules/show.custom.php');

		if ($config['files_allow'] == "yes")
			if ( stristr( $tpl->result['content'], "[attachment=" ) )
			{
				$tpl->result['content'] = show_attach($tpl->result['content'], $attachments);
			}

	create_cache("custom", $tpl->result['content'], $custom_category.$custom_template.$custom_from, true);

	}
	return $tpl->result['content'];
}

function check_module ($aviable, $block, $do) {

	$do = $do ? $do : "main";
	$aviable = explode ('|', $aviable);

	$block = str_replace("&amp;", "&", $block);
	$block = str_replace('\"', '"', $block);

	if(!(in_array($do, $aviable)) AND ($aviable[0] != "global")) return "";
	else return $block;

}
function check_ip () {

	if ($_SERVER['REMOTE_ADDR']) $ip = $_SERVER['REMOTE_ADDR'];
	else return false;

    $blockip = FALSE;
    $ips = file(ENGINE_DIR.'/data/ip.db.php');

    foreach($ips as $ip_line){
            $ip_arr = rtrim($ip_line);

            $ip_check_matches = 0;
            $db_ip_split = explode(".", $ip_arr);
            $this_ip_split = explode(".", $ip);

            for($i_i=0;$i_i<4;$i_i++){
                if ($this_ip_split[$i_i] == $db_ip_split[$i_i] OR $db_ip_split[$i_i] == '*') {
                    $ip_check_matches += 1;
                }

            }

            if ($ip_check_matches == 4) $blockip = TRUE;

    }

	return $blockip;
}

function show_attach ($story, $id) {
global $db, $config, $lang, $user_group, $member_id;

 if (is_array($id) AND count($id))
	$where = "news_id IN (".implode(",", $id).")";
 else
	$where = "news_id = '$id'";
 
  $getfiles = $db->query("SELECT id, name, onserver, dcount FROM " . PREFIX . "_files WHERE $where");

	while($row = $db->get_row($getfiles)){
	
	$size = formatsize(@filesize ( ROOT_DIR . '/uploads/files/' . $row['onserver'] ));

     if (!$user_group[$member_id['user_group']]['allow_files'])
		$link = "<span id=\"attachment\">{$lang['att_denied']}</span>";
	 elseif ($config['files_count'] == 'yes')
		$link = "<span id=\"attachment\"><a href=\"{$config['http_home_url']}engine/download.php?id={$row['id']}\" >{$row['name']}</a> [{$size}] ({$lang['att_dcount']} {$row['dcount']})</span>";
	  else
		$link = "<span id=\"attachment\"><a href=\"{$config['http_home_url']}engine/download.php?id={$row['id']}\" >{$row['name']}</a> [{$size}]</span>";

		$story = str_replace( '[attachment='.$row['id'].']', $link, $story );
	}

return $story;

}

function xfieldsload() {
  global $lang;
  $path = ENGINE_DIR.'/data/xfields.txt';
  $filecontents = file($path);

    if (!is_array($filecontents))
    msg("error", $lang['xfield_error'], "$lang[xfield_err_3] \"engine/data/xfields.txt\". $lang[xfield_err_4]");
  
    foreach ($filecontents as $name => $value) {
      $filecontents[$name] = explode("|", trim($value));
      foreach ($filecontents[$name] as $name2 => $value2) {
        $value2 = str_replace("&#124;", "|", $value2); 
        $value2 = str_replace("__NEWL__", "\r\n", $value2);
        $filecontents[$name][$name2] = $value2;
      }
    }
    return $filecontents;
}

function xfieldsdataload ($id) {

if ($id == "") return;

      $xfieldsdata = explode("||", $id);
      foreach ($xfieldsdata as $xfielddata) {
        list($xfielddataname, $xfielddatavalue) = explode("|", $xfielddata);
        $xfielddataname = str_replace("&#124;", "|", $xfielddataname);
        $xfielddataname = str_replace("__NEWL__", "\r\n", $xfielddataname);
        $xfielddatavalue = str_replace("&#124;", "|", $xfielddatavalue);
        $xfielddatavalue = str_replace("__NEWL__", "\r\n", $xfielddatavalue);
        $data[$xfielddataname] = $xfielddatavalue;
      }
    return $data;
}

function create_keywords ($story) {
global $metatags;

$keyword_count = 20;
$newarr = array ();
$quotes = array( "\x27", "\x22", "\x60", "\t","\n","\r","'",",",".","/","¬","#",";",":","@","~","[","]","{","}","=","-","+",")","(","*","&","^","%","$","<",">","?","!", '"' );
$fastquotes = array( "\x27", "\x22", "\x60", "\t","\n","\r",'"',"'" );

	$story = stripslashes($story);
	$story = str_replace('<br />', ' ', $story );
	$story = trim(strip_tags ($story));
	$story = str_replace($fastquotes, '', $story );

	$metatags['description'] = substr($story, 0, 190);

	$story = str_replace($quotes, '', $story );

	$arr   = explode(" ", $story);

	foreach ($arr as $word) {
	if (strlen($word) > 4) $newarr [] = $word;
	}

	$arr   = array_count_values ($newarr);
	arsort ($arr);

	$arr = array_keys($arr);

	$total = count ($arr);

	$offset = 0;

	$arr =	array_slice ($arr, $offset, $keyword_count);

	$metatags['keywords'] = implode (", ", $arr);
}
?>