<?

function json_return($array)
{
	if(function_exists('json_encode')){
		return json_encode($array);
	} else{
		 require_once(ROOT_PATH."lib/json.php");
		 $json   =       new Services_JSON();
		 return $json->encode($array);
	}
}

function encrypt_admin_pass($admin_pass)
{
	$admin_pass	=	md5(md5($admin_pass));	
	$admin_pass	=	substr($admin_pass,1);
	$admin_pass	=	md5($admin_pass);
	return $admin_pass;
}


function pagination_arr($page, $count, $pagesize=10,$area=10,$page_url_str='page')
{
	$page		= intval($page);
	$count		= intval($count);
	$pagesize	= intval($pagesize);
	$request_uri		=		$_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'];
	$url		= preg_replace("/&".preg_filtrate($page_url_str)."=\d+/", "", $request_uri);
	$url		= preg_replace("/&".preg_filtrate($page_url_str)."=/", "", $url);
	if(!strstr($url,'?')){
		$url	.='?';
	}	
	
	if($pagesize < 4){
		$pagesize	= 4;
	}
	if($area < 4){
		$area	= 4;
	}
	if($page < 1){
		$page	= 1;
	}
	$maxpage	= ceil($count / $pagesize);
	if($maxpage < 1){
		$maxpage	= 1;
	}
	if($page > $maxpage){
		$page	= $maxpage;
	}
	$first_page	= 1;
	$last_page	= $maxpage;
	$middle		= intval($area / 2);
	if($maxpage > $area){
		if(($page + $middle) > $maxpage){
			$first_page		= $maxpage - $area + 1;
		}else{
			$first_page		= $page - $middle;
			$last_page		= $page + $middle - 1;
			if($first_page < 1){
				$first_page	= 1;
				$last_page	= $area;
			}
		}
	}
	$thepage	= array();
	if($page == 1){
	}else{
		$thepage['first']		=		$url."&".$page_url_str."=1";	
	}
	for($i=$first_page; $i<=$last_page; $i++){
		$thepage[$i]		=	$url."&".$page_url_str."=".$i;	
	}
	if($page == $maxpage){
	}else{
		$thepage['next'] 	=	$url."&".$page_url_str."=".$maxpage;
	}
	$result[thepage]	= $thepage;
	$result[total]		= $count;
	$result[start]		= ($page - 1) * $pagesize;
	$result[page]		= $page;
	$result[maxpage]	= $maxpage;
	return $result;
}

function preg_filtrate($t){
	$t		=	str_replace(array('\\','/','^','$','*','+','?','|','.','\(','\)','[',']','!','-','{','}'),
								array('\\\\','\/','\^','\$','\*','\+','\?','\|','\.','\(','\)','\[','\]','\!','\-','\{','\}'),
								$t);
	return $t;
}

function name_from_url($url)
{
   $url  = str_replace(" ", "_",$url);
   $url  = str_replace("'", ".",$url);
   $url  = str_replace('"', ".",$url);
   $url  = str_replace(array("/", "\\", ":", "@", "|",'-'), "_", $url);
   $url  = str_replace(array("*", "?", ">", "<", '""', ",", "#",'%',"!","&",'$',';'), "", $url);
   $url  = strtolower($url);
	$url	= rawurlencode($url);
	return $url;
}


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



function get_gd_version()
{
    static $version = -1;

    if ($version >= 0){
        return $version;
    }
    if (!extension_loaded('gd')){
        $version = 0;
    }else{
        if (PHP_VERSION >= '4.3'){
            if (function_exists('gd_info')){
                $ver_info = gd_info();
                preg_match('/\d/', $ver_info['GD Version'], $match);
                $version = $match[0];
            }else{
                if (function_exists('imagecreatetruecolor')){
                    $version = 2;
                }elseif (function_exists('imagecreate')){
                    $version = 1;
                }
            }
        }else{
            if (preg_match('/phpinfo/', ini_get('disable_functions'))){
                $version = 1;
            }else{
               ob_start();
               phpinfo(8);
               $info = ob_get_contents();
               ob_end_clean();
               $info = stristr($info, 'gd version');
               preg_match('/\d/', $info, $match);
               $version = $match[0];
            }
         }
    }
    return $version;
}

function get_ip_area($ip)
{
	 session_write_close();	//php session file_get_conents bug?
	 $area	=	@file_get_contents('http://api.hostip.info/country.php?ip='.$ip);	   
    return $area;
}


function get_real_ip()
{
    static $realip = NULL;
    if ($realip !== NULL){
        return $realip;
    }
    if (isset($_SERVER)){
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($arr AS $ip){
                $ip = trim($ip);
                if ($ip != 'unknown'){
                    $realip = $ip;
                    break;
                }
            }
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }else{
            if (isset($_SERVER['REMOTE_ADDR'])){
                $realip = $_SERVER['REMOTE_ADDR'];
            }else{
                $realip = '0.0.0.0';
            }
        }
    }else{
        if (getenv('HTTP_X_FORWARDED_FOR')){
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }elseif (getenv('HTTP_CLIENT_IP')){
            $realip = getenv('HTTP_CLIENT_IP');
        }else{
            $realip = getenv('REMOTE_ADDR');
        }
    }
    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
    return $realip;
}

function get_user_browser()
{
    if (empty($_SERVER['HTTP_USER_AGENT'])){
        return '';
    }

    $agent       = $_SERVER['HTTP_USER_AGENT'];
    $browser     = '';
    $browser_ver = '';

    if (preg_match('/MSIE\s([^\s|;]+)/i', $agent, $regs)){
        $browser     = 'Internet Explorer';
        $browser_ver = $regs[1];
    }elseif (preg_match('/FireFox\/([^\s]+)/i', $agent, $regs)){
        $browser     = 'FireFox';
        $browser_ver = $regs[1];
    }elseif (preg_match('/Maxthon/i', $agent, $regs)){
        $browser     = '(Internet Explorer ' .$browser_ver. ') Maxthon';
        $browser_ver = '';
    }elseif (preg_match('/Opera[\s|\/]([^\s]+)/i', $agent, $regs)){
        $browser     = 'Opera';
        $browser_ver = $regs[1];
    }elseif (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs)){
        $browser     = 'OmniWeb';
        $browser_ver = $regs[2];
    }elseif (preg_match('/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs)){
        $browser     = 'Netscape';
        $browser_ver = $regs[2];
    }elseif (preg_match('/safari\/([^\s]+)/i', $agent, $regs)){
        $browser     = 'Safari';
        $browser_ver = $regs[1];
    }elseif (preg_match('/NetCaptor\s([^\s|;]+)/i', $agent, $regs)){
        $browser     = '(Internet Explorer ' .$browser_ver. ') NetCaptor';
        $browser_ver = $regs[1];
    }elseif (preg_match('/Lynx\/([^\s]+)/i', $agent, $regs)){
        $browser     = 'Lynx';
        $browser_ver = $regs[1];
    }
    if (!empty($browser)){
       return addslashes($browser . ' ' . $browser_ver);
    }else{
        return 'Unknow browser';
    }
}

function get_os()
{
    if (empty($_SERVER['HTTP_USER_AGENT'])){
        return 'Unknown';
    }

    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    $os    = '';

    if (strpos($agent, 'win') !== false){
        if (strpos($agent, 'nt 5.1') !== false){
            $os = 'Windows XP';
        }elseif (strpos($agent, 'nt 5.2') !== false){
            $os = 'Windows 2003';
        }elseif (strpos($agent, 'nt 5.0') !== false){
            $os = 'Windows 2000';
        }elseif (strpos($agent, 'nt 6.0') !== false){
            $os = 'Windows Vista';
        }elseif (strpos($agent, 'nt') !== false){
            $os = 'Windows NT';
        }elseif (strpos($agent, 'win 9x') !== false && strpos($agent, '4.90') !== false){
            $os = 'Windows ME';
        }elseif (strpos($agent, '98') !== false){
            $os = 'Windows 98';
        }elseif (strpos($agent, '95') !== false){
            $os = 'Windows 95';
        }elseif (strpos($agent, '32') !== false){
            $os = 'Windows 32';
        }elseif (strpos($agent, 'ce') !== false){
            $os = 'Windows CE';
        }
    }elseif (strpos($agent, 'linux') !== false){
        $os = 'Linux';
    }elseif (strpos($agent, 'unix') !== false){
        $os = 'Unix';
    }elseif (strpos($agent, 'sun') !== false && strpos($agent, 'os') !== false){
        $os = 'SunOS';
    }elseif (strpos($agent, 'ibm') !== false && strpos($agent, 'os') !== false){
        $os = 'IBM OS/2';
    }elseif (strpos($agent, 'mac') !== false && strpos($agent, 'pc') !== false){
        $os = 'Macintosh';
    }elseif (strpos($agent, 'powerpc') !== false){
        $os = 'PowerPC';
    }elseif (strpos($agent, 'aix') !== false){
        $os = 'AIX';
    }elseif (strpos($agent, 'hpux') !== false){
        $os = 'HPUX';
    }elseif (strpos($agent, 'netbsd') !== false){
        $os = 'NetBSD';
    }elseif (strpos($agent, 'bsd') !== false){
        $os = 'BSD';
    }elseif (strpos($agent, 'osf1') !== false){
        $os = 'OSF1';
    }elseif (strpos($agent, 'irix') !== false){
        $os = 'IRIX';
    }elseif (strpos($agent, 'freebsd') !== false){
        $os = 'FreeBSD';
    }elseif (strpos($agent, 'teleport') !== false){
        $os = 'teleport';
    }elseif (strpos($agent, 'flashget') !== false){
        $os = 'flashget';
    }elseif (strpos($agent, 'webzip') !== false){
        $os = 'webzip';
    }elseif (strpos($agent, 'offline') !== false){
        $os = 'offline';
    }else{
        $os = 'Unknown';
    }

    return $os;
}

function is_spider($record = true)
{
    static $spider = NULL;

    if($spider !== NULL){
        return $spider;
    }

    if(empty($_SERVER['HTTP_USER_AGENT'])){
        $spider = '';
        return '';
    }

    $searchengine_bot = array(
        'googlebot',
        'mediapartners-google',
        'baiduspider+',
        'msnbot',
        'yodaobot',
        'yahoo! slurp;',
        'yahoo! slurp china;',
        'iaskspider',
        'sogou web spider',
        'sogou push spider'
    );

    $searchengine_name = array(
        'GOOGLE',
        'GOOGLE ADSENSE',
        'BAIDU',
        'MSN',
        'YODAO',
        'YAHOO',
        'Yahoo China',
        'IASK',
        'SOGOU',
        'SOGOU'
    );
    $spider = strtolower($_SERVER['HTTP_USER_AGENT']);
    foreach ($searchengine_bot AS $key => $value){
        if (strpos($spider, $value) !== false){
            $spider = $searchengine_name[$key];
            if ($record === true){
            }
            return $spider;
        }
    }
    $spider = '';
    return '';
}


function save_searchengine_keyword($domain, $path)
{
    if(strpos($domain, 'google.com.tw') !== false && preg_match('/q=([^&]*)/i', $path, $regs)){
       $searchengine = 'GOOGLE TAIWAN';
       $keywords = urldecode($regs[1]); // google taiwan
    }
    if(strpos($domain, 'google.cn') !== false && preg_match('/q=([^&]*)/i', $path, $regs)){
       $searchengine = 'GOOGLE CHINA';
       $keywords = urldecode($regs[1]); // google china
    }
    if(strpos($domain, 'google.com') !== false && preg_match('/q=([^&]*)/i', $path, $regs)){
       $searchengine = 'GOOGLE';
       $keywords = urldecode($regs[1]); // google
    }elseif(strpos($domain, 'baidu.') !== false && preg_match('/wd=([^&]*)/i', $path, $regs)){
       $searchengine = 'BAIDU';
       $keywords = urldecode($regs[1]); // baidu
    }elseif(strpos($domain, 'baidu.') !== false && preg_match('/word=([^&]*)/i', $path, $regs)){
       $searchengine = 'BAIDU';
       $keywords = urldecode($regs[1]); // baidu
    }elseif(strpos($domain, '114.vnet.cn') !== false && preg_match('/kw=([^&]*)/i', $path, $regs)){
       $searchengine = 'CT114';
       $keywords = urldecode($regs[1]); // ct114
    }elseif(strpos($domain, 'iask.com') !== false && preg_match('/k=([^&]*)/i', $path, $regs)){
       $searchengine = 'IASK';
       $keywords = urldecode($regs[1]); // iask
    }elseif(strpos($domain, 'soso.com') !== false && preg_match('/w=([^&]*)/i', $path, $regs)){
       $searchengine = 'SOSO';
       $keywords = urldecode($regs[1]); // soso
    }elseif(strpos($domain, 'sogou.com') !== false && preg_match('/query=([^&]*)/i', $path, $regs)){
       $searchengine = 'SOGOU';
       $keywords = urldecode($regs[1]); // sogou
    }elseif(strpos($domain, 'so.163.com') !== false && preg_match('/q=([^&]*)/i', $path, $regs)){
       $searchengine = 'NETEASE';
       $keywords = urldecode($regs[1]); // netease
    }elseif(strpos($domain, 'yodao.com') !== false && preg_match('/q=([^&]*)/i', $path, $regs)){
       $searchengine = 'YODAO';
       $keywords = urldecode($regs[1]); // yodao
    }elseif(strpos($domain, 'zhongsou.com') !== false && preg_match('/word=([^&]*)/i', $path, $regs)){
       $searchengine = 'ZHONGSOU';
       $keywords = urldecode($regs[1]); // zhongsou
    }elseif(strpos($domain, 'search.tom.com') !== false && preg_match('/w=([^&]*)/i', $path, $regs)){
       $searchengine = 'TOM';
       $keywords = urldecode($regs[1]); // tom
    }elseif(strpos($domain, 'live.com') !== false && preg_match('/q=([^&]*)/i', $path, $regs)){
       $searchengine = 'MSLIVE';
       $keywords = urldecode($regs[1]); // MSLIVE
    }elseif(strpos($domain, 'tw.search.yahoo.com') !== false && preg_match('/p=([^&]*)/i', $path, $regs)){
       $searchengine = 'YAHOO TAIWAN';
       $keywords = urldecode($regs[1]); // yahoo taiwan
    }elseif (strpos($domain, 'cn.yahoo.') !== false && preg_match('/p=([^&]*)/i', $path, $regs)){
       $searchengine = 'YAHOO CHINA';
       $keywords = urldecode($regs[1]); // yahoo china
    }elseif (strpos($domain, 'yahoo.') !== false && preg_match('/p=([^&]*)/i', $path, $regs)){
       $searchengine = 'YAHOO';
       $keywords = urldecode($regs[1]); // yahoo
    }elseif(strpos($domain, 'msn.com.tw') !== false && preg_match('/q=([^&]*)/i', $path, $regs)){
       $searchengine = 'MSN TAIWAN';
       $keywords = urldecode($regs[1]); // msn taiwan
    }elseif(strpos($domain, 'msn.com.cn') !== false && preg_match('/q=([^&]*)/i', $path, $regs)){
       $searchengine = 'MSN CHINA';
       $keywords = urldecode($regs[1]); // msn china
    }elseif(strpos($domain, 'msn.com') !== false && preg_match('/q=([^&]*)/i', $path, $regs)){
       $searchengine = 'MSN';
       $keywords = urldecode($regs[1]); // msn
    }

    if(!empty($keywords)){
       $gb_search = array('YAHOO CHINA', 'TOM', 'ZHONGSOU', 'NETEASE', 'SOGOU', 'SOSO', 'IASK', 'CT114', 'BAIDU');
       if(in_array($searchengine, $gb_search)){
           $keywords = iconv('GBK', 'UTF-8', $keywords);
       }
			global $db_obj;	
			$keyword_arr	=	$db_obj->getRecord("SELECT keyword_id,count FROM {$db_obj->db_pre}keywords WHERE keyword='".$db_obj->escape($keywords)."' AND searchengine='{$searchengine}' AND date='".date('Y-m-d')."'");
			if(!$keyword_arr){
				$keyword_id	=	$db_obj->addRecord("{$db_obj->db_pre}keywords", array(
								'date'				=>	date('Y-m-d'),
								'searchengine'		=>	$searchengine,
								'keyword'			=>	$keywords,
								'count'				=>	1,
							));
			}else{
				$keyword_id	=	$keyword_arr['keyword_id'];
				$db_obj->updateRecord("{$db_obj->db_pre}keywords"," keyword_id=$keyword_id",array('count'=>$count+1));

			}
    		return $keyword_id;
	 }
}

function sendmail($to,$title,$desc,$from='',$from_name='',$port,$smtp_arr=array(),$reply_to='',$attachment=array())
{
	require_once(ROOT_PATH."lib/class.smtp.php");
	require_once(ROOT_PATH."lib/class.phpmailer.php");
	$mail			= new PHPMailer();
	if($smtp_arr['host']&&$smtp_arr['user']&&$smtp_arr['pass']){
		$mail->IsSMTP();
		$mail->Host		=	$smtp_arr['host'];
		$mail->Username = $smtp_arr['user'];                        // SMTP username
      $mail->Password = $smtp_arr['pass'];                    // SMTP password
		$mail->SMTPAuth = true;                         // turn on SMTP authentication
	}else{
		$mail->IsMail();
	}
	$mail->FromName = $from_name;
   $mail->AddAddress($to);
   $mail->WordWrap = 50;                                 // set word wrap to 50 characters	

	$mail->From    = $from;	
	$mail->Port	=	$port;
	$mail->IsHTML(true);                                  
   $mail->Subject = $title;
   $mail->Body    = $desc;

	if($attachment){
		foreach($attachment as $val){
			$mail->AddAttachment($val); 	
		}	
	}
	if(!$reply_to){
		$reply_to	=	$from;
	}
	$mail->AddReplyTo($reply_to,$from_name);
	if($mail->Send()){
	 	return true;
   }else{
		return false;
   }	
}



function dir_to_url($dir)
{
	if(!$dir){
		return false;
	}
	if(preg_match('|^http://|si',$dir)||preg_match('|^/|si',$dir)){
		return $dir;
	}
	global $glo_domain_directory,$glo_domain_name;
	$tmp_arr		=	explode('/',$dir);
	$url_arr		=	array_map('rawurldecode',$tmp_arr);
	$url			=	implode('/',$url_arr);
	return preg_replace('|^'.ROOT_PATH.'|si',$glo_domain_name.$glo_domain_directory,UPLOAD_DIR).$url;
}

function get_url($url,$name='')
{
	global $glo_config_arr;
	if(!$glo_config_arr['url_rewrite']['value']){
		return $url;
	}
	preg_match('/(download|support|article|article_list|about|purchase|product|soft|channel)\.php/si',$url,$type);
	$type	=	$type[1];
	
	if($name){
		$name		=	name_from_url($name);
	}
	$parameter_url_arr	=	explode('&',$url);
	$parameter_arr			=	array();
	foreach($parameter_url_arr as $val){
		if(strstr($url,'?')){
			$val	=	preg_replace('/.*?\?/si','',$val);
		}	
		$val_arr	=	explode('=',$val);
		if($val_arr[1]){
			$parameter_arr[$val_arr[0]]	=	$val_arr[1];
		}
	}	
	if(isset($parameter_arr['cat_id'])){
		if($name){
			$name	.='-';
		}
		$name	.=	'category_'.$parameter_arr['cat_id'];
	}
	if(isset($parameter_arr['page'])){
		if($name){
			$name	.='-';
		}
		$name	.=	'page_'.$parameter_arr['page'];
	}

	switch($type){
		case 'soft':
				$url	=	$name.'-'.$parameter_arr['software_id'].'-software.html';
			break;

		case 'article':
				$url	=	$name.'-'.$parameter_arr['article_id'].'-article.html';
			break;	
	
		case 'channel':
				$url	=	$name.'-'.$parameter_arr['channel_id'].'-channel.html';
			break;	

		case 'product':
				if($name){
					$name	=	'-'.$name;
				}	
				$url	=	'product'.$name.'.html';
			break;

		case 'download':
				if($name){
					$name	=	'-'.$name;
				}	
				$url	=	'download'.$name.'.html';
			break;

		case 'purchase':
				if($name){
					$name	=	'-'.$name;
				}		
				$url	=	'purchase'.$name.'.html';
			break;

		case 'article_list':
				if($name){
					$name	=	'-'.$name;
				}	
				$url	=	'article-list'.$name.'.html';
			break;

		case 'support':
				if($name){
					$name	=	'-'.$name;
				}	
				$url	=	'support'.$name.'.html';	
			break;

		case 'about':
				if($name){
					$name	=	'-'.$name;
				}	
				$url	=	'about'.$name.'.html';
			break;
		default :
				return $url;
			break;
	}
	return $url;
}

function file_ext_name ($filename) 
{  
	$filearea=explode(".",$filename);  
	$partnum=count($filearea);          
	return $filearea[$partnum-1]; 
}

function storage_encode($data)
{
	return  base64_encode(serialize($data));
}

function storage_dencode($data)
{
	return unserialize(base64_decode($data));
}

function sub_str($str, $length=0,$append=true)
{
    $str = trim($str);
    $strlength = strlen($str);

    if ($length == 0 || $length >= $strlength){
        return $str;
    }elseif ($length < 0){
        $length = $strlength + $length;
        if ($length < 0){
            $length = $strlength;
        }
    }

    if (function_exists('mb_substr')){
        $newstr = mb_substr($str, 0, $length, SIT_CHARSET);
    }elseif (function_exists('iconv_substr')){
        $newstr = iconv_substr($str, 0, $length, SIT_CHARSET);
    }else{
        //$newstr = trim_right(substr($str, 0, $length));
        $newstr = substr($str, 0, $length);
    }

	 if ($append && $str != $newstr){
        $newstr .= '...';
    }
    return $newstr;
}

function get_basename($filename)
{
	    return preg_replace('/^.+[\\\\\\/]/', '', $filename);
}


function file_mode_info($file_path)
{
    if (!file_exists($file_path)){
        return false;
    }
    $mark = 0;
    if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'){
        $test_file = $file_path . '/test.txt';
        if (is_dir($file_path)){
            $dir = @opendir($file_path);
            if ($dir === false){
                return $mark; 
            }
            if (@readdir($dir) !== false){
                $mark ^= 1; 
            }
            @closedir($dir);
            $fp = @fopen($test_file, 'wb');
            if ($fp === false){
                return $mark; 
            }
            if (@fwrite($fp, 'directory access testing.') !== false){
                $mark ^= 2; 
            }
            @fclose($fp);
            @unlink($test_file);

            $fp = @fopen($test_file, 'ab+');
            if ($fp === false){
                return $mark;
            }
            if (@fwrite($fp, "modify test.\r\n") !== false){
                $mark ^= 4;
            }
            @fclose($fp);

            if (@rename($test_file, $test_file) !== false){
                $mark ^= 8;
            }
            @unlink($test_file);
        }
        
		  elseif (is_file($file_path)){
            $fp = @fopen($file_path, 'rb');
            if ($fp){
                $mark ^= 1; 
            }
            @fclose($fp);
            
				$fp = @fopen($file_path, 'ab+');
            if ($fp && @fwrite($fp, '') !== false){
                $mark ^= 6; 
            }
            @fclose($fp);

            if (@rename($test_file, $test_file) !== false){
                $mark ^= 8;
            }
        }
    }
    else{
        if (@is_readable($file_path)){
            $mark ^= 1;
        }

        if (@is_writable($file_path)){
            $mark ^= 14;
        }
    }
    return decbin($mark);
}
