<?php

/********************************************************************************
	- MemHT Portal -

	Copyright (C) 2007-2008 by Miltenovik Manojlo
	http://www.memht.com

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your opinion) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License along
	with this program; if not, see <http://www.gnu.org/licenses/> (GPLv2)
	or write to the Free Software Foundation, Inc., 51 Franklin Street,
	Fifth Floor, Boston, MA02110-1301, USA.

********************************************************************************/

if (stristr(htmlentities($_SERVER['PHP_SELF']), "inc_functions.php")) {
	die("<table style='padding: 2px; border: 1px solid #999; background-color: #EEE; font-family: Verdana; font-size: 10px;' align='center'><tr><td><b>Error:</b> This file cannot be opened directly!</td></tr></table>");
}

function getAvatar($uid=false) {
	global $dblink,$userInfo;

	if ($uid!==false) {
  		$row = $dblink->get_row("SELECT avatar,user,email FROM memht_utenti WHERE id=".intval($uid));
		$avat = outCode($row['avatar']);
  		$gravatar = (!empty($avat)) ? outCode($row['avatar']) : outCode($row['email']) ;
		$img = "http://www.gravatar.com/avatar/".md5($gravatar)."?s=80&amp;r=g";
		$username = outCode($row['user']);
	} else {
		$gravatar = (!empty($userInfo['avatar'])) ? $userInfo['avatar'] : $userInfo['email'] ;
		$img = "http://www.gravatar.com/avatar/".md5($gravatar)."?s=80&amp;r=g";
		$username = $userInfo['user'];
	}
	return "<img src='$img' title='$username' alt='$username'>";
}

if (isset($_GET['newlang'])) {
	$newlang = inCode($_GET['newlang']);
	if (validate($newlang)) {
		if ($newlang != "reset") {
			setcookie("language",$newlang,time()+31536000); //1year
		} else {
			setcookie("language","",time()-31536000); //-1year
		}
		header("Location: index.php");
	}
}

if (isset($_GET['newtemplate'])) {
	$newtemplate = inCode($_GET['newtemplate']);
	if (validate($newtemplate)) {
		if ($newtemplate != "reset") {
			setcookie("template",$newtemplate,time()+31536000); //1year
		} else {
			setcookie("template","",time()-31536000); //-1year
		}
		header("Location: index.php");
	}
}

if (isset($_GET['changerss'])) {
	if (isAuth($userid,3)) {
		$changerss = intval($_GET['changerss']);
		$dblink->query("UPDATE memht_rssreader_links SET inblock=0");
		$dblink->query("UPDATE memht_rssreader_links SET inblock=1 WHERE id=$changerss");
	}
}

//===========================================
//Security
//===========================================

if (preg_match("`http`is",@$_SERVER['QUERY_STRING'])) { die(); }

//Query string protection (Unknown author)
if(isset($_SERVER['QUERY_STRING'])) {
	$qS = $_SERVER['QUERY_STRING'];
	if (stc($qS,'%20union%20')
	OR stc($qS,'/*')
	OR stc($qS,'*/union/*')
	OR stc($qS,'c2nyaxb0')
	OR stc($qS,'+union+')
	OR stc($qS,'http://')
	//OR stc($qS,'www')
	OR (stc($qS,'cmd=') AND !stc($qS,'&cmd'))
	OR (stc($qS,'exec') AND !stc($qS,'execu'))
	OR stc($qS,'concat')) {
		die("<table style='padding: 2px; border: 1px solid #999; background-color: #EEE; font-family: Verdana; font-size: 10px;' align='center'><tr><td><b>Illegal Operation:</b> Query not allowed.</td></tr></table>");
	}
}
//Post protection (Unknown author) [MAY BE DISABLED]
if (@$_SERVER['REQUEST_METHOD']=="POST") {
	if (isset($_SERVER['HTTP_REFERER'])) {
    	if (!stc($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'])) {
			die("<table style='padding: 2px; border: 1px solid #999; background-color: #EEE; font-family: Verdana; font-size: 10px;' align='center'><tr><td><b>Illegal Operation:</b> Posting allowed only from main server.</td></tr></table>");
    	}
  	}
}
function stc($haystack, $needle, $offset=0) {
	return strpos(strtoupper($haystack), strtoupper($needle), $offset);
}

//Initialize configuration and language
$row_conf = $dblink->get_row("SELECT * FROM memht_config");
if (isset($_COOKIE['language'])) { $siteConfig['language'] = preg_replace('`[^a-zA-Z]`is','',$_COOKIE['language']); } else { $siteConfig['language'] = outCode($row_conf['lingua']); }

//Control if the page name is valid
if (isset($_GET['page'])) {
	if (preg_match("`[^0-9a-zA-Z_-]`is",$_GET['page'])) {
		die("<table style='padding: 2px; border: 1px solid #999; background-color: #EEE; font-family: Verdana; font-size: 10px;' align='center'><tr><td><b>Illegal Operation:</b> Special chars in page name not allowed.</td></tr></table>");
	}
	$page = inCode($_GET['page']);
}

//Check if there are special chars in the string
function checkCode($code) {
	return (preg_match("`^[0-9a-zA-Z_-]*$`is",$code)) ? true : false ;
}

//Clean special chars and code tags from the string
function cleanCode($str) {
	//<>/\?&`~!@#$%^*()[]|;:"'
	$str = strip_tags($str); //Clean HTML tags
	$str = preg_replace("`[<>/\?&`~@#\$%\^*']`is","",$str); //Clean special chars

	return $str;
}

//Data input function (from user)
function inCode($string,$indb=1) {
	if (get_magic_quotes_gpc()) { $string = stripslashes($string); }
	$string = str_replace('<br type="_moz" />','',$string); //FCKeditor 2.5.1 bug fix
	if ($string=="<br />") { $string = ""; } //FCKeditor 2.5.1 bug fix
	$string = preg_replace("`UNION.SELECT|INTO.OUTFILE`is","",$string);
	$string = htmlentities($string,ENT_QUOTES);
	return ($indb==1) ? mysql_real_escape_string($string) : addslashes($string) ;
}

//Data output function (from database)
function outCode($string,$html=1) {
	global $langdata;

	$string = ($html==1) ? unhtmlentities($string) :  stripslashes($string) ;
	$string = str_replace('\"','"',$string);
	$string = str_replace("\'","'",$string);
	$string = str_replace("&amp;","&",$string);

	if (!preg_match("`admin.php`is",$_SERVER['PHP_SELF']) AND $html==1) {
		//Extract [code]...[/code]
		preg_match_all('`\[code\](.+?)\[/code\]`is',$string,$outstr,PREG_PATTERN_ORDER);
		$numcodes = count($outstr[0]);
		$string_cleaned = $string;
		for ($a=0;$a<=$numcodes;$a++) {
			$string_cleaned = preg_replace('`\[code\](.+?)\[/code\]`is','___CODE_'.$a.'___',$string_cleaned,1);
		}
		//Restore [code]...[/code]
		$string = $string_cleaned;
		for ($a=0;$a<$numcodes;$a++) {
			$outstr[1][$a] = str_replace("&#039;","'",str_replace("<br />","",$outstr[1][$a]));
			$string = preg_replace('#(___CODE_)('.$a.')(___)#ise',"'<div class=\"std_code\"><div style=\"overflow:auto; max-width:500px; width:expression(document.body.clientWidth > 400? \'400px\': \'auto\' );\">'.highlightcode(\$outstr[1][$a]).'</div></div>'",$string,1);
		}
	}

	//Language chars fix
	if (isset($langdata['char_pat']) AND @sizeof($langdata['char_pat']) == @sizeof($langdata['char_rep'])) {
		$string = str_replace($langdata['char_pat'],$langdata['char_rep'],$string);
	}

	return $string;
}

//VIRTUAL PAGES OUTPUT, DO NOT USE FOR ANY OTHER PURPOSES!!!
//Added in 3.8.0
function outCodeVP($string) {
	$string = unhtmlentitiesVP($string) ;
	$string = str_replace('\"','"',$string);
	$string = str_replace("\'","'",$string);
	$string = str_replace("&amp;","&",$string);

	return $string;
}
//VIRTUAL PAGES OUTPUT, DO NOT USE FOR ANY OTHER PURPOSES!!!
//Added in 3.8.0
function unhtmlentitiesVP($string) {
	$trans_tbl1 = get_html_translation_table(HTML_ENTITIES);
	foreach ($trans_tbl1 as $ascii => $htmlentitie) {
		$trans_tbl2[$ascii] = '&#'.ord($ascii).';';
	}
	$string = str_replace("&#039;","'",$string);
	$string = str_replace("&#39;","'",$string);

	$trans_tbl1 = array_flip($trans_tbl1);
	$trans_tbl2 = array_flip($trans_tbl2);

	$string = strtr(strtr($string,$trans_tbl1),$trans_tbl2);
	return $string;
}

function unhtmlentities($string,$html=1) {
	$trans_tbl1 = get_html_translation_table(HTML_ENTITIES);
	foreach ($trans_tbl1 as $ascii => $htmlentitie) {
		$trans_tbl2[$ascii] = '&#'.ord($ascii).';';
	}

	$trans_tbl1 = array_flip($trans_tbl1);
	$trans_tbl2 = array_flip($trans_tbl2);

	$tagstostrtip = array('iframe','script','style');
	$string = strtr(strtr($string,$trans_tbl1),$trans_tbl2);
	if ($html==1) { $string = strip_selected_tags($string,$tagstostrtip); }
	return $string;
}

function strip_selected_tags($text, $tags = array()) {
	$args = func_get_args();
	$text = array_shift($args);
	$tags = func_num_args() > 2 ? array_diff($args,array($text)) : (array)$tags;
	foreach ($tags as $tag){
		if(preg_match_all('/<'.$tag.'[^>]*>([^<]*)<\/'.$tag.'>/iu',$text,$found) ){
			$text = str_replace($found[0],$found[1],$text);
		}
	}
	return @$text;
}

function urlToLink($text) {
	return preg_replace('/([^"\'>])([hf][tps]{2,4}:\/\/[^\\s<>"\'()]{4,})/i', '$1<a href="$2">$2</a>',$text);
}

function highlightcode($code) {
	if (memRunHooks('HighlightCode',array(&$code))) {
		include_once('inc/geshi/geshi.php');

		$code = str_replace("&gt;n&quot;",">\\n\"",$code);
		$code = unhtmlentities($code,0); // /!\ USE WITH GESHI HIGHLIGHTER ONLY /!\

		$geshi =& new GeSHi($code,'php');
		$geshi->set_header_type(GESHI_HEADER_NONE);
		$geshi->enable_keyword_links(false);
		$code = $geshi->parse_code();

		memRunHooks('HighlightCodeEnd',array(&$code));
	}
	return $code;
}

//Added in 3.8.5
//Thanks to paulo89, JPappi and BLaCk.DeWiL for their help with chars
function mem_urlencode($str) {
	global $langdata;

	if (isset($langdata['url_pat']) AND @sizeof($langdata['url_pat']) == @sizeof($langdata['url_rep'])) {
		$str = preg_replace($langdata['url_pat'],$langdata['url_rep'],$str);
	}
	$patterns = array(
		'`[ +_\.]`is',
		'`([!?"“”\'\[\]:\(\)=<>,])|(&quot;|&#039;|&lt;|&gt;)`is',
		'`[èé]`is',
		'`[òó]`is',
		'`[àáã]`is',
		'`[ùúü]`is',
		'`[ìíýÝ]`is',
		'`ç`is',
		'`ä`is',
		'`Ä`is',
		'`Ü`is',
		'`ö`is',
		'`Ö`is',
		'`ß`is',
		'`ð`is',
		'`þ`is',
		'`Þ`is',
		'`Ç`is',
        '`Ð`is'
	);
	$replaces =  array(
		'-',
		'',
		'e',
		'o',
		'a',
		'u',
		'i',
		'c',
		'ae',
		'Ae',
		'Ue',
		'oe',
		'Oe',
		'ss',
		'g',
		's',
		'S',
        'C',
        'G'
	);
	return urlencode(preg_replace($patterns,$replaces,$str));
}

//Added in 3.8.5
function mem_urldecode($str) {
	return urldecode($str);
}

//===========================================
//Validation / Check
//===========================================

//Return the visitor rank
function myRank() {
	global $dblink,$userid,$userInfo;

	/*
	RANKS
	0 = Guest
	1 = Normal user
	2 = Power user (normal user + permission to access admin pages)
	3 = Admin (power user + power in the site front-edit)
	4 = Superadmin (full power)
	*/

	if (isset($userInfo['rank'])) {
		return $userInfo['rank'];
	} else {
		$row = $dblink->get_row("SELECT rank FROM memht_utenti WHERE id=$userid");
		return intval($row['rank']);
	}
}

function isAuth($userid,$rank=0) {
	global $dblink,$privs;

	/*
	RANKS
	0 = Guest
	1 = Normal user
	2 = Power user (normal user + permission to access admin pages)
	3 = Admin (power user + power in the site front-edit)
	4 = Superadmin (full power)
	*/

	if (memRunHooks('IsAuth',array($userid,$rank,&$privs))) {
		if (!$privs['user']) { return 0; }
		return ($dblink->get_num("SELECT id FROM memht_utenti WHERE id=$userid AND rank>=$rank")>0) ? true : false ;
	}
}

//DEPRECATED in 4.0.1
function isAdmin($usert) {
		global $userid;

		return (isAuth($userid,3)) ? true : false;
}

//Check if the visitor is logged as user
function isUser($userid,$force=0) {
	global $dblink,$privs;

	if (memRunHooks('IsUser',array($userid,$force,&$privs))) {
		if (isset($_COOKIE['login_user'])) {
			$cookiecontent = $_COOKIE['login_user'];
			$cookieitem = explode("#",$cookiecontent);

			if ($privs['user']) {
				$pcookieitem = explode("#",$privs['user']);
				if ($cookieitem[0]==$pcookieitem[0] AND $cookieitem[1]==$pcookieitem[1] AND $cookieitem[2]==$pcookieitem[2]) {
					return true;
				} else {
					$privs['user'] = false;
					return false; //Error? Hack?
				}
			} else if ($force==1) {
				//Database Account Control
				if ($dblink->get_num("SELECT id FROM memht_utenti WHERE id=$userid AND pass='".inCode($cookieitem[2])."' LIMIT 1")>0) {
					$privs['user'] = $cookiecontent;
					return true; //Account Correct
				} else {
					$privs['user'] = false;
					return false; //Error? Hack?
				}
			} else {
				return false;
			}
		} else {
			return false; //Not Logged
		}
		return false;
	}
}

//Generic validation function
function validate($string,$regex='^[^<>]*$') {
	if ($regex=="url") { $regex = "^[http://]*[a-zA-Z0-9~\._-]*\.*[a-zA-Z0-9~\._-]*\.[A-Za-z]{2,4}/*[a-zA-Z0-9?\.+&@#/\=~_|-]*"; }
	return (preg_match("`".$regex."`is",$string)) ? true : false ;
}

//Check if the username if valid (content and length)
function validUser($usert) {
	global $dblink,$siteConfig;

	if (preg_match("`^([^<>\'\"`%\$\\\/#\,]{4,".$siteConfig['user_max_lunghezza']."})$`is",$usert)) {
		return ($dblink->get_num("SELECT user FROM memht_utenti_vietati WHERE user='$usert'")) ? false : true ;
	} else {
		return false;
	}
}

//Check if the password if valid (content and length)
function validPass($pass) {
	global $siteConfig;

	return (preg_match("`^([^<>\'\"`%\$\\\/#\,]{4,".$siteConfig['pass_max_lunghezza']."})$`is",$pass)) ? true : false ;

}

//Check if the email is valid
function validEmail($email) {
	global $dblink;

	if ($email=="") { return false; }
	$domain = @explode("@",$email);
	$domain = @$domain[1];

	return (!preg_match("`^([a-zA-Z0-9~\._-]{2,})(@{1}[a-zA-Z0-9~\._-]{2,})(\.{1}[a-zA-Z]{2,4})$`is",$email) OR deep_in_array($domain,$dblink->get_list("SELECT domain FROM memht_email_nodomain"),true)) ? false : true ;
}

//Check if the ip if valid [SHOULD BE IMPROOVED]
function validIp($ip) {
	return (preg_match("`^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$`is",$ip)) ? true : false ;
}

//Check if the page is already installed in the database
function pageInstalled($paget) {
	global $dblink;

	return ($dblink->get_num("SELECT id FROM memht_pagine WHERE nome='$paget'")) ? true : false ;
}

//Check if the IP is in the range
function ipInRange($ip,$rangefrom,$rangeto) {
	$ip = explode(".",$ip);
	$rangefrom = explode(".",$rangefrom);
	$rangeto = explode(".",$rangeto);
	if (($ip[0]>=$rangefrom[0] AND $ip[0]<=$rangeto[0]) AND
		($ip[1]>=$rangefrom[1] AND $ip[1]<=$rangeto[1]) AND
		($ip[2]>=$rangefrom[2] AND $ip[2]<=$rangeto[2]) AND
		($ip[3]>=$rangefrom[3] AND $ip[3]<=$rangeto[3])) {
		return true;
	} else {
		return false;
	}
}

//Check if the IP is in the spider db table, return spider name if true
function isSpider($ip) {
	global $dblink;

	return (validIp($ip) AND $row = $dblink->get_row("SELECT spidname FROM memht_spider_ranges WHERE '".ip2num($ip)."' BETWEEN fromip AND toip")) ? outCode($row['spidname']) : false ;
}

function addToGroups($type=2) {
	global $dblink,$tzNOW,$userid;

	//================
	// TYPE
	//----------------
	// 0 = Manual
	// 1 = Posts
	// 2 = Contributes
	//----------------

	if ($type==0) { return; }
	if ($result = $dblink->get_list("SELECT id,amount FROM memht_groups WHERE type=$type")) {
		if ($dblink->get_num("SELECT id FROM memht_groups_blacklist WHERE user=$userid")>0) { return; }
		foreach ($result as $row) {
			$gid = intval($row['id']);
			$amount = intval($row['amount']);

			switch ($type) {
				case 1:
					if ($dblink->get_num("SELECT id FROM memht_utenti WHERE id=$userid AND post>=$amount")>0) {
						if ($dblink->get_num("SELECT id FROM memht_groups_members WHERE groupid=$gid AND user=$userid")==0) {
							$dblink->query("INSERT INTO memht_groups_members (groupid,user,permanent,joined,type,note)
											VALUES ('$gid','$userid','1',$tzNOW,'1','Added by the system')");
						}
					}
				break;
				case 2:
					if ($dblink->get_num("SELECT id FROM memht_utenti WHERE id=$userid AND contributes>=$amount")>0) {
						if ($dblink->get_num("SELECT id FROM memht_groups_members WHERE groupid=$gid AND user=$userid")==0) {
							$dblink->query("INSERT INTO memht_groups_members (groupid,user,permanent,joined,type,note)
											VALUES ('$gid','$userid','1',$tzNOW,'2','Added by the system')");
						}
					}
				break;
			}
		}
	}
}

//===========================================
//Maintenance
//===========================================
class Maintenance {
	//Override timings, forcing the execution
	var $forcedexec = false;

	//Call all class functions
	function All() {
		global $dblink,$siteConfig,$tzNOW;

		if ($dblink->get_num("SELECT last FROM memht_maintenance")==0) { $dblink->query("INSERT INTO memht_maintenance (last) VALUES ('2000-01-01 00:00:00')"); }
		if ($this->forcedexec OR $dblink->get_num("SELECT last FROM memht_maintenance WHERE (last + INTERVAL ".$siteConfig['maintenance']." MINUTE) < $tzNOW")>0) {
			$dblink->query("UPDATE memht_maintenance SET last=$tzNOW");

			if (memRunHooks('Maintenance',array($this->forcedexec))) {
				$this->CleanBanned();
				$this->MessageBoxFlood();
				$this->OldWaitingUsers();
				$this->OldPrivateMessages();
				$this->OldLoginAttempts();
				$this->GroupMembers();
				$this->ResetMediumLoadTime();
				$this->DeleteOldLiveData();
				$this->DeleteOldAdminData();
				$this->DeleteRssCache();
				$this->RssAggregator();
				$this->CleanStatistics();

				memRunHooks('MaintenanceEnd',array($this->forcedexec));
			}
		}
	}

	//Clean the database from extinguished temporary ban's
	function CleanBanned() {
		global $dblink,$tzNOW;

		$dblink->query("DELETE FROM memht_banned WHERE date < $tzNOW AND permanent=0");
	}

	//Clean messagemox flood data
	function MessageBoxFlood() {
		global $dblink,$siteConfig,$tzNOW;

		$dblink->query("DELETE FROM memht_messagebox_flood WHERE (time + INTERVAL ".$siteConfig['maintenance_mesboxflood']." MINUTE) < $tzNOW");
	}

	//Clean old pending user registrations
	function OldWaitingUsers() {
		global $dblink,$siteConfig,$tzNOW;

		$dblink->query("DELETE FROM memht_utenti_attesa WHERE activated=0 AND (data + INTERVAL ".$siteConfig['maintenance_waitusers']." HOUR) < $tzNOW");
		$dblink->query("DELETE FROM memht_utenti_attesa WHERE activated=1 AND (data + INTERVAL 3 MONTH) < $tzNOW");
	}

	//Clean old private messages
	function OldPrivateMessages() {
		global $dblink,$siteConfig,$tzNOW;

		$dblink->query("DELETE FROM memht_pvtmsg WHERE (date + INTERVAL ".$siteConfig['maintenance_oldpm']." DAY) < $tzNOW");
	}

	//Clean old login attempts
	function OldLoginAttempts() {
		global $dblink,$siteConfig,$tzNOW;

		$dblink->query("DELETE FROM memht_login_flood WHERE (time + INTERVAL ".$siteConfig['maintenance_failedlogin']." MINUTE) < $tzNOW");
	}

	//Clean expired group members
	function GroupMembers() {
		global $dblink,$siteConfig,$tzNOW;

		$dblink->query("UPDATE memht_groups_members SET standby=1 WHERE permanent=0 AND standby=0 AND expire < $tzNOW");
		$dblink->query("DELETE FROM memht_groups_members WHERE permanent=0 AND standby=1 AND (expire + INTERVAL ".$siteConfig['maintenance_standbygroup']." DAY) < $tzNOW");
	}

	function DeleteOldLiveData() {
		global $dblink,$siteConfig,$tzNOW;

		$dblink->query("DELETE FROM memht_statistics_livedata WHERE (date + INTERVAL 12 HOUR) < $tzNOW");
	}

	function DeleteOldAdminData() {
		global $dblink,$siteConfig,$tzNOW;

		$dblink->query("DELETE FROM memht_statistics_administration WHERE (date + INTERVAL 7 DAY) < $tzNOW");
	}

	//Reset medium load time
	function ResetMediumLoadTime() {
		global $dblink,$siteConfig,$tzNOW;

		$dblink->query("DELETE FROM memht_statistics_loadtime WHERE (started + INTERVAL ".$siteConfig['maintenance_loadtime']." HOUR) < $tzNOW");
	}

	//Delete RSS chache
	function DeleteRssCache() {
		global $dblink;

		if (@count(@glob("inc/magpie/cache/*", GLOB_BRACE))>20) {
			$limit = 0;
			$over = 0;
			$handle = @opendir('inc/magpie/cache/');
			while (false !== ($file = @readdir($handle))) {
				if ($limit>20 OR $over>20) { break; }
				if ($file != "." AND $file != "..") {
					@unlink("inc/magpie/cache/$file");
					$limit++;
				}
				$over++;
			}
			@closedir($handle);
		}
	}

	//Rss Aggregator
	function RssAggregator() {
		global $dblink,$tzNOW;

		if ($dblink->get_num("SELECT id FROM memht_aggregator WHERE enabled=1")>0) {
			if ($dblink->get_num("SELECT maintenance_aggregator FROM memht_maintenance WHERE (maintenance_aggregator + INTERVAL 1 HOUR) < $tzNOW")>0) {
				$dblink->query("UPDATE memht_maintenance SET maintenance_aggregator=$tzNOW");
				$result = $dblink->get_list("SELECT * FROM memht_aggregator");
				foreach ($result as $row) {
					$whr = intval($row['whr']);
					$argument = intval($row['argument']);
					$author = outCode($row['author']);
					$rssurl = outCode($row['rssurl']);
					$numfeeds = intval($row['numfeeds']);
					if (!defined('MAGPIE_CACHE_DIR')) { define('MAGPIE_CACHE_DIR','inc/magpie/cache'); }
					require_once("inc/magpie/rss_fetch.inc");
					if ($rss = @fetch_rss($rssurl)) {
						$channel = inCode($rss->channel['title']);
						$items = array_reverse($rss->items);
						$lim = 0;
						foreach ($items as $item) {
							if ($lim>=$numfeeds) { break; }
							$link = inCode(@$item['link']);
							$title = inCode(@$item['title']);
							$description = inCode(@$item['description']);
							$encoded = inCode(@$item['content']['encoded']);
							if (strlen($link)>4 AND strlen($title)>4 AND strlen($description)>10) {
								$more = "Source: <a href=\"$link\" target=\"_blank\" title=\"$channel\"><i>$channel</i></a>";
								if ($author=="") { $author = $channel; }
								//1 = Articles, 2 = Guide, 3 = News
								switch ($whr) {
									case 1:
										if ($encoded!="") {
											$desc = $description;
											$description = $encoded;
										} else {
											$desc = "";
										}
										$rssquery = "INSERT INTO memht_articoli (id,argomento,nome,descrizione,testo,autore,data,enabled) VALUES ";
										$rssquery .= "(null,'$argument','$title','$desc','$description<br><br>$more','$author',$tzNOW,'1')";
										$checkquery = "SELECT id FROM memht_articoli WHERE nome='$title'";
									break;
									case 2:
										if ($encoded!="") {
											$desc = $description;
											$description = $encoded;
										} else {
											$desc = "";
										}
										$rssquery = "INSERT INTO memht_guide (id,argomento,nome,descrizione,testo,autore,data,enabled) VALUES ";
										$rssquery .= "(null,'$argument','$title','$desc','$description<br><br>$more','$author',$tzNOW,'1')";
										$checkquery = "SELECT id FROM memht_guide WHERE nome='$title'";
									break;
									case 3:
										$encoded = ($encoded=="") ? $more : $encoded."<br><br>".$more ;
										$rssquery = "INSERT INTO memht_news (id,argomento,nome,testo_home,testo,autore,data,enabled) VALUES ";
										$rssquery .= "(null,'$argument','$title','$description','$encoded','$author',$tzNOW,'1')";
										$checkquery = "SELECT id FROM memht_news WHERE nome='$title'";
									break;
								}
								if ($dblink->get_num($checkquery)==0) { $dblink->query($rssquery); $lim++; }
							}
						}
					}
				}
			}
		}
	}

	//Clean statistics data
	//Added in 3.8.0
	function CleanStatistics() {
		global $dblink,$tzNOW;

		//memht_statistics_browsers
		$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_browsers WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_browsers WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_browsers WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");

		//memht_statistics_domains
		$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_domains WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_domains WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_domains WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");

		//memht_statistics_os
		$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_os WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_os WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_os WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");

		//memht_statistics_pages
		$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_pages WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_pages WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_pages WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");

		//memht_statistics_screenres
		$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_screenres WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_screenres WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_screenres WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");

		//memht_statistics_searchengines
		$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_searchengines WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_searchengines WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_searchengines WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");

		//memht_statistics_searchkeywords
		$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_searchkeywords WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_searchkeywords WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_searchkeywords WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");

		//memht_statistics_users
		$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_users WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_users WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
		$dblink->query("DELETE FROM memht_statistics_users WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");

		//memht_statistics_spiders
		$dblink->query("DELETE FROM memht_statistics_spiders WHERE (lastvisit + INTERVAL 1 WEEK) < $tzNOW");
	}
}

//Rewritten in 4.0.5
function sendNewsletter() {
	global $dblink,$siteConfig,$tzNOW;

	if (memRunHooks('SendNewsletter')) {
		if ($srow = $dblink->get_row("SELECT * FROM memht_newsletter_status")) {
			//Unfinished newsletter session
			$crow = $dblink->get_row("SELECT * FROM memht_newsletter_config");
			$aut_mailpause = intval($crow['aut_mailpause']);

			if ($dblink->get_num("SELECT date FROM memht_newsletter_status WHERE (date + INTERVAL $aut_mailpause MINUTE) < $tzNOW")>0) {
				//Check busy status
				$proceed = true;
				if ($dblink->get_num("SELECT busy FROM memht_newsletter_busy WHERE busy=0")==0) {
					//Busy
					$proceed = false;
					if ($dblink->get_num("SELECT busy FROM memht_newsletter_busy WHERE busy=1 AND (date + INTERVAL 5 MINUTE) < $tzNOW")>0) {
						//Stuck > Reset
						$dblink->query("TRUNCATE memht_newsletter_busy");
						$dblink->query("INSERT INTO memht_newsletter_busy (busy,date) VALUES (0,$tzNOW)");
						$dblink->query("UPDATE memht_newsletter_status SET date=$tzNOW");
					}
				}

				if ($proceed) {
					//Set busy
					$dblink->query("UPDATE memht_newsletter_busy SET busy=1,date=$tzNOW");

					//Config
					$sender_mail = outCode($crow['email_mittente']);
					$mailorsmtp = intval($crow['mailorsmtp']);
					$smtp = outCode($crow['smtp']);
					$useauth = intval($crow['useauth']);
					$smtpuser = outCode($crow['smtpuser']);
					$smtppass = outCode($crow['smtppass']);
					$aut_mailpersession = intval($crow['aut_mailpersession']);

					//Status
					$title = outCode($srow['title']);
					$content = outCode($srow['content']);
					$emails = intval($srow['emails']);

					require_once("inc/class/class.phpmailer.php");
					$mail = new PHPMailer();
					$mail->From = $sender_mail;
					$mail->FromName = $siteConfig['site_name'];
					$mail->Subject = $title;
					if ($mailorsmtp==1) {
						//Smtp
						$mail->Host = $smtp;
						$mail->Mailer = "smtp";
						if ($useauth) {
							$mail->SMTPAuth = true;
							$mail->Username = $smtpuser;
							$mail->Password = $smtppass;
						}
					} else {
						//Mail
						$mail->Mailer = "mail";
					}
					$mail->IsHTML(true);
					$mail->Body = $content;

					if ($result = $dblink->get_list("SELECT id,email FROM memht_newsletter WHERE sent=0 ORDER BY id LIMIT $aut_mailpersession")) {
						$count = 0;
						foreach ($result as $row) {
							$id = intval($row['id']);
							$email = outCode($row['email']);

							$dblink->query("UPDATE memht_newsletter SET sent=1,date=$tzNOW WHERE id=$id");

							$mail->AddAddress($email);
							$mail->Send();
							$mail->ClearAddresses();
							$count++;
						}

						//Update status
						$dblink->query("UPDATE memht_newsletter_status SET date=$tzNOW,emails=emails+$count");
					} else {
						//No more emails
						$dblink->query("TRUNCATE memht_newsletter_status");
						$dblink->query("INSERT INTO memht_newsletter_sent (title,content,date,numemails) VALUES ('".inCode($title)."','".inCode($content)."',$tzNOW,$emails)");
					}

					//Finished
					$dblink->query("UPDATE memht_newsletter_busy SET busy=0,date=$tzNOW");
				}
			}
		}

		memRunHooks('SendNewsletterEnd');
	}
}

//===========================================
//Various
//===========================================

//Convert from bytes to formatted string
function strSize($bytes) {
	if ($bytes<1024) {
		return "$bytes byte";
	} else {
		$kb = $bytes / 1024;
		if ($kb<1024) {
			return sprintf("%01.2f", $kb)." Kb";
		} else {
			$mb = $kb / 1024;
			if ($mb<1024) {
				return sprintf("%01.2f", $mb)." Mb";
			} else {
				$gb = $mb / 1024;
					return sprintf("%01.2f", $gb)." Gb";
			}
		}
	}
}

//Return the image corresponding to the os
function os2img($os) {
	if (preg_match("`Windows Vista`is",$os)) { $img = "<img src='images/os/win.gif' border='0' title='Windows Vista' alt='Windows Vista'>"; }
	else if (preg_match("`Windows XP`is",$os)) { $img = "<img src='images/os/win.gif' border='0' title='Windows XP' alt='Windows XP'>"; }
	else if (preg_match("`Windows`is",$os)) { $img = "<img src='images/os/win.gif' border='0' title='Windows' alt='Windows'>"; }
	else if (preg_match("`Macintosh`is",$os)) { $img = "<img src='images/os/mac.gif' border='0' title='Mac' alt='Mac'>"; }
	else if (preg_match("`FreeBSD`is",$os)) { $img = "<img src='images/os/freebsd.gif' border='0' title='FreeBSD' alt='FreeBSD'>"; }
	else if (preg_match("`SunOS`is",$os)) { $img = "<img src='images/os/sunos.gif' border='0' title='SunOS' alt='SunOS'>"; }
	else if (preg_match("`IRIX`is",$os)) { $img = "<img src='images/os/irix.gif' border='0' title='IRIX' alt='IRIX'>"; }
	else if (preg_match("`BeOS`is",$os)) { $img = "<img src='images/os/beos.gif' border='0' title='BeOS' alt='BeOS'>"; }
	else if (preg_match("`OS/2`is",$os)) { $img = "<img src='images/os/os2.gif' border='0' title='OS/2' alt='OS/2'>"; }
	else if (preg_match("`AIX`is",$os)) { $img = "<img src='images/os/aix.gif' border='0' title='AIX' alt='AIX'>"; }
	else if (preg_match("`Linux`is",$os)) { $img = "<img src='images/os/linux.gif' border='0' title='Linux' alt='Linux'>"; }
	else if (preg_match("`Unix`is",$os)) { $img = "<img src='images/os/unix.gif' border='0' title='Unix' alt='Unix'>"; }
	else if (preg_match("`Amiga`is",$os)) { $img = "<img src='images/os/amiga.gif' border='0' title='Amiga' alt='Amiga'>"; }	
	else { $img = "<img src='images/os/00.gif' border='0' title='Unknown' alt='Unknown'>"; }
	return $img;
}

//Return the image corresponding to the browser
function browser2img($browser) {
	if (preg_match("`Opera`is",$browser)) { $img = "<img src='images/browsers/opera.gif' border='0' title='Opera' alt='Opera'>"; }
	else if (preg_match("`Netscape`is",$browser)) { $img = "<img src='images/browsers/netscape.gif' border='0' title='Netscape' alt='Netscape'>"; }
	else if (preg_match("`Crazy Browser`is",$browser)) { $img = "<img src='images/browsers/crazy_browser.gif' border='0' title='Crazy Browser' alt='Crazy Browser'>"; }
	else if (preg_match("`MSIE`is",$browser)) { $img = "<img src='images/browsers/msie.gif' border='0' title='Internet Explorer' alt='IE'>"; }
	else if (preg_match("`Konqueror`is",$browser)) { $img = "<img src='images/browsers/konqueror.gif' border='0' title='Konqueror' alt='Konqueror'>"; }
	else if (preg_match("`Galeon`is",$browser)) { $img = "<img src='images/browsers/galeon.gif' border='0' title='Galeon' alt='Galeon'>"; }
	else if (preg_match("`Phoenix`is",$browser)) { $img = "<img src='images/browsers/phoenix.gif' border='0' title='Phoenix' alt='Phoenix'>"; }
	else if (preg_match("`Firebird`is",$browser)) { $img = "<img src='images/browsers/firebird.gif' border='0' title='Firebird' alt='Firebird'>"; }
	else if (preg_match("`Firefox`is",$browser)) { $img = "<img src='images/browsers/firefox.gif' border='0' title='Firefox' alt='Firefox'>"; }
	else if (preg_match("`Chrome`is",$browser)) { $img = "<img src='images/browsers/chrome.gif' border='0' title='Chrome' alt='Chrome'>"; }
	else if (preg_match("`Mozilla`is",$browser)) { $img = "<img src='images/browsers/mozilla.gif' border='0' title='Mozilla' alt='Mozilla'>"; }
	else { $img = "<img src='images/browsers/00.gif' alt='Unknown' border='0' title='Unknown'>"; }
	return $img;
}

//Return the image corresponding to the domain
function domain2img($domain) {
	return ($domain!="") ? "<img src='images/countries/$domain.png' border='0' title='$domain' alt='$domain'>" : "<img src='images/countries/00.png' border='0' title='Unknown' alt='Unknown'>";
}

function ipcountry2img($ip) {
	global $dblink;

	if ($dblink->get_num("SELECT ccode FROM memht_iptocountry LIMIT 1")>0) {
		if (validIp($ip) AND $row = $dblink->get_row("SELECT ccode,cname FROM memht_iptocountry WHERE '".ip2num($ip)."' BETWEEN fromip AND toip LIMIT 1")) {
			return "<img src='images/countries/".strtolower(outCode($row['ccode'])).".png' border='0' title=\"".ucfirst(strtolower(outCode($row['cname'])))."\" alt=\"".ucfirst(strtolower(outCode($row['cname'])))."\">";
		} else {
			return "<img src='images/countries/00.png' border='0' title='Unknown' alt='Unknown'>";
		}
	}
}

function ipcountry2domain($ip) {
	global $dblink;

	if (validIp($ip) AND $row = $dblink->get_row("SELECT ccode,cname FROM memht_iptocountry WHERE '".ip2num($ip)."' BETWEEN fromip AND toip LIMIT 1")) {
		return strtolower(outCode($row['ccode']));
	} else {
		return "";
	}
}

function ip2num($ip) {
	if (validIp($ip)) {
		$ip = explode(".",$ip);
		return intval(str_pad($ip[0],3,"0",STR_PAD_LEFT)).str_pad($ip[1],3,"0",STR_PAD_LEFT).str_pad($ip[2],3,"0",STR_PAD_LEFT).str_pad($ip[3],3,"0",STR_PAD_LEFT);
	} else {
		return 0;
	}
}

function num2ip($num) {
	$len = strlen($num);
	return intval(substr($num,-$len,($len-9))).".".intval(substr($num,-9,3)).".".intval(substr($num,-6,3)).".".intval(substr($num,-3,3));
}

//Trim string
function trimString($string,$length,$char=0) {
	$length = intval($length);
	if ((strlen($string)>$length)) {
		if ($char) {
			//Count chars
			$string = substr($string,0,($length));
			$string .= "..";
		} else {
			//Count words
			preg_match_all("/[^0-9a-zA-Z]/",$string,$found);
			$nstring = preg_split("/[^0-9a-zA-Z]/",$string,-1,PREG_SPLIT_DELIM_CAPTURE);

			$num = sizeof($nstring);
			if ($length>=$num) { $length = $num; }
			$string = "";
			for ($i=0;$i<$length;$i++) {
				$string .= $nstring[$i];
				if ($i<$length-1) { $string .= $found[0][$i]; }
			}
			$string .= "..";
		}
	}
	return $string;
}

//Return a random string
function randString($length) {
	$key = "";
	$pattern = "1234567890abcdefghijklmnopqrstuvwxyz";
	for($i=0;$i<$length;$i++) {
		$key .= $pattern{rand(0,35)};
	}
	return $key;
}

//Mask email (email@memht.com -> email at memht dot com)
function maskEmail($email) {
	$email = str_replace("@"," at ",$email);
	$email = str_replace("."," dot ",$email);
	return $email;
}

//Censure string
function censure($string) {
	global $dblink,$admin;

	$result = $dblink->get_list("SELECT cens FROM memht_censorlist");
	foreach ($result as $row) {
		$cens = trim(outCode($row['cens']));
		$string = preg_replace("`$cens`is", "****", $string);
	}
	return $string;
}

//Write to the admin log file
function adminLog($text) {
	global $admin,$visitorInfo,$siteConfig;

	if ($siteConfig['adminlog']) {
		//Temporary disabled
		/*$content = "[".@date(Y.".".m.".".d)."-".@date(H.".".i)."][$admin][".$visitorInfo['ip']."]-$text\n";

		$myfile = 'admin/log/adminlog.txt';
		@$handle = fopen($myfile, 'a');
		if (!@chmod($myfile,0600)) { //Make readabe and writable only by the site script
			mem_ftp_chmod($myfile,600);
		}
		@fwrite($handle, $content);
		@fclose($handle);*/
	}
}

function textarea($name,$width="",$height="",$editor=1,$set="simple",$value="") {
	global $siteConfig;

	if ($width!="") { if (preg_match("`[^%]$`is",$width) AND preg_match("`[^px]$`is",$width)) { $width = "100%"; } } else { $width = "100%"; }
	if ($height!="") { if (preg_match("`[^%]$`is",$height) AND preg_match("`[^px]$`is",$height)) { $height = "200px"; } } else { $height = "200px"; }

	if ($siteConfig['textarea_editor'] && $editor){
		include_once("inc/fckeditor/fckeditor.php");

		$oFCKeditor = new FCKeditor($name);
		$oFCKeditor->BasePath = 'inc/fckeditor/';
		$oFCKeditor->ToolbarSet = $set;
		if ($width!="") { $oFCKeditor->Width = $width; }
		if ($height!="") { $oFCKeditor->Height = $height; }
		$oFCKeditor->ProcessHTMLEntities = false;
		$oFCKeditor->Value = $value;
		$oFCKeditor->Create();
	} else {
		if ($width=="100%") { $width = "99%"; } //The text area is tending outside the layout, more than 100%
		echo "<textarea name='$name' style='width:$width; height:$height;'>$value</textarea>";
	}
}

function numToMonth($str,$short=0) {
	$str = intval($str);

	switch ($str) {
		case 1: if ($short==0) { return _JAN_; } else { return substr(_JAN_,0,3); } break;
		case 2: if ($short==0) { return _FEB_; } else { return substr(_FEB_,0,3); } break;
		case 3: if ($short==0) { return _MAR_; } else { return substr(_MAR_,0,3); } break;
		case 4: if ($short==0) { return _APR_; } else { return substr(_APR_,0,3); } break;
		case 5: if ($short==0) { return _MAY_; } else { return substr(_MAY_,0,3); } break;
		case 6: if ($short==0) { return _JUN_; } else { return substr(_JUN_,0,3); } break;
		case 7: if ($short==0) { return _JUL_; } else { return substr(_JUL_,0,3); } break;
		case 8: if ($short==0) { return _AUG_; } else { return substr(_AUG_,0,3); } break;
		case 9: if ($short==0) { return _SEP_; } else { return substr(_SEP_,0,3); } break;
		case 10: if ($short==0) { return _OCT_; } else { return substr(_OCT_,0,3); } break;
		case 11: if ($short==0) { return _NOV_; } else { return substr(_NOV_,0,3); } break;
		case 12: if ($short==0) { return _DEC_; } else { return substr(_DEC_,0,3); } break;
	}
}

function file_ext($name) {
	return strtolower(end(explode('.',$name)));
}

function file_name($name) {
	$ext = strrchr($name, '.');
	if ($ext != false) {
		$name = substr($name, 0, -strlen($ext));
	}
	return $name;
}

//Base data from unknown author
function browser($agent) {
	if (preg_match("/Opera ([0-9]\.[0-9]{0,2})/i",$agent,$found) && strstr($agent, "MSIE")) $browser = "Opera ".$found[1];
	else if (preg_match("/Opera ([0-9]\.[0-9]{0,2})/i",$agent,$found) && strstr($agent, "Mozilla")) $browser = "Opera ".$found[1];
	else if (preg_match("/Opera\/([0-9]\.[0-9]{0,2})/i",$agent,$found)) $browser = "Opera ".$found[1];
	else if (preg_match("/Netscape[0-9]\/([0-9]{1,2}\.[0-9]{1,2})/i",$agent,$found)) $browser = "Netscape ".$found[1];
	else if (preg_match("/Netscape\/([0-9]{1,2}\.[0-9]{1,2})/i",$agent,$found)) $browser = "Netscape ".$found[1];
	else if (preg_match("/Crazy Browser ([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2})/i",$agent,$found)) $browser = $found[0];
	else if (preg_match("/MSIE ([0-9]{1,2}\.[0-9]{1,2})/i",$agent,$found)) $browser = $found[0];
	else if (preg_match("/Konqueror/i",$agent)) $browser = "Konqueror";
	else if (preg_match("/Galeon/i",$agent)) $browser = "Galeon";
	else if (preg_match("/Phoenix\/([0-9]{1}\.[0-9]{1,2})/i",$agent,$found)) $browser = "Phoenix ".$found[1];
	else if (preg_match("/Firebird\/([0-9]{1}\.[0-9]{1,2})/i",$agent,$found)) $browser = "Firebird ".$found[1];
	else if (preg_match("/Firefox\/([0-9]{1}\.[0-9]{1,2})/i",$agent,$found)) $browser = "Firefox ".$found[1];
	else if (preg_match("/Chrome\/([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,4}\.[0-9]{1,4})/i",$agent,$found)) $browser = "Chrome ".$found[1];
	else if (preg_match("/Mozilla\/([0-9]{1}\.[0-9]{1,2}) \[en\]/i",$agent,$found)) $browser = "Netscape ".$found[1];
	else if (preg_match("/Mozilla\/([0-9]{1,2}\.[0-9]{1,2})/i",$agent,$found)) $browser = "Mozilla ".$found[1];
	else if (preg_match("/(^Mozilla)(.)*\;\srv:([0-9]\.[0-9])/i",$agent,$found)) $browser = $found[1]." ".$found[3];
	else if (preg_match("/Avant Browser/i",$agent,$found)) $browser = "Avant Browser";
	else if (preg_match("/Minimo\/([0-9]{1}\.[0-9]{1,3})/i",$agent,$found)) $browser = "Minimo ".$found[1];
	else if (preg_match("/SeaMonkey\/([0-9]{1}\.[0-9a-zA-Z]{1,2})/i",$agent,$found)) $browser = "SeaMonkey ".$found[1];
	else if (preg_match("/Safari\/([0-9]{3})/i",$agent,$found)) $browser = "Safari ".$found[1];
	else if (preg_match("/Camino\/([0-9]{1}\.[0-9a-zA-Z]{1,3})/i",$agent,$found)) $browser = "Camino ".$found[1];
	else $browser = "Other";
	return $browser;
}
//Base data from unknown author
function os($agent) {
	if( strstr( $agent, "Win") ) {
		$os = "Windows";
		if (preg_match("/Windows NT 6\.0/i",$agent)) $os = "Windows Vista";
		else if (preg_match("/Windows NT 5\.1/i",$agent)) $os = "Windows XP";
		else if (preg_match("/Windows NT 5\.2/i",$agent)) $os = "Windows 2003";
		else if (preg_match("/Windows NT 5\.0/i",$agent)) $os = "Windows 2000";
		else if (preg_match("/Windows NT/i",$agent)) $os = "Windows NT";
		else if (preg_match("/WinNT/i",$agent)) $os = "Windows NT";
		else if (preg_match("/Windows ME/i",$agent)) $os = "Windows ME";
		else if (preg_match("/Win 9x 4.90/i",$agent)) $os = "Windows ME";
		else if (preg_match("/Windows ME/i",$agent)) $os = "Windows ME";
		else if (preg_match("/Windows CE/i",$agent)) $os = "Windows CE";
		else if (preg_match("/98/i",$agent)) $os = "Windows 98";
		else if (preg_match("/95/i",$agent)) $os = "Windows 95";
	}
	else if (strstr($agent,"Mac")) $os = "Macintosh";
	else if (strstr($agent,"PPC")) $os = "Macintosh";
	else if (strstr($agent,"FreeBSD")) $os = "FreeBSD";
	else if (strstr($agent,"SunOS")) $os = "SunOS";
	else if (strstr($agent,"IRIX")) $os = "IRIX";
	else if (strstr($agent,"BeOS")) $os = "BeOS";
	else if (strstr($agent,"OS/2")) $os = "OS/2";
	else if (strstr($agent,"AIX")) $os = "AIX";
	else if (strstr($agent,"Linux")) $os = "Linux";
	else if (strstr($agent,"Unix")) $os = "Unix";
	else if (strstr($agent,"Amiga")) $os = "Amiga";
	else $os = "Other";
	return $os;
}

function searchengine($agent) {
	if (preg_match("/google\.([a-zA-Z]{1,3})\.([a-zA-Z]{1,3})/i",$agent,$found)) $engine = "Google.".$found[1].".".$found[2];
	else  if (preg_match("/google\.([a-zA-Z]{1,3})/i",$agent,$found)) $engine = "Google.".$found[1];
	else if (preg_match("/excite\.([a-zA-Z]{1,3})/i",$agent,$found)) $engine = "Excite.".$found[1];
	else if (preg_match("/yahoo\.([a-zA-Z]{1,3})/i",$agent,$found)) $engine = "Yahoo.".$found[1];
	else if (preg_match("/msn\.([a-zA-Z]{1,3})/i",$agent,$found)) $engine = "Msn.".$found[1];
	else if (preg_match("/live\.([a-zA-Z]{1,3})/i",$agent,$found)) $engine = "Live.".$found[1];
	else if (preg_match("/altavista\.([a-zA-Z]{1,3})/i",$agent,$found)) $engine = "Altavista.".$found[1];
	else if (preg_match("/alltheweb\.([a-zA-Z]{1,3})/i",$agent,$found)) $engine = "Alltheweb.".$found[1];
	else if (preg_match("/looksmart\.([a-zA-Z]{1,3})/i",$agent,$found)) $engine = "Looksmart.".$found[1];
	else $engine = "";
	return $engine;
}

function getSearchQuery($agent) {
	$ref = $agent;
	$query_string = false;

	$querystruct = array();
	$querystruct[] = array("google.", "q", "Google");
	$querystruct[] = array("ask.com", "q", "Ask.com");
	$querystruct[] = array("ask.co.uk", "ask", "Ask.co.uk");
	$querystruct[] = array("comcast.net", "q", "Comcast");
	$querystruct[] = array("yahoo", "p", "Yahoo");
	$querystruct[] = array("aol.com", "query", "AOL");
	$querystruct[] = array("msn.com", "q", "MSN");
	$querystruct[] = array("live.com", "q", "Live.com");
	$querystruct[] = array("netscape.com", "query", "Netscape");
	$querystruct[] = array("netzero.net", "query", "NetZero");
	$querystruct[] = array("altavista.com", "q", "Altavista");
	$querystruct[] = array("mywebsearch.com", "searchfor", "Mywebsearch");
	$querystruct[] = array("alltheweb.com", "q", "Alltheweb");
	$querystruct[] = array("cnn.com", "query", "CNN");
	$querystruct[] = array("myspace.com", "q", "MySpace");

	for($i=0,$size=sizeof($querystruct);$i<$size;$i++){
		if (stristr($ref,$querystruct[$i][0]) ) {
			$symbol = $querystruct[$i][1];
			$temp1 = explode("$symbol=",$ref,2);
			$temp2 = explode("&",$temp1[1]);
			$string = $temp2[0];
			$query_string = urldecode($string);
		}
	}
	return $query_string;
}

function getDirContent($dir) {
	unset($filearray);
	$filearray = array();
	$handle = opendir($dir);
	while (false!== ($file = readdir($handle))) {
		if ($file!= "." AND $file!= ".." AND $file!="Thumbs.db") {
			$filearray[] = $file;
		}
	}
	closedir($handle);
	@sort($filearray);
	@reset($filearray);

	return $filearray;
}

function breakLongLinks($link,$length=60) {
	return (strlen($link)>$length) ? substr($link,0,30).".....".substr($link,-20,20) : $link;
}

function getMicrotime() {
	list($usec, $sec) = explode(" ", microtime());
	return ((float)$usec + (float)$sec);
}

function showPath() {
	global $dblink,$siteConfig,$page,$pathtext,$tpl;

	if (memRunHooks('ShowPath',array(&$pathtext))) {
		$pathtext = "<a href='".$siteConfig['site_url']."' title=\""._HOME_."\">"._HOME_."</a>";

		if ($page!="") {
			if ($row = $dblink->get_row("SELECT titolo FROM memht_pagine WHERE nome='$page' AND nome!='mypage'")) {
				$title = outCode($row['titolo']);
				$pathtext .= " > <a href='index.php?page=$page' title=\"$title\">$title</a>";
			}

			if (file_exists("pages/$page/path.php")) { @include_once("pages/$page/path.php"); }
		}

		memRunHooks('ShowPathEnd',array(&$pathtext));
	}
	$tpl->assign('showpath',$pathtext);
}

function memhtErrorHandler($errno,$errstr,$errfile,$errline,$args) {
	global $siteConfig,$visitorInfo,$userid;

	//The error has been supressed with @
	if (error_reporting()==0) { return; }
	//Ignore E_STRICT notices
	if ($errno==2048) { return; }

	//Show errors
	$showerrors = 1;
	//Show errors only to administrators
	$showerrors = (isAuth($userid,3)) ? $showerrors : 0 ;

	//Log errors to file
	$logtofile = 0;

	//Log errors to email
	$logtoemail = 0;

	switch($errno){
		case 1:		$errtitle = "Error";			break;
		case 2:		$errtitle = "Warning";			break;
		case 4:		$errtitle = "Parse Error";		break;
		case 8:		$errtitle = "Notice";			break;
		case 16:	$errtitle = "Core Error";		break;
		case 32:	$errtitle = "Core Warning";		break;
		case 64:	$errtitle = "Compile Error";	break;
		case 128:	$errtitle = "Compile Warning";	break;
		case 256:	$errtitle = "User Error";		break;
		case 512:	$errtitle = "User Warning";		break;
		case 1024:	$errtitle = "User Notice";		break;
		case 2048:	$errtitle = "Strict Notice";	break;
		default:	$errtitle = "Unknown error";	break;
	}

	$errtrace = @debug_backtrace();

	if ($showerrors==1) {
		if (preg_match("`mysql`is",$errstr)) {
			//MySQL
			echo "<div class='errorbox'>";
					echo "<div class='errorbox_title'><b>Database error</b></div>";
					echo "<div class='errorbox_text'><b>Errno:</b> $errno (MySQL Errno: ".@mysql_errno().")</div>";
					echo "<div width='1%' class='errorbox_text'><b>File:</b> ".$errtrace[2]['file']."</div>";
					echo "<div class='errorbox_text'><b>Line:</b> ".$errtrace[2]['line']."</div>";
					echo "<div class='errorbox_text'><b>Function:</b> ".$errtrace[2]['function']."</div>";
					if (isAuth($userid,3)) {
						echo "<div class='errorbox_text'><b>MySQL error:</b> ".@mysql_error()."</div>";
						echo "<div class='errorbox_text'><b>Query:</b> ".$args['query']."</div>";
					}
					echo "<div class='errorbox_text'><b>Note:</b> $errstr</div>";
			echo "</div>";
		} else {
			//Other errors
			echo "<div class='errorbox'>";
				echo "<div class='errorbox_title'><b>$errtitle</b></div>";
				echo "<div class='errorbox_text' nowrap><b>Errno:</b> $errno</div>";
				echo "<div class='errorbox_text'><b>File:</b> ".$errtrace[1]['file']."</div>";
				echo "<div class='errorbox_text'><b>Line:</b> ".$errtrace[1]['line']."</div>";
				echo "<div class='errorbox_text'><b>Function:</b> ".$errtrace[1]['function']."</div>";
				echo "<div class='errorbox_text'><b>Note:</b> $errstr</div>";
			echo "</div>";
		}
	}

	//Log errors to file
	//Ignore notices
	if ($logtofile==1 AND $errno!=8 AND $errno!=2048) {
		$errlog =  "=================================================\n";
		if (preg_match("`mysql`is",$errstr)) {
			$errlog .= "Database error (MySQL Errno: ".@mysql_errno().")\n";
		} else {
			$errlog .= "$errtitle\n";
		}
		$errlog .= "-------------------------------------------------\n";
		$errlog .= "Errno:\t\t$errno\n";
		$errlog .= "Time:\t\t".@date(Y.".".m.".".d)."-".@date(H.".".i)."\n";
		$errlog .= "IP:\t\t".$visitorInfo['ip']."\n";
		$errlog .= "Req. URI:\t".@$_SERVER['REQUEST_URI']."\n";
		$errlog .= "Referer:\t".@$_SERVER['HTTP_REFERER']."\n";
		if (preg_match("`mysql`is",$errstr)) {
			$errlog .= "File:\t\t".$errtrace[2]['file']."\n";
			$errlog .= "Line:\t\t".$errtrace[2]['line']."\n";
			$errlog .= "Function:\t".$errtrace[2]['function']."\n";
			$errlog .= "MySQL error:\t".@mysql_error()."\n";
		} else {
			$errlog .= "File:\t\t".$errtrace[1]['file']."\n";
			$errlog .= "Line:\t\t".$errtrace[1]['line']."\n";
			$errlog .= "Function:\t".$errtrace[1]['function']."\n";
		}
		if (isset($args['query'])) { $errlog .= "Query:\t\t".$args['query']."\n"; }
		$errlog .= "Note:\t\t$errstr\n";

		if (@filesize("inc/errors.log")>1048576) { @unlink("inc/errors.log"); } //1Mb
		@error_log($errlog,3,"inc/errors.log");
	}

	//Log errors to email
	//Ignore notices
	if ($logtoemail==1 AND $errno!=8 AND $errno!=2048) {
		$errlog =  "=================================================\n";
		if (preg_match("`mysql`is",$errstr)) {
			$errlog .= "Database error (MySQL Errno: ".@mysql_errno().")\n";
		} else {
			$errlog .= "$errtitle\n";
		}
		$errlog .= "-------------------------------------------------\n";
		$errlog .= "Errno:\t\t$errno\n";
		$errlog .= "Time:\t\t".@date(Y.".".m.".".d)."-".@date(H.".".i)."\n";
		$errlog .= "IP:\t\t".$visitorInfo['ip']."\n";
		$errlog .= "Req. URI:\t".@$_SERVER['REQUEST_URI']."\n";
		$errlog .= "Referer:\t".@$_SERVER['HTTP_REFERER']."\n";
		if (preg_match("`mysql`is",$errstr)) {
			$errlog .= "File:\t\t".$errtrace[2]['file']."\n";
			$errlog .= "Line:\t\t".$errtrace[2]['line']."\n";
			$errlog .= "Function:\t".$errtrace[2]['function']."\n";
			$errlog .= "MySQL error:\t".@mysql_error()."\n";
		} else {
			$errlog .= "File:\t\t".$errtrace[1]['file']."\n";
			$errlog .= "Line:\t\t".$errtrace[1]['line']."\n";
			$errlog .= "Function:\t".$errtrace[1]['function']."\n";
		}
		if (isset($args['query'])) { $errlog .= "Query:\t\t".$args['query']."\n"; }
		$errlog .= "Note:\t\t$errstr\n";

		$mailheaders = "From: ".$siteConfig['site_name']." <".$siteConfig['webmaster_mail'].">\n";
		$mailheaders .= "Reply-To: ".$siteConfig['webmaster_mail']."\n";
		$mailheaders .= "Content-type: text/plain; charset="._LANG_CHARSET_."\n";
		$mailheaders .= "Content-transfer-encoding: 8bit\n";
		$mailheaders .= "X-Mailer: PHP/".phpversion();

		@mail($siteConfig['webmaster_mail'],$siteConfig['site_name']." - Error log",$errlog,$mailheaders);
	}
}


function mem_ftp_chmod($filename,$mode) {
	global $siteConfig;

	if ($filename=="" OR $mode=="") { return false; }
	$mode = (!preg_match("`0`is",$mode{0})) ? "0{$mode}" : "$mode" ;
	if ($siteConfig['ftp_server']!="" AND $siteConfig['ftp_user']!="") {
		$ftp_base = $siteConfig['ftp_base'];
		if ($ftp_base=="") { $ftp_base = "/"; }
		$filename = $ftp_base.$filename;

		if ($conn_id = @ftp_connect($siteConfig['ftp_server'])) {
			if ($login_result = @ftp_login($conn_id,$siteConfig['ftp_user'],$siteConfig['ftp_pass'])) {
				if (@ftp_site($conn_id,"CHMOD $mode $filename")) {
					return true;
				} else {
					$filename = "/public_html".$filename;
					if (@ftp_site($conn_id,"CHMOD $mode $filename")) {
						return true;
					} else {
						return false;
					}
				}
				@ftp_close($conn_id);
			}
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function mem_ftp_mkdir($path,$dir,$mode=777) {
	global $siteConfig;

	if ($path=="" OR $dir=="") { return false; }
	$mode = (!preg_match("`0`is",$mode{0})) ? "0{$mode}" : "$mode" ;
	if ($siteConfig['ftp_server']!="" AND $siteConfig['ftp_user']!="") {
		$ftp_base = $siteConfig['ftp_base'];
		if ($ftp_base=="") { $ftp_base = "/"; }

		if ($conn_id = @ftp_connect($siteConfig['ftp_server'])) {
			if ($login_result = @ftp_login($conn_id,$siteConfig['ftp_user'],$siteConfig['ftp_pass'])) {
				if (@ftp_chdir($conn_id,$path)) {
					if (@ftp_mkdir($conn_id,$dir)) {
						@ftp_site($conn_id,"CHMOD $mode $dir");
						return true;
					} else {
						return false;
					}
				} else {
					return false;
				}
				@ftp_close($conn_id);
			}
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function deep_in_array($value,$array,$case_insensitive = false){
	foreach($array as $item){
		if (is_array($item)) {
			$ret = deep_in_array($value,$item,$case_insensitive);
		} else {
			$ret = ($case_insensitive) ? strtolower($item)==$value : $item==$value;
		}
		if ($ret) { return $ret; }
	}
	return false;
}

function dnsLink($ip) {
	$url = "http://www.dnsstuff.com/tools/ipall.ch?domain={{IP}}";
	return str_replace("{{IP}}",$ip,$url);
}

//Virtual components installed
//Added in 3.8.1
function start_element_handler($parser,$data,$attr){
	global $key,$gattr;
	$key = $data;
	$gattr = (sizeof(@$attr['opt'])>0) ? $attr['opt'] : "" ;
}
function end_element_handler($parser,$data){}
function content_element_handler($parser,$data){
	global $obj,$key,$gattr;
	$data = trim($data);
	if ($data!="") {
		if ($gattr!="") {
			$obj[$key][$gattr] = trim($data);
		} else {
			$obj[$key] = trim($data);
		}
	}
}
function get_xml_file_content($url) {
	global $obj,$key,$gattr;
	if ($data = @file_get_contents($url)) {
		$obj = array();
		$key = "";
		$gattr = "";
		$xmlparser = xml_parser_create();
		xml_parser_set_option($xmlparser,XML_OPTION_CASE_FOLDING,0);
		xml_set_element_handler($xmlparser,"start_element_handler","end_element_handler");
		xml_set_character_data_handler($xmlparser,"content_element_handler");
		if(!(xml_parse($xmlparser,$data))){ return false; }
		xml_parser_free($xmlparser);
		return $obj;
	} else {
		return false;
	}
}

function sendEmail($to,$subject,$message,$fromname,$fromemail,$ishtml=0) {
	global $siteConfig;

	require_once("inc/class/class.phpmailer.php");
	$mail = new PHPMailer();
	$mail->From = $fromemail;
	$mail->FromName = $fromname;
	$mail->Subject = $subject;
	if ($siteConfig['mail_usesmtp']==1) {
		//Smtp
		$mail->Host = $siteConfig['mail_smtp'];
		$mail->Mailer = "smtp";
		if ($siteConfig['mail_smtpauth']) {
			$mail->SMTPAuth = true;
			$mail->Username = $siteConfig['mail_smtpuser'];
			$mail->Password = $siteConfig['mail_smtppass'];
		}
	} else {
		//Mail
		$mail->Mailer = "mail";
	}
	if ($ishtml==1) { $mail->IsHTML(true); }
	$mail->Body = $message;

	$mail->AddAddress($to);
	if ($mail->Send()) {
		$mail->ClearAddresses();
		return true;
	} else {
		$mail->ClearAddresses();
		return false;
	}
}

//4.0.1
function cleanTitleAtr($string) {
	return str_replace("'","&#039;",$string);
}

?>