<?PHP
if( ! defined( 'DATALIFEENGINE' ) ) {die( "Hacking attempt!" );}

require_once SYSTEM_DIR . '/classes/cache.class.php';
$cache = new cache($dir= ROOT_DIR . '/cache');

function format_uptime($seconds) {
    $secs = intval($seconds % 60);
    $mins = intval($seconds / 60 % 60);
    $hours = intval($seconds / 3600 % 24);
    $days = intval($seconds / 86400);

    if ($days > 0) {
        $uptimeString .= $days;
        $uptimeString .= (($days == 1) ? " day" : " days");
    }
    if ($hours > 0) {
        $uptimeString .= (($days > 0) ? ", " : "") . $hours;
        $uptimeString .= (($hours == 1) ? " hour" : " hours");
    }
    if ($mins > 0) {
        $uptimeString .= (($days > 0 || $hours > 0) ? ", " : "") . $mins;
        $uptimeString .= (($mins == 1) ? " minute" : " minutes");
    }
    if ($secs > 0) {
        $uptimeString .= (($days > 0 || $hours > 0 || $mins > 0) ? ", " : "") . $secs;
        $uptimeString .= (($secs == 1) ? " second" : " seconds");
    }
    return $uptimeString;
}

function dirsize($directory) {
    if( ! is_dir( $directory ) ) return - 1;
    $size = 0;
    if( $DIR = opendir( $directory ) ) {
        while ( ($dirfile = readdir( $DIR )) !== false ) {
            if( @is_link( $directory . '/' . $dirfile ) || $dirfile == '.' || $dirfile == '..' ) continue;
            if( @is_file( $directory . '/' . $dirfile ) ) $size += filesize( $directory . '/' . $dirfile );
            else if( @is_dir( $directory . '/' . $dirfile ) ) {
                $dirSize = dirsize( $directory . '/' . $dirfile );
                if( $dirSize >= 0 ) $size += $dirSize;
                else return - 1;
            }
        }
        closedir( $DIR );
    }
    return $size;
}

function check_login($username, $md5_password, $post = true) {
    global $member_id, $db, $user_group, $lang, $_IP, $_TIME, $config;
	
    if( $username == "" OR $md5_password == "" ) return false;
	$result = false;
	
	if( $post ) {
		$username = $db->safesql( $username );
		$md5_password = md5( $md5_password );

        if ( preg_match( "/[\||\'|\<|\>|\"|\!|\?|\$|\@|\/|\\\|\&\~\*\+]/", $username) ) return false; $where_name = "name='{$username}'";

        $member_id = $db->super_query( "SELECT * FROM " . USERPREFIX . "_users WHERE {$where_name} AND password='{$md5_password}'" );
		
		if( $member_id['user_id'] and $user_group[$member_id['user_group']]['allow_admin'] and $member_id['banned'] != 'yes' ) $result = TRUE;
		else $member_id = array ();
	} else {
		
		$username = intval( $username );
		$md5_password = md5( $md5_password );
		
		$member_id = $db->super_query( "SELECT * FROM " . USERPREFIX . "_users WHERE user_id='$username'" );
		
        if( $member_id['user_id'] AND $member_id['password'] AND $member_id['password'] == $md5_password AND $user_group[$member_id['user_group']]['allow_admin'] AND $member_id['banned'] != 'yes' ) $result = TRUE;
      	else $member_id = array ();
	}
	
	if( $result ) {
		if( !allowed_ip( $row['allowed_ip'] ) ) {
			$member_id = array ();
			$result = false;
			set_cookie( "dle_user_id", "", 0 );
			set_cookie( "dle_name", "", 0 );
			set_cookie( "dle_password", "", 0 );
			set_cookie( "dle_hash", "", 0 );
			@session_destroy();
			@session_unset();
			set_cookie( session_name(), "", 0 );
			
			msg( "info", $lang['index_msge'], $lang['ip_block'] );
		}
	}
	return $result;
}

function mksize($bytes) {
    if ($bytes < 1000)
        return $bytes. " b";
    if ($bytes < 1000 * 1024)
        return number_format($bytes / 1024, 2) . " Kb";
    if ($bytes < 1000 * 1048576)
        return number_format($bytes / 1048576, 2) . " Mb";
    if ($bytes < 1000 * 1073741824)
        return number_format($bytes / 1073741824, 2) . " Gb";
    if ($bytes < 1000 * 1099511627776)
        return number_format($bytes / 1099511627776, 2) . " Tb";
    if ($bytes < 1000 * 1125899906842620)
        return number_format($bytes / 1125899906842620, 2) . " Pb";
    if ($bytes < 1000 * 1152921504606850000)
        return number_format($bytes / 1152921504606850000, 2) . " Eb";
}

function CheckCanGzip() {
	
	if( headers_sent() || connection_aborted() || ! function_exists( 'ob_gzhandler' ) || ini_get( 'zlib.output_compression' ) ) return 0;
	
	if( strpos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip' ) !== false ) return "x-gzip";
	if( strpos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip' ) !== false ) return "gzip";
	
	return 0;
}

function GzipOut() {
	global $Timer, $db;
	
	$ENCODING = CheckCanGzip();
	
	if( $ENCODING ) {
		$Contents = ob_get_contents();
		ob_end_clean();
		
		header( "Content-Encoding: $ENCODING" );
		
		$Contents = gzencode( $Contents, 1, FORCE_GZIP );
		echo $Contents;
		
		exit();
	} else {
		//      ob_end_flush(); 
		exit();
	}
}

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 allowed_ip($ip_array) {
	$ip_array = trim( $ip_array );
	
	if( $ip_array == "" ) {
		return true;
	}
	
	$ip_array = explode( "|", $ip_array );
	$db_ip_split = explode( ".", $_SERVER['REMOTE_ADDR'] );
	
	foreach ( $ip_array as $ip ) {
		
		$ip_check_matches = 0;
		$this_ip_split = explode( ".", trim( $ip ) );
		
		for($i_i = 0; $i_i < 4; $i_i ++) {
			if( $this_ip_split[$i_i] == $db_ip_split[$i_i] or $this_ip_split[$i_i] == '*' ) {
				$ip_check_matches += 1;
			}
		
		}
		if( $ip_check_matches == 4 ) return true;
	}
	return FALSE;
}

////////////////////////////////////////////////////////
// Function:     msg
// Description: Displays message to user


function msg($type, $title, $text, $back = FALSE) {
	global $lang;

	if( $back ) {
		$back = "<br /><br> <a class=main href=\"$back\">$lang[func_msg]</a>";
	}
	
	echoheader( $type, $title );
	
	echo <<<HTML
<div style="padding-top:5px;padding-bottom:2px;">
<table width="100%">
    <tr>
        <td width="4"><img src="system/skins/images/tl_lo.gif" width="4" height="4" border="0"></td>
        <td background="system/skins/images/tl_oo.gif"><img src="system/skins/images/tl_oo.gif" width="1" height="4" border="0"></td>
        <td width="6"><img src="system/skins/images/tl_ro.gif" width="6" height="4" border="0"></td>
    </tr>
    <tr>
        <td background="system/skins/images/tl_lb.gif"><img src="system/skins/images/tl_lb.gif" width="4" height="1" border="0"></td>
        <td style="padding:5px;" bgcolor="#FFFFFF">
<table width="100%">
    <tr>
        <td bgcolor="#EFEFEF" height="29" style="padding-left:10px;"><div class="navigation">{$title}</div></td>
    </tr>
</table>
<div class="unterline"></div>
<table width="100%">
    <tr>
        <td height="100" align="center">{$text} {$back}</td>
    </tr>
</table>
</td>
        <td background="system/skins/images/tl_rb.gif"><img src="system/skins/images/tl_rb.gif" width="6" height="1" border="0"></td>
    </tr>
    <tr>
        <td><img src="system/skins/images/tl_lu.gif" width="4" height="6" border="0"></td>
        <td background="system/skins/images/tl_ub.gif"><img src="system/skins/images/tl_ub.gif" width="1" height="6" border="0"></td>
        <td><img src="system/skins/images/tl_ru.gif" width="6" height="6" border="0"></td>
    </tr>
</table>
</div>
HTML;
	
	echofooter();
	exit();
}

function echoheader($image, $header_text) {
	global $PHP_SELF, $skin_header, $member_id, $user_group;
	
    $skin_header = str_replace( "{header-text}", $header_text, $skin_header );
   	$skin_header = str_replace( "{user}", $member_id['name'], $skin_header );
   	$skin_header = str_replace( "{group}", $user_group[$member_id['user_group']]['group_name'], $skin_header );
	
	echo $skin_header;
}

function echofooter() {
	
	global $PHP_SELF, $is_loged_in, $skin_footer;
	
	echo $skin_footer;

}

function listdir($dir) {
	
	$current_dir = opendir( $dir );
	while ( $entryname = readdir( $current_dir ) ) {
		if( is_dir( "$dir/$entryname" ) and ($entryname != "." and $entryname != "..") ) {
			listdir( "${dir}/${entryname}" );
		} elseif( $entryname != "." and $entryname != ".." ) {
			unlink( "${dir}/${entryname}" );
		}
	}
	@closedir( $current_dir );
	rmdir( ${dir} );
}


function totranslit( $var, $lower = true, $punkt = true ) {
    global $langtranslit;

   	if ( is_array($var) ) return "";
    if (!is_array ( $langtranslit ) OR !count( $langtranslit ) ) {
   	$langtranslit = array('à' => 'a', 'á' => 'b', 'â' => 'v', 'ã' => 'g', 'ä' => 'd', 'å' => 'e', '¸' => 'e', 'æ' => 'zh', 'ç' => 'z', 'è' => 'i', 'é' => 'y', 'ê' => 'k', 'ë' => 'l', 'ì' => 'm', 'í' => 'n', 'î' => 'o', 'ï' => 'p', 'ð' => 'r', 'ñ' => 's', 'ò' => 't', 'ó' => 'u', 'ô' => 'f', 'õ' => 'h', 'ö' => 'c', '÷' => 'ch', 'ø' => 'sh', 'ù' => 'sch', 'ü' => '', 'û' => 'y', 'ú' => '', 'ý' => 'e', 'þ' => 'yu', 'ÿ' => 'ya', "¿" => "yi", "º" => "ye",
                          'À' => 'A', 'Á' => 'B', 'Â' => 'V', 'Ã' => 'G', 'Ä' => 'D', 'Å' => 'E', '¨' => 'E', 'Æ' => 'Zh', 'Ç' => 'Z', 'È' => 'I', 'É' => 'Y', 'Ê' => 'K', 'Ë' => 'L', 'Ì' => 'M', 'Í' => 'N', 'Î' => 'O', 'Ï' => 'P', 'Ð' => 'R', 'Ñ' => 'S', 'Ò' => 'T', 'Ó' => 'U', 'Ô' => 'F', 'Õ' => 'H', 'Ö' => 'C', '×' => 'Ch', 'Ø' => 'Sh', 'Ù' => 'Sch', 'Ü' => '', 'Û' => 'Y', 'Ú' => '', 'Ý' => 'E', 'Þ' => 'Yu', 'ß' => 'Ya', "¯" => "yi", "ª" => "ye",);
    }

   	$var = trim( strip_tags( $var ) );
   	$var = preg_replace( "/\s+/ms", "-", $var );
   	$var = str_replace( "/", "-", $var );

   	$var = strtr($var, $langtranslit);

    if( $punkt ) {$var = preg_replace( "/[^a-z0-9\_\-.]+/mi", "", $var );}else{$var = preg_replace( "/[^a-z0-9\_\-]+/mi", "", $var );}

	$var = preg_replace( '#[\-]+#i', '-', $var );

	if( $lower ) {$var = strtolower( $var );}

    $var = str_ireplace( ".php", "", $var );
   	$var = str_ireplace( ".php", ".ppp", $var );

    if( strlen( $var ) > 50 ) {
   		$var = substr( $var, 0, 50 );
   		if( ($temp_max = strrpos( $var, '-' )) ) $var = substr( $var, 0, $temp_max );
   	}
	return $var;
}

// ********************************************************************************
// Show Radio
// ********************************************************************************
function showRadio($title = "", $description = "", $allow_name = "", $row = false){
	 global $f_lg;

		if ($row[$allow_name])
		{
			$o_value = "checked";

			$t_value = "";
		}

		else
		{
			$o_value = "";

			$t_value = "checked";
		}

		echo"<tr>
		<td style=\"padding:4px\" class=\"option\">
		<b>{$title}</b><br /><span class=small>{$description}</span>
		<td width=394 align=middle >
		<input type=\"radio\" name=\"save[{$allow_name}]\" {$o_value} value=\"1\">{$f_lg['yes']}
		<input type=\"radio\" name=\"save[{$allow_name}]\" {$t_value} value=\"0\">{$f_lg['no']}
		</tr><tr><td background=\"system/skins/images/mline.gif\" height=1 colspan=2></td></tr>";
	}

// ********************************************************************************
// showRow
// ********************************************************************************
	function showRow($title="", $description="", $field="")
	{
		echo"<tr>
		<td style=\"padding:4px\" class=\"option\">
		<b>$title</b><br /><span class=small>$description</span>
		<td width=394 align=middle >$field
		</tr><tr><td background=\"system/skins/images/mline.gif\" height=1 colspan=2></td></tr>";
		$bg = ""; $i++;
	}

// ********************************************************************************
// makeDropDown
// ********************************************************************************
	function makeDropDown($options, $name, $selected)
	{
		$output = "<select name=\"$name\">\r\n";

		foreach($options as $value => $description)
		{
			$output .= "<option value=\"$value\"";
			if($selected == $value){ $output .= " selected "; }
			$output .= ">$description</option>\n";
		}

		$output .= "</select>";

		return $output;
	}

function langdate($format, $stamp) {
	global $langdate;
	
	return strtr( @date( $format, $stamp ), $langdate );

}

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

    if ($mod == "addnews" OR $mod == "editnews")
   		$allow_list = explode( ',', $user_group[$member_id['user_group']]['cat_allow_addnews'] );
   	else
	    $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;&nbsp;';
	}
	
	if( isset( $cat_parentid ) ) {
		
		$root_category = @array_keys( $cat_parentid, $parentid );
		
		if( is_array( $root_category ) ) {
			
			foreach ( $root_category as $id ) {
				
				$category_name = $cat[$id];
				
				if( $allow_list[0] == "all" or in_array( $id, $allow_list ) ) {
					
					if( $spec_list[0] == "all" or in_array( $id, $spec_list ) ) $color = "black";
					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 . $category_name . '</option>';
				}
				
				$returnstring = CategoryNewsSelection( $categoryid, $id, $nocat, $sublevelmarker, $returnstring );
			}
		}
	}
	
	return $returnstring;
}

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

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

	$story = preg_replace( "'\[hide\](.*?)\[/hide\]'si", "", $story );
	$story = preg_replace( "'\[file=(.*?)\]'si", "", $story );
	$story = preg_replace( "'\[torrent=(.*?)\]'si", "", $story );
	$story = str_replace( "&nbsp;", " ", $story );
	
	$story = str_replace( '<br />', ' ', $story );
	$story = trim( strip_tags( $story ) );

	if( trim( $_REQUEST['meta_title'] ) != "" ) {
        $headers['title'] = trim( htmlspecialchars( strip_tags( stripslashes($_REQUEST['meta_title'] ) ) ) );
      	$headers['title'] = $db->safesql(str_replace( $fastquotes, '', $headers['title'] ));
	} else $headers['title'] = "";
	
	if( trim( $_REQUEST['descr'] ) != "" ) {
		$headers['description'] = substr( strip_tags( stripslashes( $_REQUEST['descr'] ) ), 0, 190 );
        $headers['description'] = $db->safesql( str_replace( $fastquotes, '', $headers['description'] ));
	} else {
		$story = str_replace( $fastquotes, '', $story );
		$headers['description'] = $db->safesql( substr( stripslashes($story), 0, 190 ) );
	}
	
	if( trim( $_REQUEST['keywords'] ) != "" ) {
		$headers['keywords'] = $db->safesql( str_replace( $fastquotes, " ", strip_tags( stripslashes( $_REQUEST['keywords'] ) ) ) );
	} else {
		$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 );
		$headers['keywords'] = $db->safesql( implode( ", ", $arr ) );
	}
	return $headers;
}

function get_groups($id = false) {
	global $user_group;
	
	$returnstring = "";
	
	foreach ( $user_group as $group ) {
		$returnstring .= '<option value="' . $group['id'] . '" ';
		
		if( is_array( $id ) ) {
			foreach ( $id as $element ) {
				if( $element == $group['id'] ) $returnstring .= 'SELECTED';
			}
		} elseif( $id and $id == $group['id'] ) $returnstring .= 'SELECTED';
		
		$returnstring .= ">" . $group['group_name'] . "</option>\n";
	}
	
	return $returnstring;

}

function permload($id) {
	
	if( $id == "" ) return;
	
	$data = array ();
	
	$groups = explode( "|", $id );
	foreach ( $groups as $group ) {
		list ( $groupid, $groupvalue ) = explode( ":", $group );
		$data[$groupid][1] = ($groupvalue == 1) ? "selected" : "";
		$data[$groupid][2] = ($groupvalue == 2) ? "selected" : "";
		$data[$groupid][3] = ($groupvalue == 3) ? "selected" : "";
	}
	return $data;
}

function check_xss() {
	$url = html_entity_decode( urldecode( $_SERVER['QUERY_STRING'] ) );
    $url = str_replace( "\\", "/", $url );

	if( $url ) {
        if( (strpos( $url, '<' ) !== false) || (strpos( $url, '>' ) !== false) || (strpos( $url, '"' ) !== false) || (strpos( $url, './' ) !== false) || (strpos( $url, '../' ) !== false) || (strpos( $url, '\'' ) !== false) || (strpos( $url, '.php' ) !== false) ) {
			if( $_GET['mod'] != "editnews" or $_GET['action'] != "list" ) die( "Hacking attempt!" );
		}
	}
	
	$url = html_entity_decode( urldecode( $_SERVER['REQUEST_URI'] ) );
    $url = str_replace( "\\", "/", $url );
	
	if( $url ) {
        if( (strpos( $url, '<' ) !== false) || (strpos( $url, '>' ) !== false) || (strpos( $url, '"' ) !== false) || (strpos( $url, '\'' ) !== false) ) {
			die( "Hacking attempt!" );
		}
	}
}

function clean_url($url) {
	
	if( $url == '' ) return;
	
    $url = str_replace( "http://", "", $url );
   	$url = str_replace( "https://", "", $url );
	if( strtolower( substr( $url, 0, 4 ) ) == 'www.' ) $url = substr( $url, 4 );
	$url = explode( '/', $url );
	$url = reset( $url );
	$url = explode( ':', $url );
	$url = reset( $url );
	
	return $url;
}

$domain_cookie = explode (".", clean_url( $_SERVER['HTTP_HOST'] ));
$domain_cookie_count = count($domain_cookie);
$domain_allow_count = -2;

if ( $domain_cookie_count > 2 ) {

	if ( in_array($domain_cookie[$domain_cookie_count-2], array('com', 'net', 'org') )) $domain_allow_count = -3;
	if ( $domain_cookie[$domain_cookie_count-1] == 'ua' ) $domain_allow_count = -3;
	$domain_cookie = array_slice($domain_cookie, $domain_allow_count);
}

$domain_cookie = "." . implode (".", $domain_cookie);

if( ip2long($_SERVER['HTTP_HOST']) != -1 AND ip2long($_SERVER['HTTP_HOST']) !== FALSE ) define( 'DOMAIN', null );
else define( 'DOMAIN', $domain_cookie );

function set_cookie($name, $value, $expires) {
	if( $expires ) {$expires = time() + ($expires * 86400);
	} else {$expires = FALSE;}

	if( PHP_VERSION < 5.2 ) {setcookie( $name, $value, $expires, "/", DOMAIN . "; HttpOnly" );
	} else {setcookie( $name, $value, $expires, "/", DOMAIN, NULL, TRUE );}
}

function get_url($id) {
	global $cat_info;
	if( ! $id ) return;
	$parent_id = $cat_info[$id]['parentid'];
	$url = $cat_info[$id]['alt_name'];
	while ( $parent_id ) {
		$url = $cat_info[$parent_id]['alt_name'] . "/" . $url;
		$parent_id = $cat_info[$parent_id]['parentid'];
		if( $cat_info[$parent_id]['parentid'] == $cat_info[$parent_id]['id'] ) break;
	}
	return $url;
}

function convert_unicode($t, $to = 'windows-1251') {
	$to = strtolower( $to );

	if( $to == 'utf-8' ) {
        return $t;
	} else {
		if( function_exists( 'iconv' ) ) $t = iconv( "UTF-8", $to . "//IGNORE", $t );
		else $t = "The library iconv is not supported by your server";
	}
	return $t;
}

function check_netz($ip1, $ip2) {
	
	$ip1 = explode( ".", $ip1 );
	$ip2 = explode( ".", $ip2 );
	
	if( $ip1[0] != $ip2[0] ) return false;
	if( $ip1[1] != $ip2[1] ) return false;
	
	return true;

}

function compare_filter($a, $b) {
	
	$a = explode( "|", $a );
	$b = explode( "|", $b );
	
	if( $a[1] == $b[1] ) return 0;
	
	return strcasecmp( $a[1], $b[1] );

}
?>