<?php
!defined("MONKEYMAO") && die("Accessed Defined!");
function authcode($string, $operation, $key = '') {
	$key = $key ? $key : $GLOBALS['mm_auth_key'];

	$coded = '';
	$keylength = strlen($key);
	$string = $operation == 'DECODE' ? base64_decode($string) : $string;
	for($i = 0; $i < strlen($string); $i += $keylength) {
		$coded .= substr($string, $i, $keylength) ^ $key;
	}
	$coded = $operation == 'ENCODE' ? str_replace('=', '', base64_encode($coded)) : $coded;
	return $coded;
}

function textcut($string, $length, $dot = '') {
	global $charset;

	if(strlen($string) <= $length) {
		return $string;
	}

	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);

	$strcut = '';
	if(strtolower($charset) == 'utf-8') {

		$n = $tn = $noc = 0;
		while($n < strlen($string)) {

			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t < 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}

			if($noc >= $length) {
				break;
			}

		}
		if($noc > $length) {
			$n -= $tn;
		}

		$strcut = substr($string, 0, $n);

	} else {
		for($i = 0; $i < $length; $i++) {
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}

	$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

	return $strcut.$dot;
}

function clearcookies() {
	global $time, $cookiepath, $cookiedomain, $mm_mid, $mm_user, $mm_pw, $mm_secques, $adminid, $groupid, $credits;
	dsetcookie('auth', '', -86400 * 365);
	dsetcookie('visitedfid', '', -86400 * 365);
	$mm_mid = $adminid = $credits = 0;
	$mm_user = $mm_pw = $mm_secques = '';
}
function dsetcookie($var, $value, $life = 0, $prefix = 1) {
	global $tablepre, $cookiedomain, $cookiepath, $time, $_SERVER;
	setcookie(($prefix ? $tablepre : '').$var, $value,
		$life ? $time + $life : 0, $cookiepath,
		$cookiedomain, $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
}
function filter($string, $force = 0) {
	if(!$GLOBALS['magic_quotes_gpc'] || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = filter($val, $force);
			}
		} else {
			$string = addslashes($string);
		}
	}
	return $string;
}

function random($length, $numeric = 0) {
	mt_srand((double)microtime() * 1000000);
	if($numeric) {
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	} else {
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}
function formhash() {
	global $mm_user, $mm_mid, $mm_pw, $time;
	return substr(md5(substr($time, 0, -7).$mm_user.$mm_mid.$mm_pw), 8, 8);
}
function checksubmit($var, $allowget = 0, $useseccode = 0){	
	if(empty($GLOBALS[$var])) {		
		return FALSE;
	} else {
		global $_SERVER, $adminid, $submitrefcheck, $seccode, $seccodeverify;

		if($allowget || ($_SERVER['REQUEST_METHOD'] == 'POST' && $GLOBALS['formhash'] == formhash() && (empty($_SERVER['HTTP_REFERER']) ||
			preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])))) {
			if($useseccode) {			
				if(intval($seccodeverify) == intval($seccode)) {
					$seccode = random(4, 1);					
					return TRUE;
				} else {
					msg('seccode_error');					
				}
			} else {
				return TRUE;
			}
		} else {
			msg('error');
		}
	}
}

function idarray($idarray, $quote = '\'', $bound = ','){
	if(!is_array($idarray)){
		return false;
	}
	$ids = $common = '';
	foreach($idarray AS $key => $id){
		$ids .=$common. $quote . $id .$quote;
		$common = $bound;
	}
	return $ids;
}


function lang($file, $tpldir = '') {
	$tpldir = $tpldir ? $tpldir : TPLDIR;
	$languagepack = MODEPATH.'./'.$tpldir.'/'.$file.'.lang.php';
	
	if(file_exists($languagepack)) {
		return $languagepack;
	} else {
		return FALSE;
	}
}

function paging($num, $perpage, $curpage, $mpurl, $maxpages = 0) {
	$multipage = '';
	$mpurl .= strpos($mpurl, '?') ? '&' : '?';
	if($num > $perpage) {
		$page = 10;
		$offset = 2;

		$realpages = @ceil($num / $perpage);
		$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;

		if($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $from + $page - 1;
			if($from < 1) {
				$to = $curpage + 1 - $from;
				$from = 1;
				if($to - $from < $page) {
					$to = $page;
				}
			} elseif($to > $pages) {
				$from = $pages - $page + 1;
				$to = $pages;
			}
		}

		$multipage = ($curpage - $offset > 1 && $pages > $page ? '<td>&nbsp;<a href="'.$mpurl.'page=1"><b>|</b>&lt;&nbsp;</td>' : '').
			($curpage > 1 ? '<td>&nbsp;<a href="'.$mpurl.'page='.($curpage - 1).'">&lt;</a>&nbsp;</td>' : '');
		for($i = $from; $i <= $to; $i++) {
			$multipage .= $i == $curpage ? '<td bgcolor="#F2F2F2">&nbsp;<u><b>'.$i.'</b></u>&nbsp;</td>' :
				'<td>&nbsp;<a href="'.$mpurl.'page='.$i.'">'.$i.'</a>&nbsp;</td>';
		}

		$multipage .= ($curpage < $pages ? '<td>&nbsp;<a href="'.$mpurl.'page='.($curpage + 1).'">&gt;</a>&nbsp;</td>' : '').
			($to < $pages ? '<td>&nbsp;<a href="'.$mpurl.'page='.$pages.'">&gt;<b>|</b></a>&nbsp;</td>' : '').
			($curpage == $maxpages ? '<td>&nbsp;<a href="misc.php?action=maxpages&pages='.$maxpages.'">&gt;<b>?</b></a>&nbsp;</td>' : '').
			($pages > $page ? '<td style="padding: 0"><input type="text" name="custompage" size="2" style="border: 1px solid #F2F2F2" onKeyDown="if(event.keyCode==13) {window.location=\''.$mpurl.'page=\'+this.value; this.form.submit=false;}"></td>' : '');

		$multipage = $multipage ? '<table cellspacing="0" cellpadding="0" border="0"><tr><td height="3"></td></tr><tr><td>'.
			'<table cellspacing="1" cellpadding="2" class="tableborder"><tr bgcolor="#F2F2F2" class="smalltxt"><td class="header">&nbsp;'.$num.'&nbsp;</td><td class="header">&nbsp;'.$curpage.'/'.$realpages.'&nbsp;</td>'.$multipage.'</tr></table>'.
			'</td></tr><tr><td height="3"></td></tr></table>' : '';
	}
	return $multipage;
}

function msg($msg, $url = '', $extra = '') {
	extract($GLOBALS, EXTR_SKIP);
	global $extrahead, $mm_action, $debuginfo, $seccode, $fid, $tid;
	$extrahead .= $url ? '<meta http-equiv="refresh" content="3;url='.
		(empty($_DCOOKIE['sid']) && $transsidstatus ? transsid($url) : $url).
		'">' : '';
	@include lang('msg');
	$msg = $lang[$msg] ? $lang[$msg] : $msg;	
	eval("\$messages = \"".$msg."\";");	

	if($extra == 'NOPERM' && !$passport_status) {
		//get secure code checking status (pos. -2)
		if($seccodecheck = substr(sprintf('%05b', $seccodestatus), -2, 1)) {
			$seccode = random(4, 1);
		}
		include theme('nopermission');
	} else {
		include theme('msg');
	}
	mexit();
}
function mexit($msg=''){
	exit($msg);
}

function theme($file, $tpldir='',$addon = 'default'){
	global $tplrefresh;

	$tpldir = $tpldir ? $tpldir : TPLDIR;
	$tplfile = MODEPATH.'./'.$tpldir.'/'.$file.'.htm';
	$objfile = MODEPATH.'./cache/themes/'.$addon.'_'.$file.'.tpl.php';
	if(!file_exists($tplfile)) {
		mexit('Template file is not finded, Please Check!!!');
	}
	if($tplrefresh == 1 || ($tplrefresh > 1 && substr($GLOBALS['time'], -1) > $tplrefresh)) {
		if(@filemtime($tplfile) > @filemtime($objfile)) {
			require_once MODEPATH.'./includes/theme.func.php';
			parse_theme($file, $tpldir, $addon);
		}
	}
	return $objfile;
}

function opinfo(){
	if($GLOBALS['showopinfo']){
		global $db,$time,$mm_starttime;
		$mtime = explode(" ", microtime());
        $endtime = $mtime[1] + $mtime[0];
		$taken = $endtime - $mm_starttime;
		echo 'Processed in '.number_format($taken, 8).' second(s). SQL:'. $db ->querynum .' queries, '.number_format($db ->querytimes,6).' second(s)';
	}
}

function htmlconvert($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = htmlconvert($val);
		}
	} else {
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
			str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
	}
	return $string;
}
function isemail($email) {
	return strlen($email) > 8 && preg_match("/^[-_+.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+([a-z]{2,4})|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email);
}

function ispage($number) {
	return !empty($number) && preg_match ("/^([0-9]+)$/", $number);
}

function isurl($url) { 
	return ereg("[a-zA-z]+://[^\s]*", $url); 
}

function mmsession() {
	if(!empty($GLOBALS['sessionupdated'])) {
		return TRUE;
	}

	global $db, $tablepre, $sessionexists, $sessionupdated, $sid, $onlineip, $mm_user, $mm_mid, $time, $lastactivity, $seccode,
		$pvfrequence, $spageviews, $lastolupdate, $groupid,  $invisible, $mm_action, $onlinehold,$adminid;
	if($sessionexists == 1) {	

		$db->query("UPDATE {$tablepre}sessions SET mid='$mm_mid', username='$mm_user', adminid='$adminid',groupid='$groupid', invisible='$invisible', action='$mm_action', lastactivity='$time', seccode='$seccode' WHERE sid='$sid'");	
	} else {
		$ips = explode('.', $onlineip);
		
		$db->query("DELETE FROM {$tablepre}sessions WHERE sid='$sid' OR lastactivity<($time-$onlinehold) OR ('$mm_mid'<>'0' AND mid='$mm_mid') OR (mid='0' AND ip1='$ips[0]' AND ip2='$ips[1]' AND ip3='$ips[2]' AND ip4='$ips[3]' AND lastactivity>$time-60)");
		$db->query("INSERT INTO {$tablepre}sessions (sid, ip1, ip2, ip3, ip4, mid, username, adminid,groupid, invisible, action, lastactivity, seccode)
			VALUES ('$sid', '$ips[0]', '$ips[1]', '$ips[2]', '$ips[3]', '$mm_mid', '$mm_user','$adminid', '$groupid',  '$invisible', '$mm_action', '$time', '$seccode')", 'SILENT');
			
		if($mm_mid && $time - $lastactivity > 21600) {
			$db->query("UPDATE {$tablepre}members SET lastip='$onlineip', lastvisit=lastactivity, lastactivity='$time' WHERE mid='$mm_mid'", 'UNBUFFERED');
		}
	}
	
	$sessionupdated = 1;
}
function site() {
	return preg_replace("/.*?([^\.\/]+)(\.(com|net|org|gov|edu))?\.[^\.\/]+$/", "\\1", $_SERVER['HTTP_HOST']);
}

function output() {
	global $sid, $transsidstatus, $rewritestatus,$system_version;
	//echo '<!-- Photo CMS -->Powered BY <a href="http://'.$system_version['homesite'].'"><font color="#FF9900"><b>'.$system_version['system'].' V '.$system_version['version'].'</b></font></a> &copy; 2008 <a href="http://'.$system_version['homesite'].'"><font color="#00CCFF">'.$system_version['company'].'</font></a>.<!-- Photo CMS -->';
	echo 'Copyright &copy; <a href="http://'.$system_version['homesite'].'"><font color="#FF9900"><b>'.$system_version['system'].' V '.$system_version['version'].'</b></font></a> '.$system_version['company'].'';
	Define('COPYRIGHT', true);
	if(($transsidstatus = empty($GLOBALS['_DCOOKIE']['sid']) && $transsidstatus) || in_array($rewritestatus, array(2, 3))) {		
		$searcharray = array	(
			"/\<a(\s*[^\>]+\s*)href\=([\"|\']?)([^\"\'\s]+)/ies",
			"/(\<form.+?\>)/is"
			);
		$replacearray = array	(
			"transsid('\\3','<a\\1href=\\2')",
			"\\1\n<input type=\"hidden\" name=\"sid\" value=\"$sid\">"
			);
		$content = preg_replace($searcharray, $replacearray, ob_get_contents());
		ob_end_clean();
		$GLOBALS['gzip'] ? ob_start('ob_gzhandler') : ob_start();

		echo $content;
	}
}

function mreferer($default = 'index.php') {
	global $referer;
	if(empty($referer) && isset($GLOBALS['_SERVER']['HTTP_REFERER'])) {
		$referer = preg_replace("/([\?&])((sid\=[a-z0-9]{6})(&|$))/i", '\\1', $GLOBALS['_SERVER']['HTTP_REFERER']);
		$referer = substr($referer, -1) == '?' ? substr($referer, 0, -1) : $referer;
	} else {
		$referer = filter($referer);
	}

	if(!preg_match("/(\.php|[a-z]+(\-\d+)+\.html)/", $referer) || strpos($referer, 'loggin')) {
		$referer = $default;
	}
	return $referer;
}
function userlogs($log, $mid = 0,$type = 'system'){
	global $db, $tablepre, $time,$loglines;
	$db -> query("INSERT INTO {$tablepre}userlogs  (type, mid, dateline, logs) VALUES ('$type', '$mid', '$time', '$log') ");
	$db -> query("DELETE FROM {$tablepre}userlogs WHERE dateline<$time-$loglines*86400");
}
function transsid($url, $tag = '', $wml = 0) {
	global $sid;
	$tag = stripslashes($tag);
	if(!$tag || (!preg_match("/^(http:\/\/|mailto:|#|javascript)/i", $url) && !strpos($url, 'sid='))) {
		if($pos = strpos($url, '#')) {
			$urlret = substr($url, $pos);
			$url = substr($url, 0, $pos);
		} else {
			$urlret = '';
		}
		$url .= (strpos($url, '?') ? ($wml ? '&amp;' : '&') : '?').'sid='.$sid.$urlret;
	}
	return $tag.$url;
}

function writetofile($file_name,$data,$method='w') {
	if($filenum=@fopen($file_name,$method)){
		flock($filenum,LOCK_EX);
		$file_data=fwrite($filenum,$data);
		fclose($filenum);
		return $file_data;
	}else{
		exit('Can not fopen please check the file or PHP.INI');
	}
}
function readfromfile($file){
	if(!@$fp = fopen($file, 'r')) {
		return false;
	} else {
		$str = @fread($fp, filesize($file));
		fclose($fp);
		return $str;
	}
}
function sizecount($filesize) {
	if($filesize >= 1073741824) {
		$filesize = round($filesize / 1073741824 * 100) / 100 . ' G';
	} elseif($filesize >= 1048576) {
		$filesize = round($filesize / 1048576 * 100) / 100 . ' M';
	} elseif($filesize >= 1024) {
		$filesize = round($filesize / 1024 * 100) / 100 . ' K';
	} else {
		$filesize = $filesize . ' bytes';
	}
	return $filesize;
}
function fileext($filename) {
	return trim(substr(strrchr($filename, '.'), 1));
}

function Gettoptags($n=0,$f=''){
global $tablepre,$db;
$Gettoptags="";
 			$query = $db -> query("Select tags,count From {$tablepre}tags where result='1'order by count desc limit 0,$n; ");
 			while($row = $db -> fetch_array($query)){
 				 if($row['count']>1000) $style=" style='font-size:11pt;color:red'";
 				 else if($row['count']>300) $style=" style='font-size:10pt;color:green'";
 				 else $style = "";
 				 $Gettoptags .= '<a href="'.$siteurl.'/search/?q='.urlencode($row['tags']).'"'.$style.">".$row['tags']."</a> $f ";
 			}
 			return $Gettoptags;
}

function Getnewtags($n=0,$f=''){
global $tablepre,$db;
$Gettoptags="";
 			$query = $db -> query("Select tags,count From {$tablepre}tags where result='1'order by id desc limit 0,$n; ");
 			while($row = $db -> fetch_array($query)){
 				 if($row['count']>1000) $style=" style='font-size:11pt;color:red'";
 				 else if($row['count']>300) $style=" style='font-size:10pt;color:green'";
 				 else $style = "";
 				 $Getnewtags .= '<a href="'.$siteurl.'/search/?q='.urlencode($row['tags']).'"'.$style.">".$row['tags']."</a> $f ";
 			}
 			return $Getnewtags;
}
function Getpiclist($id,$pid){
global $tablepre,$db;
$Getpiclist="";
$i=0;
 			$query = $db -> query("Select uid,pid From {$tablepre}uploads WHERE pid='$pid'");
 			$lines = $db -> result($query, 0);
 			while($row = $db -> fetch_array($query)){
 			$i=$i+1;
 			if($row['uid']==$id) $sid=$i;
 			if($row['uid']==$id) $style=" style='font-size:10pt;color:green'";
 			else $style = "";
 			if(($sid+6)>$i || $i<($sid-6)){
 				 $Getpiclist .= '<a href="?/'.$row['pid'].'/'.$row['uid'].'.html"'.$style.'>'.$i.'</a> ';
 				 }
 			}
 			return $Getpiclist;
}

function Getpicsort($id='0'){
global $tablepre,$db;
$Getpicsort="p.id IN($id";
$i=0;
 			$query = $db -> query("SELECT id FROM {$tablepre}picsort WHERE upid='$id'");
 			while($row = $db -> fetch_array($query)){
 				 $Getpicsort .= ','.$row['id'].'';
 			}
 			return $Getpicsort.')';
}
?>