<?php
!defined("MONKEYMAO") && die("Accessed Defined!");
function cpmsg($msg, $url = '', $extra = '',$cancelurl='') {
	extract($GLOBALS, EXTR_SKIP);
	global $extrahead, $mm_action, $debuginfo, $seccode, $fid, $tid;

	@include lang('msg','themes/admin');
	$msg = $lang[$msg] ? $lang[$msg] : $msg;	
	eval("\$messages = \"".$msg."\";");	
	if($extra == 'NOPERM') {
		//get secure code checking status (pos. -2)
		if($seccodecheck = substr(sprintf('%05b', $seccodestatus), -2, 1)) {
			$seccode = random(4, 1);
		}
		include theme('ask','themes/admin', 'admin');
	} else {
		$extrahead .= $url ? '<meta http-equiv="refresh" content="3;url='.
		(empty($_DCOOKIE['sid']) && $transsidstatus ? transsid($url) : $url).
		'">' : '';
		include theme('msg', 'themes/admin', 'admin');
	}
	mexit();
}
function cpchecksubmit($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 {
					cpmsg('secodecheck');					
				}
			} else {
				return TRUE;
			}
		} else {
			cpmsg('error');
		}
	}
}
function input($name, $value=0, $checked=0,$type = 'radio', $size=30){
	$checkedhtml = '';
	if(in_array($type,array('radio', 'checkbox'))){
		$checkedhtml = $value == $checked ? ' checked' : '';
	}else{
		$checkedhtml = ' size="'.$size.'" '.($checked ? $checked : '');
	}
	echo('<input type="'.$type.'" name="'.$name.'" Value="'.$value.'" '.$checkedhtml.'>');
}
function rcache($cachename){
		if(!$cachename){
			cpmsg('chache_name_empty');
		}
		$cachefile=MODEPATH.'./cache/cache_'.$cachename.'.php';
		!@file_exists($cachefile) && cache();
		
		return $cachefile;
	}
function checkupfile($file) {
	return function_exists('is_uploaded_file') && (is_uploaded_file($file) || is_uploaded_file(str_replace('\\\\', '\\', $file)));
}
function uploadfile($varname='attach',$tofilename=''){
	global $_FILES,$time,$attachdir,$db,$attachdesc;
	$attachments = $attacharray = array();
		if(isset($_FILES[$varname]) && is_array($_FILES[$varname])) {
			foreach($_FILES[$varname] as $key => $var) {
				foreach($var as $id => $val) {
					$attachments[$id][$key] = $val;
				}
			}
		}
		$upids=$common='';
		if(isset($attachments)) {
			$alled=array('png','jpg','gif','jpeg','bmp','swf');
			foreach($attachments AS $key => $attach){
						$attach_saved = false;
				if(!checkupfile($attach['tmp_name']) || !($attach['tmp_name'] != 'none' && $attach['tmp_name'] && $attach['name'])) {
					continue;
				}
				$filename = filter($attach['name']);
		
				$attach['ext'] = $extension = strtolower(fileext($attach['name']));
				if(substr($attach['type'], 0, 5) == 'image') {
					$attach['isimage'] = 1;
				} else {
					$attach['isimage'] = 0;
				}
				$attach['thumb'] = 0;
				$attach['name'] = htmlspecialchars($attach['name'], ENT_QUOTES);
				if(strlen($attach['name']) > 90) {
					$attach['name'] = 'abbr_'.md5($attach['name']).'.'.$extension;
				}
				if(!in_array($attach['ext'],$alled) || !$attach['ext']) {
					cpmsg('file_unaccepted');
				}
				if(empty($attach['size'])) {
					cpmsg('file_unaccepted');
				}
					
				 $attach_subdir = 'day_'.date('Ymd');
			
				$attach_dir = $attachdir.'/'.$attach_subdir;
				if(!is_dir(MODEPATH.$attach_dir)) {
					@mkdir(MODEPATH.$attach_dir, 0777);
					@fclose(@fopen(MODEPATH.$attach_dir.'/index.htm', 'w'));
				}
				$attach['attachment'] = $attach_subdir.'/';
				$attach['path'] = $attach_subdir;
			$attach['attachment'] .= preg_replace("/(php|phtml|php3|php4|jsp|exe|dll|asp|cer|asa|shtml|shtm|aspx|asax|cgi|fcgi|pl)(\.|$)/i", "_\\1\\2",
				date('Ymd').'_'.substr(md5($filename.microtime()), 6).random(6).'.'.$extension);
			$target = MODEPATH.'./'.$attachdir.'/'.stripslashes($attach['attachment']);
				if(@copy($attach['tmp_name'], $target) || (function_exists('move_uploaded_file') && @move_uploaded_file($attach['tmp_name'], $target))) {
					@unlink($attach['tmp_name']);
					$attach_saved = true;
				}
				if(!$attach_saved && @is_readable($attach['tmp_name'])) {
					@$fp = fopen($attach['tmp_name'], 'rb');
					@flock($fp, 2);
					@$attachedfile = fread($fp, $attach['size']);
					@fclose($fp);
					@$fp = fopen($target, 'wb');
					@flock($fp, 2);
					if(@fwrite($fp, $attachedfile)) {
						@unlink($attach['tmp_name']);
						$attach_saved = true;
					}
					@fclose($fp);
				}
				$attach['size'] = filesize($target);
				if($attach_saved) {
					@chmod($target, 0644);
					if(in_array($attach['ext'], array('jpg', 'jpeg', 'gif', 'png', 'swf', 'bmp')) && function_exists('getimagesize') && !@getimagesize($target)) {
						@unlink($target);
						cpmsg('file_unaccepted');
					}
				}
				$attach['description'] = textcut(htmlconvert($attachdesc[$key]), 100);
		
				$attacharray[$key] = $attach;
			}
		}
		
		return $attacharray ? $attacharray : false;
}
// sortselect(sort array group by upid, selected id, funtion get sub group sortid, sort list level number)
function sortselect($sorts = array(),$checkid=0,$id=0,$now=0){
	$lists='';
	if(count($sorts[$id])) {
		foreach($sorts[$id] as $key => $sort){
			$selected = $sort['id'] == $checkid ? ' selected' : '';
			$lists.= '<option value="'.$sort['id'].'"'.$selected.'>'.str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;',$now).$sort['sortname']."</option>";
			if(count($sorts[$sort['id']])) {
				$lists.=sortselect($sorts,$checkid,$sort['id'],$now+1);
						
			}
		}
	}
	return $lists;	
}
// getupfloders(sort array group by id, now sortid)
function getupfloders($sorts = array(),$id=0){
	$list = $sorts[$id];
	if($list[upid]>0) {
		$lists.=getupfloders($sorts,$list[upid]);
		
	}
	$lists.='/'.$list['folders'];
	
	return $lists;	
}
// checktype(sort array group by id, from id, move to id)
function checktype($sorts = array(),$id=0,$checkid=0){				
	$list = $sorts[$checkid];
	if($id == $checkid) {
			return true;		
	}
	if($list[upid]) {
		return checktype($sorts,$id,$list[upid]);
	}
		
}
function mkpaths($paths){
	if($paths) {
		$listpath = explode('/',$paths);
		$mkpath='';
		for($i=1;$i<=count($listpath);$i++) {
			$mkpath = $mkpath.'/'.$listpath[$i];
			if(!is_dir(MODEPATH.'.'.$mkpath)){
				if(!@mkdir(MODEPATH.'.'.$mkpath,0777)) {
						cpmsg('file_dir_error');
				}
			}
		}
	}
}
function lockfile($floder){
	if(!is_dir(MODEPATH.'.'.$floder)) {
		cpmsg('file_dir_error');
		
	}
	
    if ($dh = @opendir(MODEPATH.'.'.$floder)) {
        while (($file = readdir($dh)) !== false) {
			if ($file != "." && $file != "..") {
				echo MODEPATH.'.'.$floder. '/' . $file."<br>";
				if(is_dir(MODEPATH.'.'.$floder. '/' . $file)) {
					lockfile($floder. '/' . $file);	
					writetofile(MODEPATH.'.'.$floder. '/'.$file.'/' . 'lockfile',1);
					
				}			
	
			}   
        }
        closedir($dh);
    }
}
function clearfolder($floder){
	if(!is_dir(MODEPATH.'.'.$floder)) {
		return false;
	}
	if(in_array($floder,array('.','./','/','.//')) || file_exists(MODEPATH.'.'.$floder. '/' . 'lockfile')) {
		cpmsg('file_dir_error');
		
	}	
    if ($dh = opendir(MODEPATH.'.'.$floder)) {
        while (($file = readdir($dh)) !== false) {
			if ($file != "." && $file != "..") {		
				if(is_dir(MODEPATH.'.'.$floder. '/' . $file)) {
					clearfolder($floder. '/' . $file);						
					@rmdir(MODEPATH.'.'.$floder. '/' . $file);
				}else{
					@unlink(MODEPATH.'.'.$floder. '/' . $file);
				}					
	
			}   
        }
        closedir($dh);
    }
}
function checkdir($floder){
	if(!is_dir(MODEPATH.'.'.$floder)) {
		return false;
		
	}
	$files = array();
    if ($dh = @opendir(MODEPATH.'.'.$floder)) {
        while (($file = readdir($dh)) !== false) {
			if ($file != "." && $file != "..") {		
				if(is_file(MODEPATH.'.'.$floder. '/' . $file)) {	
					$files[]=$floder. '/' . $file;
				}		
			}   
        }
        closedir($dh);
    }
	return $files;
}

function sqldumptable($table, $startfrom = 0, $currsize = 0) {
	global $db, $dbcut, $startrow, $extended, $dbformat, $sqlcharset, $dumpcharset, $dbtextype, $complete, $excepttables;
	$offset = 300;
	$tabledump = '';
	$tablefields = array();

	$query = $db->query("SHOW FULL COLUMNS FROM $table", 'SILENT');
	if(!$query && $db->errno() == 1146) {
		return;
	} elseif(!$query) {
		$dbtextype = FALSE;
	} else {
		while($fieldrow = $db->fetch_array($query)) {
			$tablefields[] = $fieldrow;
		}
	}
	if(!$startfrom) {

		$createtable = $db->query("SHOW CREATE TABLE $table", 'SILENT');

		if(!$db->error()) {
			$tabledump = "DROP TABLE IF EXISTS $table;\n";
		} else {
			return '';
		}

		$create = $db->fetch_row($createtable);

		if(strpos($table, '.') !== FALSE) {
			$tablename = substr($table, strpos($table, '.') + 1);
			$create[1] = str_replace("CREATE TABLE $tablename", 'CREATE TABLE '.$table, $create[1]);
		}
		$tabledump .= $create[1];

		if($dbformat == 'MYSQL41' && $db->version() < '4.1') {
			$tabledump = preg_replace("/TYPE\=(.+)/", "ENGINE=\\1 DEFAULT CHARSET=".$dumpcharset, $tabledump);
		}
		if($db->version() > '4.1' && $sqlcharset) {
			$tabledump = preg_replace("/(DEFAULT)*\s*CHARSET=.+/", "DEFAULT CHARSET=".$sqlcharset, $tabledump);
		}

		$query = $db->query("SHOW TABLE STATUS LIKE '$table'");
		$tablestatus = $db->fetch_array($query);
		$tabledump .= ($tablestatus['Auto_increment'] ? " AUTO_INCREMENT=$tablestatus[Auto_increment]" : '').";\n\n";
		if($dbformat == 'MYSQL40' && $db->version() >= '4.1' && $db->version() < '5.1') {
			if($tablestatus['Auto_increment'] <> '') {
				$temppos = strpos($tabledump, ',');
				$tabledump = substr($tabledump, 0, $temppos).' auto_increment'.substr($tabledump, $temppos);
			}
			if($tablestatus['Engine'] == 'MEMORY') {
				$tabledump = str_replace('TYPE=MEMORY', 'TYPE=HEAP', $tabledump);
			}
		}
	}

	if(!in_array($table, $excepttables)) {
		$tabledumped = 0;
		$numrows = $offset;
		$firstfield = $tablefields[0];

		if($extended == '0') {
			while($currsize + strlen($tabledump) + 500 < $dbcut * 1000 && $numrows == $offset) {
				if($firstfield['Extra'] == 'auto_increment') {
					$selectsql = "SELECT * FROM $table WHERE $firstfield[Field] > $startfrom LIMIT $offset";
				} else {
					$selectsql = "SELECT * FROM $table LIMIT $startfrom, $offset";
				}
				$tabledumped = 1;
				$rows = $db->query($selectsql);
				$numfields = $db->num_fields($rows);

				$numrows = $db->num_rows($rows);
				while($row = $db->fetch_row($rows)) {
					$comma = $t = '';
					for($i = 0; $i < $numfields; $i++) {
						$t .= $comma.($dbtextype && !empty($row[$i]) && (strexists($tablefields[$i]['Type'], 'char') || strexists($tablefields[$i]['Type'], 'text')) ? '0x'.bin2hex($row[$i]) : '\''.mysql_escape_string($row[$i]).'\'');
						$comma = ',';
					}
					if(strlen($t) + $currsize + strlen($tabledump) + 500 < $dbcut * 1000) {
						if($firstfield['Extra'] == 'auto_increment') {
							$startfrom = $row[0];
						} else {
							$startfrom++;
						}
						$tabledump .= "INSERT INTO $table VALUES ($t);\n";
					} else {
						$complete = FALSE;
						break 2;
					}
				}
			}
		} else {
			while($currsize + strlen($tabledump) + 500 < $dbcut * 1000 && $numrows == $offset) {
				if($firstfield['Extra'] == 'auto_increment') {
					$selectsql = "SELECT * FROM $table WHERE $firstfield[Field] > $startfrom LIMIT $offset";
				} else {
					$selectsql = "SELECT * FROM $table LIMIT $startfrom, $offset";
				}
				$tabledumped = 1;
				$rows = $db->query($selectsql);
				$numfields = $db->num_fields($rows);

				if($numrows = $db->num_rows($rows)) {
					$t1 = $comma1 = '';
					while($row = $db->fetch_row($rows)) {
						$t2 = $comma2 = '';
						for($i = 0; $i < $numfields; $i++) {
							$t2 .= $comma2.($dbtextype && !empty($row[$i]) && (strexists($tablefields[$i]['Type'], 'char') || strexists($tablefields[$i]['Type'], 'text'))? '0x'.bin2hex($row[$i]) : '\''.mysql_escape_string($row[$i]).'\'');
							$comma2 = ',';
						}
						if(strlen($t1) + $currsize + strlen($tabledump) + 500 < $dbcut * 1000) {
							if($firstfield['Extra'] == 'auto_increment') {
								$startfrom = $row[0];
							} else {
								$startfrom++;
							}
							$t1 .= "$comma1 ($t2)";
							$comma1 = ',';
						} else {
							$tabledump .= "INSERT INTO $table VALUES $t1;\n";
							$complete = FALSE;
							break 2;
						}
					}
					$tabledump .= "INSERT INTO $table VALUES $t1;\n";
				}
			}
		}

		$startrow = $startfrom;
		$tabledump .= "\n";
	}

	return $tabledump;
}
function strexists($haystack, $needle) {
	return !(strpos($haystack, $needle) === FALSE);
}

function splitsql($sql) {
	$sql = str_replace("\r", "\n", $sql);
	$ret = array();
	$num = 0;
	$queriesarray = explode(";\n", trim($sql));
	unset($sql);
	foreach($queriesarray as $query) {
		$queries = explode("\n", trim($query));
		foreach($queries as $query) {
			$ret[$num] .= $query[0] == "#" ? NULL : $query;
		}
		$num++;
	}
	return($ret);
}
function supe_dbconnect() {

	global $supe, $db;

	if(!$supe['status']) {
		return FALSE;
	} elseif(empty($supe['dbmode'])) {
		$supe['db'] = $db;
	} elseif(empty($supe['db'])) {
		$supe['db'] = new dbstuff;
		$supe['link'] = $supe['db']->connect($supe['dbhost'], $supe['dbuser'], $supe['dbpw'], $supe['dbname'], $supe['pconnect'], FALSE);
		$supe['status'] = $supe['link'] ? $supe['link'] : FALSE;
	}
}
?>