<?php

/**
 *      [Dzz!] (C)2001-2099 dzz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: function_dzz_core.php 1000 2011-5-31 15:41:43Z angel rain $
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}
define('SYSICON_FOLDER','dzz/images/sysicon/foldericon/');
define('SYSICON_URL','dzz/images/sysicon/urlicon/');

if (!function_exists('json_decode') ){
    function json_decode($content, $assoc=false){
        require_once DISCUZ_ROOT.'/dzz/class/class_json.php'; 
        if ( $assoc ){
                    $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
        } else {
                    $json = new Services_JSON;
        }
        return $json->decode($content);
    }
}

if ( !function_exists('json_encode') ){
    function json_encode($content){
	   require_once DISCUZ_ROOT.'/dzz/class/class_json.php'; 
		$json = new Services_JSON;
        return $json->encode($content);
    }
}

function arr_encode(&$array){
	foreach($array as $key => $value){
		if(is_array($value)){
			arr_encode($array[$key]);
		}else{
			$array[$key] = (diconv(stripslashes($value),CHARSET,'UTF-8'));
		}
	}
}
function json_encode_gbk($array){
	global $_G;
	arr_encode($array);
	$json = json_encode($array);
	return ($json);
}
function getBuySize($uid){
	global $_G;
	$buysize=0;
	$query=DB::query("select `spacesize`,`num` from ".DB::table('dzz_space_record')." where uid='{$uid}' AND `endtime`>'{$_G[timestamp]}'");
	while($value=DB::fetch($query)){
		$buysize+=($value['spacesize']*$value['num']);
	}
	if(DB::result_first("select COUNT(*) from ".DB::table('dzz_userconfig_field')." where uid='{$uid}'")){
		DB::update('dzz_userconfig_field',array('buysize'=>$buysize),"uid='{$uid}'"); 
	}else{
		DB::insert('dzz_userconfig_field',array('buysize'=>$value,'uid'=>$uid),1,1); 
	}
	return $buysize;
}

function replace_canshu($str){
	global $_G,$space;
	$replacearr=array('{DZZSCRIPT}'=>DZZSCRIPT,'{uid}'=>$space['uid']);
	$search=array();
	$replace=array();
	foreach($replacearr as $key=>$value){
		$search[]=$key;
		$replace[]=$value;
	}
	return str_replace($search,$replace,$str);
}
function dzz_libfile($libname, $folder = '') {
	$libpath = DISCUZ_ROOT.'/dzz/'.$folder;
	if(strstr($libname, '/')) {
		list($pre, $name) = explode('/', $libname);
		return realpath("{$libpath}/{$pre}/{$pre}_{$name}.php");
	} else {
		return realpath("{$libpath}/{$libname}.php");
	}
}
function dzzlang($file, $langvar = null, $vars = array(), $default = null) {
	global $_G;
	list($path, $file) = explode('/', $file);
	if(!$file) {
		$file = $path;
		$path = '';
	}
	if($path==''){
		$vars=explode(':',$file);
		if(count($vars)==2){
			list($plugfolder,$file)=explode(':',$file);
			$key = 'plugin_'. $plugfolder.'_'.$file;
			if(!isset($_G['dzzlang'][$key])) {
				include DISCUZ_ROOT.'./dzz/plugin/'.$plugfolder.'/lang/'.'lang_'.$file.'.php';
				$_G['dzzlang'][$key] = $lang;
			}
		}else{
			$key = $file;
			if(!isset($_G['dzzlang'][$key])) {
				include DISCUZ_ROOT.'./dzz/lang/'.($path == '' ? '' : $path.'/').'lang_'.$file.'.php';
				$_G['dzzlang'][$key] = $lang;
			}
		}
		$returnvalue = &$_G['dzzlang'];
	}else{
		$key = $path == '' ? $file : $path.'_'.$file;
		if(!isset($_G['dzzlang'][$key])) {
			include DISCUZ_ROOT.'./dzz/'.$path.'/lang/lang_'.$file.'.php';
			$_G['dzzlang'][$key] = $lang;
		}
		
		$returnvalue = &$_G['dzzlang'];
	}
	$return = $langvar !== null ? (isset($returnvalue[$key][$langvar]) ? $returnvalue[$key][$langvar] : null) : $returnvalue[$key];
	$return = $return === null ? ($default !== null ? $default : $langvar) : $return;
	$searchs = $replaces = array();
	if($vars && is_array($vars)) {
		foreach($vars as $k => $v) {
			$searchs[] = '{'.$k.'}';
			$replaces[] = $v;
		}
	}
	if(is_string($return) && strpos($return, '{_G/') !== false) {
		preg_match_all('/\{_G\/(.+?)\}/', $return, $gvar);
		foreach($gvar[0] as $k => $v) {
			$searchs[] = $v;
			$replaces[] = getglobal($gvar[1][$k]);
		}
	}
	$return = str_replace($searchs, $replaces, $return);
	return $return;
}
function getFileTypeName($type,$ext){
	$typename='';
	switch($type){
		case 'image':
			$typename=dzzlang('message','typename_image');
			break;
		case 'video':
			$typename=dzzlang('message','typename_video');
			break;
		case 'music':
			$typename=dzzlang('message','typename_music');
			break;
		case 'attach':
			$typename=dzzlang('message','typename_attach');
			break;
		case 'app':
			$typename=dzzlang('message','typename_app');
			break;
		case 'link':
			$typename=dzzlang('message','typename_link');
			break;
		case 'folder':
			$typename=dzzlang('message','typename_folder');
			break;
	}

	$name='';
	if($ext =='dzzdoc'){
		$name=dzzlang('message','extname_dzzdoc');
	}elseif($ext=='txt'){
		$name=dzzlang('message','extname_txt');
	}else{
		$name=strtoupper($ext).' '.$typename;
	}
	
	return $name;
}
function getmyappid(){
	global $_G;
	if(!$_G['uid']) return array();
	$var="dzz_myicos_".$_G['uid'];
	if($_G[$var]) return $_G[$var];
	else{
		$arr=array('0'=>'');
		$query=DB::query("select oid,icoid from ".DB::table('dzz_icos')." where type='app' and (uid='{$_G[uid]}' OR (uid='-1' and notdelete='1'))");
		while($value=DB::fetch($query)){
			$arr[$value['oid']]=$value['icoid'];
		}
		$_G[$var]=$arr;
 	}
	return $_G[$var];
}
function dzzgetspace($uid){
	global $_G;
	$space=array();
	if($uid==0){
		if($_G['adminid']==1){
			$space=array( 'uid' => 0,'self'=>2, 'username' => '', 'adminid' => 1, 'groupid' => 1, 'credits' => 0, 'timeoffset' => 9999);
		}else{
			$space=array( 'uid' => 0,'self'=>0, 'username' => '', 'adminid' => 0, 'groupid' => 7, 'credits' => 0, 'timeoffset' => 9999);
		}
	}else{
		$space=getspace($uid);
	}
	require_once libfile('function/friend');
	$space['isfriend']=friend_check($uid);

	//用户组信息
	if(!$usergroup=DB::fetch_first("select * from ".DB::table('dzz_usergroup')." where groupid='{$space[groupid]}'")){
		$usergroup=array();
	}
	$space['groupsize']=$usergroup['maxspacesize']*1024*1024;
	
	if($uid>0 && $config=DB::fetch_first("select u.thame,u.custom_filemanage,u.custom_dock,u.custom_backimg,custom_window,u.custom_topbar,u.spacename,u.metakeyword,u.metadescription,u.friend,u.status as dzzstatus,u.dateline,u.updatetime,u.usesize,f.allownewfolder,f.allowupload,f.allownewlink,f.attachextensions,f.maxattachsize,f.addsize,f.buysize from ".DB::table('dzz_userconfig')." u
								LEFT JOIN ".DB::table('dzz_userconfig_field')." f ON u.uid=f.uid
								 where u.uid='$uid'")){
		$arr=DB::fetch_first("select * from ".DB::table('dzz_thame')." where id='{$config[thame]}'");
		if(!$arr){
			$arr=DB::fetch_first("select * from ".DB::table('dzz_thame')." where `default`='1'");
		}
		unset($config['thame']);
		$space['thame']=array(
					'folder'=>$arr['folder'],
					'backimg'=>$config['custom_backimg']?$config['custom_backimg']:$arr['backimg'],
					'dock'=>$config['custom_dock']?$config['custom_dock']:$arr['dock'],
					'window'=>$config['custom_window']?$config['custom_window']:$arr['window'],
					'browser'=>$config['custom_browser']?$config['custom_browser']:$arr['browser'],
					
					'topbar'=>$config['custom_topbar']?$config['custom_topbar']:$arr['topbar'],
					'filemanage'=>$config['custom_filemanage']?$config['custom_filemanage']:$arr['filemanage'],
		);
		$config['allownewfolder']=(!isset($config['allownewfolder']) || $config['allownewfolder']<0)?$usergroup['allownewfolder']:$config['allownewfolder'];
		$config['allownewlink']=(!isset($config['allownewlink']) || $config['allownewlink']<0)?$usergroup['allownewlink']:$config['allownewlink'];
		$config['allowupload']=(!isset($config['allowupload']) || $config['allowupload']<0)?$usergroup['allowupload']:$config['allowupload'];
		$config['attachextensions']=(!isset($config['attachextensions']) || $config['attachextensions']<0)?$usergroup['attachextensions']:$config['attachextensions'];
		$config['maxattachsize']=(!isset($config['maxattachsize']) || $config['maxattachsize']<0)?$usergroup['maxattachsize']:$config['maxattachsize'];
		$config['maxspacesize']=$usergroup['maxspacesize']==0?0:($usergroup['maxspacesize']*1024*1024+$config['addsize']+$config['buysize']);
		
		$space=array_merge($space,$config);
	}else{
		$arr=DB::fetch_first("select * from ".DB::table('dzz_thame')." where `default`='1'");
		$space['thame']=array(
					'folder'=>$arr['folder'],
					'backimg'=>$arr['backimg'],
					'dock'=>$arr['dock'],
					'window'=>$arr['window'],
					'browser'=>$arr['browser'],
					'topbar'=>$arr['topbar'],
					'filemanage'=>$arr['filemanage'],
				);
		$space=array_merge($space,$usergroup);
	}
	if($_G['adminid']==1){
		$space['allownewfolder']=1;
		$space['allownewlink']=1;
		$space['allowupload']=1;
		
	}
	$space['fusesize']=formatsize($space['usesize']);
	if($space['maxattachsize']==0){
		$space['fmaxattachsize']=dzzlang('space/template','no_limit');
	}else{
		$space['fmaxattachsize']=formatsize($space['maxattachsize']);
	}
	if($space['maxspacesize']==0){
		$space['fmaxspacesize']=dzzlang('space/template','no_limit');
	}else{
		$space['fmaxspacesize']=formatsize($space['maxspacesize']);
	}
	$space['attachextensions']=str_replace(' ','',$space['attachextensions']);
	
	return $space;
	
}
function dzzchecktplrefresh($maintpl, $subtpl, $timecompare, $templateid, $cachefile, $tpldir, $file) {
	static $tplrefresh, $timestamp, $targettplname;
	if($tplrefresh === null) {
		$tplrefresh = getglobal('config/output/tplrefresh');
		$timestamp = getglobal('timestamp');
	}

	if(empty($timecompare) || $tplrefresh == 1 || ($tplrefresh > 1 && !($timestamp % $tplrefresh))) {
		if(empty($timecompare) || @filemtime(DISCUZ_ROOT.$subtpl) > $timecompare) {
			require_once DISCUZ_ROOT.'/dzz/class/class_template.php';
			$template = new template();
			$template->parse_template($maintpl, $templateid, $tpldir, $file, $cachefile);
			if($targettplname === null) {
				$targettplname = getglobal('style/tplfile');
				if(!empty($targettplname)) {
					$targettplname = strtr($targettplname, ':', '_');
					update_template_block($targettplname, $template->blocks);
				}
				$targettplname = true;
			}
			return TRUE;
		}
	}
	return FALSE;
}

function dzztemplate($file, $templateid = 'dzz', $tpldir = '', $gettplfile = 0, $primaltpl='') {
	global $_G;

	static $_init_style = false;
	if($_init_style === false) {
		$discuz = & discuz_core::instance();
		$discuz->_init_style();
		$_init_style = true;
	}
	$oldfile = $file;
	$file .= !empty($_G['inajax']) && ($file == 'header' || $file == 'footer') ? '_ajax' : '';
	//是插件的时候
	$vars=explode(':',$file);
	if(count($vars)==2) {
		$vars=explode(':',$file);
		$tpldir='./dzz/plugin';
		$tplfile = $tpldir .'/'.$vars[0].'/template/'.$vars[1].'.htm';
		$file=$vars[0].'/'.$vars[1];
	}else{
		list($path,$filename)=explode('/',$file);
		if($filename){
			if($path=='admin'){
				$tpldir = './dzz/admin/default';
				$tplfile = $tpldir .'/'.$filename.'.htm';
				//$file=$filename;
			}else{
				$tpldir = './dzz/'.$path.'/template';
				$tplfile = $tpldir .'/'.$filename.'.htm';
			}
		}
	}
	if(!$tpldir) $tpldir='./dzz/template';
	//$filebak = $file;

	/*if(defined('IN_MOBILE') && !defined('TPL_DEFAULT') && strpos($file, 'mobile/') === false || $_G['forcemobilemessage']) {
		$file = 'mobile/'.$oldfile;
	}
*/
	
	$tplfile = $tplfile ? $tplfile : ($tpldir.'/'.$file.'.htm');
	//$file == 'common/header' && defined('CURMODULE') && CURMODULE && $file = 'common/header_'.$_G['basescript'].'_'.CURMODULE;


	$cachefile = './data/template/'.(defined('STYLEID') ? STYLEID.'_' : '_').$templateid.'_'.str_replace('/', '_', $file).'.tpl.php';

/*	if($templateid != 1 && !file_exists(DISCUZ_ROOT.$tplfile)) {
		$tplfile = './template/default/'.$filebak.'.htm';
	}*/

	if($gettplfile) {
		return $tplfile;
	}
	dzzchecktplrefresh($tplfile, $tplfile, @filemtime(DISCUZ_ROOT.$cachefile), $templateid, $cachefile, $tpldir, $file);
	return DISCUZ_ROOT.$cachefile;
}
function microtime_float()
{
    list($usec, $sec) = explode(' ', microtime());
	return (floatval($usec) + floatval($sec));
}


function curl_file_get_contents($durl){
	global $_SERVER;
	
  	$ch = curl_init();
	 curl_setopt($ch, CURLOPT_URL, $durl);
	 curl_setopt($ch, CURLOPT_TIMEOUT, 15);
	// curl_setopt($ch, CURLOPT_TIMEOUT_MS, 500);
	 curl_setopt($ch, CURLOPT_ENCODING ,'');
	 curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
	 curl_setopt($ch, CURLOPT_REFERER,'');
	 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
	 curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
	 $r = curl_exec($ch);
	 curl_close($ch);
	 return $r;
	 }
function ico_png($source,$target){
		
		require_once dzz_libfile('class/ico');
		$oico=new Ico($source);
		$max=-1;
		$data_length=0;
		for($i=0; $i<$oico->TotalIcons(); $i++){
			$data=$oico->GetIconInfo($i);
			if($data['data_length']>$data_length){
				$data_length=$data['data_length'];
				$max=$i;
			}
		} 
		if($max>=0 && imagepng($oico->GetIcon($max),$target)){
			return true;
		}else return false;
}

function check_remote_file_exists($url)
{
	set_time_limit(120);
   $u = parse_url($url);
  
   if(!$u || !isset($u['host'])) return false;
  
    $h = get_headers($url);
    if(!$h || !isset($h[0])) return false;
    $status = $h[0];
    return preg_match("/.*200\s{1}OK/i", $status) ? true : false;
  
}

function dzz_file_get_contents($source){
	if(function_exists('curl_init')!==false){
		if($data=curl_file_get_contents($source)){
			return $data;
		}else{
			return file_get_contents($source);
		}
	}else{
		return file_get_contents($source);
	}
	//$data=dfsockopen($source,  0, '',  '',  FALSE, '',  60,  TRUE);
}
function imagetolocal($source, $dir='appimg',$target='') {
	global $_G;
	if(empty($source)) return false;
	if(!$data =dzz_file_get_contents($source)) {
		return false;
	}
	if($target=='dzz/images/default/icodefault.png' || $target=='dzz/images/default/widgetdefault.png' || preg_match("/^(http|ftp|https|mms)\:\/\/(.+?)/i", $target)){
		$target='';
	}
	if(!$target) {
		$imageext=array('jpg','jpeg','png','gif');
		$ext=strtolower(substr(strrchr($source, '.'), 1, 10));
		if(!in_array($ext,$imageext)) $ext='jpg';
		$subdir = $subdir1 = $subdir2 = '';
		$subdir1 = date('Ym');
		$subdir2 = date('d');
		$subdir = $subdir1.'/'.$subdir2.'/';
		$target1=$_G['setting']['attachdir'].$dir.'/'.$subdir.''.date('His').''.strtolower(random(16)).'.'.$ext;
		$target=str_replace($_G['setting']['attachdir'],'',$target1);
	}else{
		$target1=$_G['setting']['attachdir'].$target;
	}
	$targetpath = dirname($target1);
	dmkdir($targetpath);
	if(file_put_contents($target1, $data)){
		if(@filesize($target1)<200) {
			@unlink($target1);
			return false;
		}
		return $target;
	}else return false;
}
function uploadtolocal($upload,$dir='appimg',$target=''){
	global $_G;
	if($target=='dzz/images/default/icodefault.png' || $target=='dzz/images/default/widgetdefault.png' || preg_match("/^(http|ftp|https|mms)\:\/\/(.+?)/i", $target)){
		$target='';
	}
	$source=$upload['tmp_name'];
	$imageext=array('jpg','jpeg','png','gif');
	$ext=strtolower(substr(strrchr($upload['name'], '.'), 1, 10));
	if(!in_array($ext,$imageext)) cpmsg("'jpg', 'jpeg', 'gif', 'png', 'bmp','ico'",'','error');
	if($target) {
		$target1=$_G['setting']['attachdir'].$target;
	}else{
		$subdir = $subdir1 = $subdir2 = '';
		$subdir1 = date('Ym');
		$subdir2 = date('d');
		$subdir = $subdir1.'/'.$subdir2.'/';
		$target1=$_G['setting']['attachdir'].$dir.'/'.$subdir.''.date('His').''.strtolower(random(16)).'.'.$ext;
		$target=str_replace($_G['setting']['attachdir'],'',$target1);
	}
	
	if(save_to_local($source, $target1)){
		return $target;
	}else{
		return false;
	}
}
function image_to_icon($source,$target,$domain){
	global $_G;
		if(!$data = dzz_file_get_contents($source)){
			return false;
		}
		if(!$target){
			$imageext=array('jpg','jpeg','png','gif');
			$ext=strtolower(substr(strrchr($source, '.'), 1, 10));
			if(!in_array($ext,$imageext)) $ext='jpg';
			$subdir = $subdir1 = $subdir2 = '';
			$subdir1 = date('Ym');
			$subdir2 = date('d');
			$subdir = $subdir1.'/'.$subdir2.'/';
			$target='icon/'.$subdir.''.$domain.'_'.strtolower(random(8)).'.'.$ext;
			$target_attach=$_G['setting']['attachdir'].$target;
		}else{
			$target_attach=$_G['setting']['attachdir'].$target;
		}
		$targetpath = dirname($target_attach);
		dmkdir($targetpath);
		if(file_put_contents($target_attach, $data)){
			return $target;
		}else{
			return false;
		}
}

function upload_to_icon($upload,$target,$domain){
	global $_G;
		$source=$upload['tmp_name'];
		if(!$target){
			$imageext=array('jpg','jpeg','png','gif');
			$ext=strtolower(substr(strrchr($upload['name'], '.'), 1, 10));
			if(!in_array($ext,$imageext)) $ext='jpg';
			$subdir = $subdir1 = $subdir2 = '';
			$subdir1 = date('Ym');
			$subdir2 = date('d');
			$subdir = $subdir1.'/'.$subdir2.'/';
			$target='icon/'.$subdir.''.$domain.'_'.strtolower(random(8)).'.'.$ext;
			$target_attach=$_G['setting']['attachdir'].$target;
		}else{
			$target_attach=$_G['setting']['attachdir'].$target;
		}
		if(save_to_local($source, $target_attach)){
			return $target;
		}else{
			return false;
		}
}
function delete_pic($picids){
	if(!is_array($picids)) $picids=array($picids);
	foreach($picids as $picid){
		$arr=array();
		$arr=DB::fetch_first("select * from ".DB::table('dzz_pic')." where picid='{$picid}'");
		$arr['pic']=pic_get($arr['filepath'], '', $arr['thumb'], $arr['remote'],0,1);
		if($arr['pic']) @unlink(DISCUZ_ROOT.'./'.$arr['pic']);
		if($arr['thumb']) @unlink(DISCUZ_ROOT.'./'.$arr['pic'].'.thumb.jpg');
	}
	DB::delete('dzz_pic', "picid IN (".dimplode($picids).")");
}
function app_image_add($link,$appid,$source=''){
	global $_G,$dzzdomain;	
		//$type=2;//全部图片剪裁；
		$link=str_replace(' ','%20',trim($link));
		if(!preg_match("/^(http|ftp|https|mms)/i", $link)) return false;
		if($value=DB::fetch(DB::query("SELECT * FROM ".DB::table('dzz_pic')." where id='{$appid}' and (source='{$link}' OR source='{$source}') LIMIT 1"))){
			$target=$value['filepath'];
			if((@filesize($_G['setting']['attachdir'].'./'.$target)<200) ||!is_file($_G['setting']['attachdir'].'./'.$target)){
				if(is_file($_G['setting']['attachdir'].'./'.$target)) @unlink($_G['setting']['attachdir'].'./'.$target);
				DB::query("DELETE FROM ".DB::table('dzz_pic')." WHERE picid = '{$value[picid]}'", 'UNBUFFERED');
				return app_image_add($link,$appid,$type);
			}
			DB::update('dzz_pic',array('source'=>addslashes($source)),"picid = '{$value[picid]}'");
			return true;
		}
		$thumb=0;
		$target=imagetolocal($link);
		if(!$target){ return false;}
		$picarr = array(
				'id' => $appid,
				'uid' => $_G['uid']?$_G['uid']:1,
				'username' => $_G['username']?$_G['username']:'mawangye',
				'dateline' => $_G['timestamp'],
				'filename' => strtolower(substr(strrchr($link, '/'), 1, 50)),
				'postip' => $_G['clientip'],
				'title' => '',
				'type' => $ext,
				'size' => 0,
				'filepath' =>$target,
				'thumb' => 0,
				'source'=>$source,
				'checked'=>1,
				'remote' => 0
			);
		
			DB::insert('dzz_pic', daddslashes($picarr));
			return true;
}
function dzz_pic_save($FILE,$dir='appimg') {
	global $_G;
	$allowpictype = array('jpg','jpeg','gif','png');

	require_once dzz_libfile('class/upload');
	$upload = new discuz_upload();
	$upload->init($FILE, $dir);

	if($upload->error()) {
		return lang('spacecp', 'lack_of_access_to_upload_file_size');
	}

	if(!$upload->attach['isimage']) {
		return lang('spacecp', 'only_allows_upload_file_types');
	}
	$upload->save();
	if($upload->error()) {
		return lang('spacecp', 'mobile_picture_temporary_failure');
	}
	$setarr = array(
		'uid' => $_G['uid'],
		'username' => $_G['username'],
		'dateline' => $_G['timestamp'],
		'filename' => addslashes($upload->attach['name']),
		'postip' => $_G['clientip'],
		'title' => $title,
		'type' => addslashes($upload->attach['ext']),
		'size' => $upload->attach['size'],
		'filepath' => 'appimg/'.$upload->attach['attachment'],
		'thumb' => 0,
		'remote' => 0,
		
	);
	$setarr['picid'] = DB::insert('dzz_pic', $setarr, 1);
	return $setarr;
}
function dzzshowmessage($message, $url_forward = '', $values = array(), $extraparam = array(), $custom = 0) {
	global $_G, $show_message;
	$_G['messageparam'] = func_get_args();
	if(!empty($_GET['mobiledata'])) {
		require_once libfile('class/mobiledata');
		$mobiledata = new mobiledata();
		if($mobiledata->validator()) {
			$mobiledata->outputvariables();
		}
	}
	if(empty($_G['inhookscript']) && defined('CURMODULE')) {
		hookscript(CURMODULE, $_G['basescript'], 'messagefuncs', array('param' => $_G['messageparam']));
	}
	$_G['inshowmessage'] = true;

	$param = array(
		'header'	=> false,
		'timeout'	=> null,
		'refreshtime'	=> null,
		'closetime'	=> null,
		'locationtime'	=> null,
		'alert'		=> null,
		'return'	=> false,
		'redirectmsg'	=> 0,
		'msgtype'	=> 1,
		'showmsg'	=> true,
		'showdialog'	=> false,
		'login'		=> false,
		'handle'	=> false,
		'extrajs'	=> '',
		'striptags'	=> true,
	);

	$navtitle = lang('core', 'title_board_message');

	if($custom) {
		$alerttype = 'alert_info';
		$show_message = $message;
		include dzztemplate('template/showmessage');
		dexit();
	}

	define('CACHE_FORBIDDEN', TRUE);
	$_G['setting']['msgforward'] = @unserialize($_G['setting']['msgforward']);
	$handlekey = $leftmsg = '';

	if(defined('IN_MOBILE')) {
		$_G['inajax'] = 0;
		if(!$url_forward && dreferer()) {
			$url_forward = $referer = dreferer();
		}
		if(!empty($url_forward) && strpos($url_forward, 'mobile') === false) {
			$url_forward_arr = explode("#", $url_forward);
			if(strpos($url_forward_arr[0], '?') !== false) {
				$url_forward_arr[0] = $url_forward_arr[0].'&mobile=yes';
			} else {
				$url_forward_arr[0] = $url_forward_arr[0].'?mobile=yes';
			}
			$url_forward = implode("#", $url_forward_arr);
		}
	}


	if(empty($_G['inajax']) && (!empty($_GET['quickforward']) || $_G['setting']['msgforward']['quick'] && $_G['setting']['msgforward']['messages'] && @in_array($message, $_G['setting']['msgforward']['messages']))) {
		$param['header'] = true;
	}
	$_GET['handlekey'] = !empty($_GET['handlekey']) && preg_match('/^\w+$/', $_GET['handlekey']) ? $_GET['handlekey'] : '';
	if(!empty($_G['inajax'])) {
		$handlekey = $_GET['handlekey'] = !empty($_GET['handlekey']) ? htmlspecialchars($_GET['handlekey']) : '';
		$param['handle'] = true;
	}
	if(!empty($_G['inajax'])) {
		$param['msgtype'] = empty($_GET['ajaxmenu']) && (empty($_POST) || !empty($_GET['nopost'])) ? 2 : 3;
	}
	if($url_forward) {
		$param['timeout'] = true;
		if($param['handle'] && !empty($_G['inajax'])) {
			$param['showmsg'] = false;
		}
	}

	foreach($extraparam as $k => $v) {
		$param[$k] = $v;
	}
	if(array_key_exists('set', $extraparam)) {
		$setdata = array('1' => array('msgtype' => 3));
		if($setdata[$extraparam['set']]) {
			foreach($setdata[$extraparam['set']] as $k => $v) {
				$param[$k] = $v;
			}
		}
	}

	$timedefault = intval($param['refreshtime'] === null ? $_G['setting']['msgforward']['refreshtime'] : $param['refreshtime']);
	if($param['timeout'] !== null) {
		$refreshsecond = !empty($timedefault) ? $timedefault : 3;
		$refreshtime = $refreshsecond * 1000;
	} else {
		$refreshtime = $refreshsecond = 0;
	}

	if($param['login'] && $_G['uid'] || $url_forward) {
		$param['login'] = false;
	}

	$param['header'] = $url_forward && $param['header'] ? true : false;

	if($param['header']) {
		header("HTTP/1.1 301 Moved Permanently");
		dheader("location: ".str_replace('&amp;', '&', $url_forward));
	}
	if($param['location'] && !empty($_G['inajax'])) {
		include template('common/header_ajax');
		echo '<script type="text/javascript" reload="1">window.location.href=\''.str_replace("'", "\'", $url_forward).'\';</script>';
		include template('common/footer_ajax');
		dexit();
	}

	$_G['hookscriptmessage'] = $message;
	$_G['hookscriptvalues'] = $values;
	$vars = explode(':', $message);
	if(count($vars) == 2) {
		$show_message = dzzlang($vars[0].':message', $vars[1], $values);
	} else {
		$show_message = dzzlang('message', $message, $values);
	}
	if($param['msgtype'] == 2 && $param['login']) {
		dheader('location: member.php?mod=logging&action=login&handlekey='.$handlekey.'&infloat=yes&inajax=yes&guestmessage=yes');
	}

	$show_jsmessage = str_replace("'", "\\'", $param['striptags'] ? strip_tags($show_message) : $show_message);

	if((!$param['showmsg'] || $param['showid']) && !defined('IN_MOBILE') ) {
		$show_message = '';
	}

	$allowreturn = !$param['timeout'] && !$url_forward && !$param['login'] || $param['return'] ? true : false;
	if($param['alert'] === null) {
		$alerttype = $url_forward ? (preg_match('/\_(succeed|success)$/', $message) ? 'alert_right' : 'alert_info') : ($allowreturn ? 'alert_error' : 'alert_info');
	} else {
		$alerttype = 'alert_'.$param['alert'];
	}

	$extra = '';
	if($param['showid']) {
		$extra .= 'if($(\''.$param['showid'].'\')) {$(\''.$param['showid'].'\').innerHTML = \''.$show_jsmessage.'\';}';
	}
	if($param['handle']) {
		$valuesjs = $comma = $subjs = '';
		foreach($values as $k => $v) {
			$v = daddslashes($v);
			if(is_array($v)) {
				$subcomma = '';
				foreach ($v as $subk => $subv) {
					$subjs .= $subcomma.'\''.$subk.'\':\''.$subv.'\'';
					$subcomma = ',';
				}
				$valuesjs .= $comma.'\''.$k.'\':{'.$subjs.'}';
			} else {
				$valuesjs .= $comma.'\''.$k.'\':\''.$v.'\'';
			}
			$comma = ',';
		}
		$valuesjs = '{'.$valuesjs.'}';
		if($url_forward) {
			$extra .= 'if(typeof succeedhandle_'.$handlekey.'==\'function\') {succeedhandle_'.$handlekey.'(\''.$url_forward.'\', \''.$show_jsmessage.'\', '.$valuesjs.');}';
		} else {
			$extra .= 'if(typeof errorhandle_'.$handlekey.'==\'function\') {errorhandle_'.$handlekey.'(\''.$show_jsmessage.'\', '.$valuesjs.');}';
		}
	}
	if($param['closetime'] !== null) {
		$param['closetime'] = $param['closetime'] === true ? $timedefault : $param['closetime'];
	}
	if($param['locationtime'] !== null) {
		$param['locationtime'] = $param['locationtime'] === true ? $timedefault : $param['locationtime'];
	}
	if($handlekey) {
		if($param['showdialog']) {
			$extra .= 'hideWindow(\''.$handlekey.'\');showDialog(\''.$show_jsmessage.'\', \'notice\', null, '.($param['locationtime'] !== null ? 'function () { window.location.href =\''.$url_forward.'\'; }' : 'null').', 0, null, null, null, null, '.($param['closetime'] ? $param['closetime'] : 'null').', '.($param['locationtime'] ? $param['locationtime'] : 'null').');';
			$param['closetime'] = null;
			$st = '';
		}
		if($param['closetime'] !== null) {
			$extra .= 'setTimeout("hideWindow(\''.$handlekey.'\')", '.($param['closetime'] * 1000).');';
		}
	} else {
		$st = $param['locationtime'] !== null ?'setTimeout("window.location.href =\''.$url_forward.'\';", '.($param['locationtime'] * 1000).');' : '';
	}
	if(!$extra && $param['timeout'] && !defined('IN_MOBILE')) {
		$extra .= 'setTimeout("window.location.href =\''.$url_forward.'\';", '.$refreshtime.');';
	}
	$show_message .= $extra ? '<script type="text/javascript" reload="1">'.$extra.$st.'</script>' : '';
	$show_message .= $param['extrajs'] ? $param['extrajs'] : '';
	include dzztemplate('showmessage');

	dexit();
}

//漫游入库应用市场

function manyou_app_to_market($app){
global $_G,$lang,$dzz_manyouconfig;
 //处理一级分类
	if($dzz_manyouconfig['manyou_classid'] && DB::result_first("select COUNT(*) from ".DB::table('dzz_appclass')." where classid='{$dzz_manyouconfig[manyou_classid]}' and fupid=0" )){
		$app['classid']=$dzz_manyouconfig['manyou_classid'];
	}elseif($classid=DB::result_first("select classid from ".DB::table('dzz_appclass')." where classname='".dzzlang('message','manyou_classame')."' and fupid=0" )){
		$app['classid']=$classid;
		$dzz_manyouconfig['manyou_classid']=$classid;
		
	}else{ //创建漫游应用分类
		if($classid=DB::insert('dzz_appclass',array('classname'=>addslashes(dzzlang('message','manyou_classame')),'fupid'=>0,'disp'=>999,'dateline'=>$_G['timestamp']),1)){
			$app['classid']=$classid;
			$dzz_manyouconfig['manyou_classid']=$classid;
		}else{
			return false;
		}
	}
	//处理子分类
	if($app['classname'] && $app['classid']){
		$subclass=$app['classname'];
		unset($app['classname']);
		//获取本站的子分类
				$mysubclass=$mysubclassid=array();
				$query=DB::query("select classid,classname from ".DB::table('dzz_appclass')." where fupid='{$app[classid]}'");
				while($value=DB::fetch($query)){
					$mysubclass[$value['classid']]=$value['classname'];
					$mysubclassid[$value['classname']]=$value['classid'];
				}
				
				if(in_array($subclass,$mysubclass)) $subclassids=$mysubclassid[$subclass];
				else{
					if($subclassid=DB::insert('dzz_appclass',array('classname'=>addslashes($subclass),'fupid'=>$app['classid'],'dateline'=>$_G['timestamp']),1)){
						$subclassids=$subclassid;
					}
				}
				$app['classids']=$subclassids;
	}
	
	$app['ismarket']=1;
	$app['type']=2;
	$app['open']=3;
	if($app['appico']){
		$source=$app['appico'];
		
		$target=DB::result_first("select appico from ".DB::table('dzz_apps')." where oid='{$app[oid]}' and type=2");
		if($appico=imagetolocal($source,'appico',$target)){
			$app['appico']=$appico;
		}
	}
	if($myappid=DB::result_first("select appid from ".DB::table('dzz_apps')." where oid='{$app[oid]}' and type=2")){
		DB::update('dzz_apps',daddslashes($app),"appid='{$myappid}'");
	}else{
		$app['dateline']=$_G['timestamp'];
		$myappid=DB::insert('dzz_apps',daddslashes($app),1);
	}
	if(!$myappid) {
		return false;
	}
	//维护关系表
	if($subclassids){
		DB::delete('dzz_relative',"appid ='{$mappid}'");
		DB::insert('dzz_relative',array('appid'=>$myappid,'classid'=>intval($subclassids)));
	}
	return true;
}
//下载应用到本地

function download_app($app,$pic,$classarr,$myappid){
	global $dzzdomain,$_G,$lang;
	//转码
		$app['appname']=diconv($app['appname'],'UTF-8');
		$app['appdesc']=diconv($app['appdesc'],'UTF-8');
		$app['vendor']=diconv($app['vendor'],'UTF-8');
		$app['appurl']=(diconv($app['appurl'],'UTF-8'));
		$app['subclass']=diconv($app['subclass'],'UTF-8');
		$app['classname']=diconv($app['classname'],'UTF-8');
	
	//处理一级分类
	if($classarr[$app['classid']]){
		$app['classid']=$classarr[$app['classid']];
	}else{
		if($app['classname']){ //一级分类不存在，则创建此一级分类
			$classname=addslashes($app['classname']);
			if($app['classid']=DB::result_first("select classid from ".DB::table('dzz_appclass')." where fupid=0 and classname='{$classname}'")){
				
			}else{
				$app['classid']=DB::insert('dzz_appclass',array('classname'=>$classname,'fupid'=>0,'dateline'=>$_G['timestamp']),1);
			}
		}else{
			$app['classid']=0;
		}
	}
	
	if(!$app['classid']){
		return $lang['batch_appclass_error_skip'];	
	}
	//处理二级分类
	$subclassids=array();
	if($app['subclass']){
		$subclass=explode(',',$app['subclass']);
		//获取本站的子分类
		$mysubclass=$mysubclassid=array();
		$query=DB::query("select classid,classname from ".DB::table('dzz_appclass')." where fupid='{$app[classid]}'");
		while($value=DB::fetch($query)){
			$mysubclass[$value['classid']]=$value['classname'];
			$mysubclassid[$value['classname']]=$value['classid'];
		}
		foreach($subclass as $value){
			if(in_array($value,$mysubclass)) $subclassids[]=$mysubclassid[$value];
			else{
				if($classid=DB::insert('dzz_appclass',array('classname'=>addslashes($value),'fupid'=>$app['classid'],'dateline'=>$_G['timestamp']),1)){
					$subclassids[]=$classid;
				}
			}
		}
		$app['classids']=implode(',',$subclassids);
	}
	unset($app['subclass']);
	if($app['appico']){
		$source=$dzzdomain.$app['appico'];
		if($myappid) $target=DB::result_first("select appico from ".DB::table('dzz_apps')." where appid='{$myappid}'");
		else $target='';
		if($appico=imagetolocal($source,'appico',$target)){
			$app['appico']=$appico;
		}else{
			return '<p style="font-size:12px;color:green;margin-left:20px;">"'.$app[classname].$lang['batch_setup_appico_failure'].'</p>';
		}
	}

	unset($app['appid']);
	unset($app['classname']);
	
	$app['dateline']=$_G['timestamp'];
	$app['ismarket']=1;
	if($myappid){
		DB::update('dzz_apps',daddslashes($app),"appid='{$myappid}'");
	}else{
		$myappid=DB::insert('dzz_apps',daddslashes($app),1);
	}
	if(!$myappid) {
		return $lang['insert_to_db'];
	}
	//维护关系表
	if($subclassids){
		 DB::delete('dzz_relative',"appid ='{$mappid}'");
		foreach($subclassids as $cid){
			DB::insert('dzz_relative',array('appid'=>$myappid,'classid'=>intval($cid)));
		}
	}
	
	if($pic){
		foreach($pic as $key=> $value){
			$link=$dzzdomain.$value;
			if(!app_image_add($link,$myappid,$value)){
				//echo '<p style="font-size:12px;margin-left:20px;">'.$lang['picture'].($key+1).$lang['setup_failure'].'...</p>';
				flush();
				ob_flush();
			}
		}
	}
	return true;		
}
//更新评分
function updatescore($id,$idtype) {
	$stars=array('star1'=>0,'star2'=>0,'star3'=>0,'star4'=>0,'star5'=>0,'allstar'=>0);
 	$query=DB::query("SELECT * FROM ".DB::table('dzz_score')." where id='{$id}' and idtype='{$idtype}'");
	while($value=DB::fetch($query)){
		if($value['star']==1) {$stars['star1']+=1;$stars['allstar']+=1;}
		if($value['star']==2) {$stars['star2']+=1;$stars['allstar']+=1;}
		if($value['star']==3) {$stars['star3']+=1;$stars['allstar']+=1;}
		if($value['star']==4) {$stars['star4']+=1;$stars['allstar']+=1;}
		if($value['star']==5) {$stars['star5']+=1;$stars['allstar']+=1;}
		
	}
	$score=0;
	for($i=1;$i<6;$i++){
		$score+=$stars['star'.$i]/$stars['allstar']*$i*2;
	}
	$score=round($score*100)/100;
	switch($idtype){
		case 'appid':	
			//DB::update('dzz_apps',array('star'=>$score,'starnum'=>$stars['allstar']),"appid='{$id}'");
			DB::query("update ".DB::table('dzz_apps')." set hot=hot+2 ,star='{$score}', starnum='{$stars[allstar]}' where appid='{$id}'");
			break;
		case 'lid':	
			DB::query("update ".DB::table('dzz_link')." set star='{$score}', starnum='{$stars[allstar]}' where lid='{$id}'");
			break;
		case 'vid':	
			DB::query("update ".DB::table('dzz_video')." set star='{$score}', starnum='{$stars[allstar]}' where vid='{$id}'");
			break;
		case 'mid':	
			DB::query("update ".DB::table('dzz_music')." set star='{$score}', starnum='{$stars[allstar]}' where mid='{$id}'");
			break;
		case 'picid':	
			DB::query("update ".DB::table('dzz_image')." set star='{$score}', starnum='{$stars[allstar]}' where picid='{$id}'");
			break;
		case 'qid':	
			DB::query("update ".DB::table('dzz_attach')." set star='{$score}', starnum='{$stars[allstar]}' where qid='{$id}'");
			break;
		
	
	}
	
	
}
function getapp($id){
	global $_G;
	$mem_name="appinfo_".$id;
	$mem_time=60*60*6;
	if(memory('check') && $data=memory('get',$mem_name)){
			$movie=$data;
	}else{
			$movie=array();
			$movie=DB::fetch_first("select a.*,c.classname from ".DB::table('dzz_apps')." a 
										LEFT JOIN ".DB::table('dzz_appclass')." c  ON c.classid=a.classid 
										where a.appid='{$id}'");
			if(!$movie['appico']) $movie['appico']='dzz/images/default/icodefault.png';
			if($movie['appico']!='dzz/images/default/icodefault.png' && !preg_match("/^(http|ftp|https|mms)\:\/\/(.+?)/i", $movie['appico'])){
				$movie['appico']=$_G['setting']['attachurl'].$movie['appico'];
			}
			$movie['dateline']=dgmdate($movie['dateline'], 'Y-m-d');
			$movie['scorestyle']=$movie['star']*10;
			
			
		if(memory('check')){
				memory('set',$mem_name,$movie,$mem_time);
			}
	}	
	return $movie;
}
/*function x_getattach($pid, $posttime = 0) {
	global $_G;

	require_once libfile('function/attachment');
	$attachs = $imgattachs = array();
	$sqladd1 = $posttime > 0 ? "AND dateline>'$posttime'" : '';
	$sqladd2 = $pid > 0 ? "OR pid='$pid'" : '';
	$query = DB::query("SELECT * FROM ".DB::table('dzz_attachment')." WHERE uid='$_G[uid]' $sqladd1 $sqladd2 ORDER BY dateline");
	while($attach = DB::fetch($query)) {
		$attach['filenametitle'] = $attach['filename'];
		$attach['ext'] = fileext($attach['filename']);
		$attach['filename'] = cutstr($attach['filename'], $_G['setting']['allowattachurl'] ? 25 : 30);
		$attach['attachsize'] =$attach['filesize'];
		
		$attach['filetype'] = attachtype($attach['ext']."\t".$attach['filetype']);
		
			$attach['url'] = ($attach['remote'] ? $_G['setting']['ftp']['attachurl'] : $_G['setting']['attachurl']);
			//$attach['width'] = $attach['width'] > 110 ? 110 : $attach['width'];
			if($attach['pid']) {
				$imgattachs['used'][] = $attach;
			} else {
				$imgattachs['unused'][] = $attach;
			}
		
	}
	return $imgattachs;
}*/
function is_upload_files($source) {
		return $source && ($source != 'none') && (is_uploaded_file($source) || is_uploaded_file(str_replace('\\\\', '\\', $source)));
	}
function save_to_local($source, $target) {
		$targetpath = dirname($target);
		dmkdir($targetpath);
		if(!is_upload_files($source)) {
			$succeed = false;
		}elseif(@copy($source, $target)) {
			$succeed = true;
		}elseif(function_exists('move_uploaded_file') && @move_uploaded_file($source, $target)) {
			$succeed = true;
		}elseif (@is_readable($source) && (@$fp_s = fopen($source, 'rb')) && (@$fp_t = fopen($target, 'wb'))) {
			while (!feof($fp_s)) {
				$s = @fread($fp_s, 1024 * 512);
				@fwrite($fp_t, $s);
			}
			fclose($fp_s); fclose($fp_t);
			$succeed = true;
		}

		if($succeed)  {
			@chmod($target, 0644); @unlink($source);
		} 
		return $succeed;
	}
//获取系统默认目录图标
function get_folder_sysicon(){
	global $_G;
	$icon=DB::result_first("select icon from ".DB::table('dzz_sysicon')." where  `default`=1 LIMIT 1");
	if(!$icon){
		$icon=DB::result_first("select icon from ".DB::table('dzz_sysicon')." where 1 ORDER BY disp LIMIT 1");
	}
	if($icon){
		return SYSICON_FOLDER.$icon;
	}else{
		return 'dzz/images/default/folder.png';
	}
}
//获取用户新文件夹序号
function get_newfolder_index($uid){
	global $_G,$lang;
	$index=array(0);
	$query=DB::query("select fname from ".DB::table('dzz_folder')." where  `uid`='{$uid}'");
	while($value=DB::fetch($query)){
		if(strpos($value['fname'],$lang['new_folder'])===0)	$index[]=intval(str_replace($lang['new_folder'],'',$value['fname']));
	}
	$index=array_unique($index);
	sort($index);
	for($i=0;$i<count($index);$i++){
		if($index[$i]>$i) return $i;
	}
	return $i;
	
}
//获取用户新文档序号
function get_newdoc_index($uid,$ext){
	global $_G,$lang;
	$index=array(0);
	$query=DB::query("select name from ".DB::table('dzz_icos')." where  `uid`='{$uid}' and ext='{$ext}'");
	while($value=DB::fetch($query)){
		if(strpos($value['name'],dzzlang('message','new_'.$ext))===0)	$index[]=intval(str_replace(dzzlang('message','new_'.$ext),'',$value['name']));
	}
	$index=array_unique($index);
	sort($index);
	for($i=0;$i<count($index);$i++){
		if($index[$i]>$i) return $i;
	}
	return $i;
	
}



function dzz_create_folder($uid=0,$pfid=0,$desktop=0,$fname='',$ids='',$ficon='',$username=0){
	global $_G,$lang,$space;
		if(empty($fname)) $fname=$lang['new_folder'].get_newfolder_index($uid);
		if(empty($ficon)) $ficon=get_folder_sysicon();
		//if(!$uid) $uid=$_G['uid'];
		if(!$username) $username=$space['username'];
		$setarr=array('fname'=>$fname,
					  'uid'=>$uid,
					  'ficon'=>$ficon,
					  'username'=>$username,
					  'ids'=>implode(',',$ids),
					  'pfid'=>$pfid,
					  'iconview'=>DB::result_first("select id from ".DB::table('dzz_iconview')." order by disp limit 1"),
					  'desktop'=>$desktop,
					  'dateline'=>$_G['timestamp'],
					  'friend'=>0
					 );
		if($setarr['fid']=DB::insert('dzz_folder',daddslashes($setarr),1)){
			$setarr1=array(
							'uid'=>$uid,
							'username'=>$username,
							'oid'=>$setarr['fid'],
							'name'=>$setarr['fname'],
							'url'=>'',
							'img'=>$setarr['ficon'],
							'type'=>'folder',
							'friend'=>0,
							'dateline'=>$_G['timestamp'],
							'wwidth'=>0,
							'wheight'=>0,
							'open'=>0
							);
			if($setarr1['icoid']=DB::insert('dzz_icos',daddslashes($setarr1),1)){
				$setarr1['fsize']=formatsize(0);
				$setarr1['ftype']=getFileTypeName('folder','');
				$setarr1['fdateline']=dgmdate($setarr1['dateline']);
				return array('icoarr'=>$setarr1,'folderarr'=>$setarr);
			}
		}
	return false;
}
function getAttachByMd5($message,$filename_title){
	global $_G,$space;
	$filename =date('His').''.strtolower(random(16));
	$ext=strtolower(substr(strrchr($filename_title, '.'), 1, 10));
	if(!$ext) $ext='dzzdoc';
	//保存附件并且生成附件MD5;
	$subdir = $subdir1 = $subdir2 = '';
	$subdir1 = date('Ym');
	$subdir2 = date('d');
	$subdir = $subdir1.'/'.$subdir2.'/';
	$target1='dzz/'.$subdir.'index.html';
	$target='dzz/'.$subdir;
	$target_attach=$_G['setting']['attachdir'].$target1;
	$targetpath = dirname($target_attach);
	dmkdir($targetpath);
	if($message=='') $message=' ';
	file_put_contents($_G['setting']['attachdir'].$target.$filename.'.'.$ext,$message);
	$size=@filesize($_G['setting']['attachdir'].$target.$filename.'.'.$ext);
	
	$md5=md5_file($_G['setting']['attachdir'].$target.$filename.'.'.$ext);
	if($md5 && $attach=DB::fetch_first("select * from ".DB::table('dzz_attachment')." where md5='{$md5}'")){
		$attach['filename']=$filename_title;
		$attach['filetype']=strtolower($ext);
		@unlink($_G['setting']['attachdir'].$target.$filename.'.'.$ext);
	}else{
		$attach=array(
						'uid'=>$space['uid'],
						'filesize'=>$size,
						'attachment'=>$target.$filename.'.'.$ext,
						'filetype'=>strtolower($ext),
						'filename' =>$filename_title,
						'remote'=>0,
						'copys' => 0,
						'md5'=>$md5,
						'dateline' => $_G['timestamp'],
		);
		if(!$attach['aid']=DB::insert('dzz_attachment',daddslashes($attach),1)){
			return false;
		}
	}
	return $attach;
}
function textsaveToattach($filename_title,$container,$message){
	global $_G,$space;
	if(!$attach=getAttachByMd5($message,$filename_title)){
		return array('error' => dzzlang('message','file_save_failure'));
	}
	if($space['maxspacesize']>0 && ($attach['filesize']+$space['usesize'])>$space['maxspacesize']){
		return array('error' => dzzlang('message','inadequate_capacity_space'));
	}
	$sourcedata=array(
					'uid'=>$space['uid'],
					'username'=>$space['username'],
					'filesize'=>$attach['filesize'],
					'attachment'=>$attach['attachment'],
					'filetype'=>$attach['filetype'],
					'filename' =>$attach['filename'],
					'remote'=>$attach['remote'],
					'copys' => 1,
					'img'=>geticonfromext($attach['filetype']),
					'friend'=>0,
					'dateline' => $_G['timestamp'],
					'aid'=>$attach['aid']
			);
		if($sourcedata['qid']=DB::insert('dzz_attach',daddslashes($sourcedata),1)){
			$icoarr=array(
								'uid'=>$space['uid'],
								'username'=>$space['username'],
								'oid'=>$sourcedata['qid'],
								'name'=>$sourcedata['filename'],
								'url'=>$_G['setting']['attachurl'].$attach['attachment'],
								'img'=>$sourcedata['img'],
								'type'=>'attach',
								'size'=>$attach['filesize'],
								'ext'=>$attach['filetype'],
								'friend'=>0,
								'dateline'=>$_G['timestamp'],
								'titlebuttons'=>'home,refresh,detail,min,max,close'
				);
			$icoarr['icoid']=DB::insert('dzz_icos',daddslashes($icoarr),1);
			if($icoarr['size']) DB::query("update ".DB::table('dzz_userconfig')." set usesize=usesize+$icoarr[size] where uid='{$space[uid]}'");
			DB::update('dzz_attachment',array('copys'=>$attach['copys']+1),"aid='{$attach[aid]}'");
		}
		
		if($icoarr['icoid'] ){
			if(addtoconfig($icoarr['icoid'],$container)){
				$icoarr['container']=$container;
				$icoarr['url']=replace_canshu($icoarr['url']);
					$icoarr['fsize']=formatsize($icoarr['size']);
					$icoarr['ftype']=getFileTypeName($icoarr['type'],$icoarr['ext']);
					$icoarr['fdateline']=dgmdate($icoarr['dateline']);
					
				return $icoarr;
			}else{
				dzz_delete_ico($icoarr['icoid']);
				return false;
			}
		}
	return false;
}
//移动用户桌面数据
function desktop_move_userdata($unavid,$uid,$targetunavid){
	global $_G;
	if($_G['uid']!=$uid && $_G['adminid']!=1){ return 'no_prevelige';}
	//获取用户桌面数据
	$userconfig=DB::fetch_first("select * from ".DB::table('dzz_userconfig')." where uid='$uid'");
	$screenlist=dstripslashes(unserialize(stripslashes($userconfig['screenlist'])));
	//处理icos
	if($screenlist[$targetunavid] && $screenlist[$unavid]['icos']){
		$screenlist[$targetunavid]['icos']=array_merge($screenlist[$targetunavid]['icos'],$screenlist[$unavid]['icos']);
	}
	//处理widgets
	foreach( $screenlist[$unavid]['widgets'] as $value){
		$screenlist[$targetunavid]['widgets'][$value['gid']]=$value;
	}
	//处理wins
	foreach( $screenlist[$unavid]['wins'] as $value){
		$screenlist[$targetunavid]['wins'][$value['icoid']]=$value;
	}
	
	
	DB::update('dzz_userconfig',array('screenlist'=>daddslashes(serialize($screenlist)))," uid='{$uid}'");
	return $screenlist[$targetunavid];
}
//删除用户桌面数据函数
function desktop_delete_userdata($unavid,$uid){
	global $_G;
	if($_G['uid']!=$uid && $_G['adminid']!=1){ return dzzlang('message','no_privilege');}
	//获取用户桌面数据
	$userconfig=DB::fetch_first("select * from ".DB::table('dzz_userconfig')." where uid='$uid'");
	$screenlist=dstripslashes(unserialize(stripslashes($userconfig['screenlist'])));
	//获取用户桌面icoid
	$icoids=$screenlist[$unavid]['icos'];
	foreach($icoids as $icoid){
		dzz_delete_ico($icoid);
	}
	$screenlist[$unavid]['icos']=array();
	//删除用户桌面的挂件
	$widgets=$screenlist[$unavid]['widgets'];
	foreach($widgets as $value){
		dzz_delete_widget($value['gid']);
	}
	$screenlist[$unavid]['widgets']=array();
	unset($screenlist[$unavid]);
	DB::update('dzz_userconfig',array('screenlist'=>daddslashes(serialize($screenlist)))," uid='{$uid}'");
}
//删除用户ico数据
function dzz_delete_widget($gid){
	global $_G;
	if($widget=DB::fetch_first("select * from ".DB::table('dzz_widget')." where gid='{$gid}'")){
		if($widget['uid']!=$_G['uid'] && $_G['adminid']!=1) return dzzlang('message','no_privilege');
		if($widget['idtype']=='pluginid' && $plugin=DB::fetch_first("select * from ".DB::table('dzz_plugin')." where pluginid='{$widget[typeid]}'")){
			if(is_file(DISCUZ_ROOT.'./dzz/plugin/'.$plugin['directory'].'fun.inc.php')){
				$plugin_delete_params=array('idtype'=>'gid','typeid'=>$widget['gid'],'uid'=>$widget['uid']);
				include DISCUZ_ROOT.'./dzz/plugin/'.$plugin['directory'].'fun.inc.php';
			}
		}
		DB::delete('dzz_widget',"gid='{$gid}'");
		return 'success';
	}else{
		return 'success';
	}
}
function dzz_delete_ico($icoid){//$dp为1表示处理位置,0:不处理位置；
	global $_G;
	if($icoarr=DB::fetch_first("select * from ".DB::table('dzz_icos')." where icoid='{$icoid}'")){
		if($_G['uid']!=$icoarr['uid'] && $_G['adminid']!=1){ return dzzlang('message','no_privilege');}
		switch($icoarr['type']){
			case 'folder':case 'image':case 'blog':case 'video':case 'attach':case 'link':case 'app':
				dzz_delete_source($icoarr['oid'],$icoarr['uid'],$icoarr['type']);
				break;
		}
		if($icoarr['idtype']=='pluginid' && $plugin=DB::fetch_first("select * from ".DB::table('dzz_plugin')." where pluginid='{$icoarr[typeid]}'")){
			if(is_file(DISCUZ_ROOT.'./dzz/plugin/'.$plugin['directory'].'fun.inc.php')){
				$plugin_delete_params=array('idtype'=>'icoid','typeid'=>$icoarr['icoid'],'uid'=>$icoarr['uid']);
				include DISCUZ_ROOT.'./dzz/plugin/'.$plugin['directory'].'fun.inc.php';
			}
		}
		if($icoarr['size']) DB::query("update ".DB::table('dzz_userconfig')." set usesize=usesize-$icoarr[size] where uid='{$icoarr[uid]}'");
		DB::delete('dzz_icos',"icoid='{$icoid}'");	
		return 'success';
	}
	return 'success';
}
function dzz_delete_source($oid,$uid,$type){
	global $_G;
	switch($type){
		case 'folder':
			if($folder=DB::fetch_first("select * from ".DB::table('dzz_folder')." where fid='{$oid}' and uid='{$uid}'")){
				$ids=explode(',',$folder['ids']);
				foreach($ids as $icoid){
					dzz_delete_ico($icoid);
				}
			}
			DB::delete('dzz_folder',"fid='{$oid}' and uid='{$uid}'");
			break;
		
		case 'app':
			if($app=DB::fetch_first("select * from ".DB::table('dzz_apps')." where appid='{$oid}'")){
				 DB::update('dzz_apps',array('setupnum'=>($app['setupnum']-1)<0?0:$app['setupnum']-1),"appid='{$app[appid]}'");
				if($app['uid']==$uid && $app['ismarket']<1){//是此用户应用且应用未加入应用市场则删除此应用
					if($app['appico']!='dzz/images/default/icodefault.png' && !preg_match("/^(http|ftp|https|mms)\:\/\/(.+?)/i", $app['appico'])){
						@unlink($_G['setting']['attachurl'].$app['appico']);
					}
					//删除应用图片
					$picids=array();
					$query=DB::query("select picid from ".DB::table('dzz_pic')." where id ='{$app[appid]}'");
					while($value=DB::fetch($query)){
						$picids[]=$value['picid'];
					}
					if($picids)	delete_pic($picids);
					
					//删除应用条目
					DB::delete('dzz_apps',"appid='{$app[appid]}'");
				}
			}
			break;
		case 'image':
			if($image=DB::fetch_first("select * from ".DB::table('dzz_image')." where picid='{$oid}' and uid='{$uid}'")){
				if($image['aid']){
					$attach=DB::fetch_first("select * from ".DB::table('dzz_attachment')." where aid='{$image[aid]}'");
					if($attach['copys']<=1){
						@unlink($_G['setting']['attachdir'].$attach['attachment']);
						if($attach['thumb']){
							@unlink($_G['setting']['attachdir'].$attach['attachment'].'.thumb.jpg');
						}
						DB::delete('dzz_attachment',"aid='{$image[aid]}'");
					}else{
						DB::update('dzz_attachment',array('copys'=>$attach['copys']-1),"aid='{$image[aid]}'");
					}
				}
				//处理采集库
				if($image['cid']){
					$copys=DB::result_first("select copys from ".DB::table('dzz_cimage')." where cid='{$image[cid]}'");
					if($copys<=1){
						DB::delete('dzz_cimage',"cid='{$image[cid]}'");
					}else{
						DB::update('dzz_cimage',array('copys'=>$copys-1),"cid='{$image[cid]}'");
					}
				}
			}
			DB::delete('dzz_image',"picid='{$oid}' and uid='{$uid}'");
			break;
		case 'video':
			if($video=DB::fetch_first("select * from ".DB::table('dzz_video')." where vid='{$oid}' and uid='{$uid}'")){
				if($video['aid']){
					$attach=DB::fetch_first("select * from ".DB::table('dzz_attachment')." where aid='{$video[aid]}'");
					if($attach['copys']<=1){
						@unlink($_G['setting']['attachdir'].$attach['attachment']);
						if($attach['thumb']){
							@unlink($_G['setting']['attachdir'].$attach['attachment'].'.thumb.jpg');
						}
						DB::delete('dzz_attachment',"aid='{$image[aid]}'");
					}else{
						DB::update('dzz_attachment',array('copys'=>$attach['copys']-1),"aid='{$video[aid]}'");
					}
				}
				//处理采集库
				if($video['cid']){
					$copys=DB::result_first("select copys from ".DB::table('dzz_cmusic')." where cid='{$video[cid]}'");
					if($copys<=1){
						DB::delete('dzz_cvideo',"cid='{$video[cid]}'");
					}else{
						DB::update('dzz_cvideo',array('copys'=>$copys-1),"cid='{$video[cid]}'");
					}
				}
			}
			DB::delete('dzz_video',"vid='{$oid}' and uid='{$uid}'");
			break;
		case 'music':
			if($music=DB::fetch_first("select * from ".DB::table('dzz_music')." where mid='{$oid}' and uid='{$uid}'")){
				if($music['aid']){
					$attach=DB::fetch_first("select * from ".DB::table('dzz_attachment')." where aid='{$music[aid]}'");
					if($attach['copys']<=1){
						@unlink($_G['setting']['attachdir'].$attach['attachment']);
						if($attach['thumb']){
							@unlink($_G['setting']['attachdir'].$attach['attachment'].'.thumb.jpg');
						}
						DB::delete('dzz_attachment',"aid='{$image[aid]}'");
					}else{
						DB::update('dzz_attachment',array('copys'=>$attach['copys']-1),"aid='{$music[aid]}'");
					}
				}
				//处理采集库
				if($music['cid']){
					$copys=DB::result_first("select copys from ".DB::table('dzz_cmusic')." where cid='{$music[cid]}'");
					if($copys<=1){
						DB::delete('dzz_cmusic',"cid='{$music[cid]}'");
					}else{
						DB::update('dzz_cmusic',array('copys'=>$copys-1),"cid='{$music[cid]}'");
					}
				}
			}
			DB::delete('dzz_music',"mid='{$oid}' and uid='{$uid}'");
			break;
		case 'link':
			if($link=DB::fetch_first("select * from ".DB::table('dzz_link')." where lid='{$oid}' and uid='{$uid}'")){
				//处理采集库
				if($link['cid']){
					$copys=DB::result_first("select copys from ".DB::table('dzz_clink')." where cid='{$link[cid]}'");
					if($copys<=1){
						DB::delete('dzz_clink',"cid='{$link[cid]}'");
					}else{
						DB::update('dzz_clink',array('copys'=>$copys-1),"cid='{$link[cid]}'");
					}
				}
				if($link['did']){
					if($icon=DB::fetch_first("select * from ".DB::table('dzz_icon')." where did='{$link[did]}'")){
						if($icon['check']<2 && $icon['copys']<2){
							@unlink(DISCUZ_ROOT.'./'.$icon['pic']);
							DB::delete('dzz_icon',"did='{$link[did]}'");
						}else{
							DB::update('dzz_icon',array('copys'=>$icon['copys']-1),"did='{$link[did]}'");
						}
					}
				}
			}
			DB::delete('dzz_link',"lid='{$oid}' and uid='{$uid}'");
			break;
		case 'attach':
			if($attach1=DB::fetch_first("select * from ".DB::table('dzz_attach')." where qid='{$oid}' and uid='{$uid}'")){
				if($attach1['aid']){
					$attach=DB::fetch_first("select * from ".DB::table('dzz_attachment')." where aid='{$attach1[aid]}'");
					if($attach['copys']<=1){
						@unlink($_G['setting']['attachdir'].$attach['attachment']);
						if($attach['thumb']){
							@unlink($_G['setting']['attachdir'].$attach['attachment'].'.thumb.jpg');
						}
						DB::delete('dzz_attachment',"aid='{$attach1[aid]}'");
					}else{
						DB::update('dzz_attachment',array('copys'=>$attach['copys']-1),"aid='{$attach1[aid]}'");
					}
				}
			}
			DB::delete('dzz_attach',"qid='{$oid}' and uid='{$uid}'");
			break;
	}
	
	return true;
}
//判断附件是否已经存在，返回附件数组
function dzz_imagetoattach($link){
	global $_G,$space;
	 $md5=md5_file($link);
	if($md5 && $attach=DB::fetch_first("select * from ".DB::table('dzz_attachment')." where md5='{$md5}'")){
		  //判断空间大小
		  if($space['maxspacesize']>0 && ($attach['filesize']+$space['usesize'])>$space['maxspacesize']){
			 return array('error' => dzzlang('message','inadequate_capacity_space'));
		 }
		return $attach;
	}else{
		if($target=imagetolocal($link,'dzz')){
			//判断空间大小
			$size=@filesize($_G['setting']['attachdir'].$target);
			if($space['maxspacesize']>0 && (intval($size)+$space['usesize'])>$space['maxspacesize']){
				@unlink($_G['setting']['attachdir'].$target);
				return array('error' => dzzlang('message','inadequate_capacity_space'));
			 }
			$attach=array(
							'uid'=>$space['uid'],
							'filesize'=>intval($size),
							'attachment'=>$target,
							'filetype'=>strtolower(substr(strrchr($link, '.'), 1, 10)),
							'filename' =>substr(strrchr($link, '/'), 1, 50),
							'remote'=>$remote,
							'copys' => 0,
							'md5'=>$md5,
							'dateline' => $_G['timestamp'],
			);
			if($attach['aid']=DB::insert('dzz_attachment',daddslashes($attach),1)){
				return $attach;
			}
		}
	}
	 return array('error' => dzzlang('message','unknow_error'));;
}
/*function linktolocal($source, $dir='dzz',$target='') {
	global $_G;
	if(empty($source)) return false;
	if(!$data =dzz_file_get_contents($source)) {
		return false;
	}
	
	if($target) {
		@unlink($_G['setting']['attachdir'].$target);
	}
	
	$ext=strtolower(substr(strrchr($source, '.'), 1, 10));
	
	$subdir = $subdir1 = $subdir2 = '';
	$subdir1 = date('Ym');
	$subdir2 = date('d');
	$subdir = $subdir1.'/'.$subdir2.'/';
	$target1=$_G['setting']['attachdir'].$dir.'/'.$subdir.''.date('His').''.strtolower(random(16)).'.'.$ext;
	$target=str_replace($_G['setting']['attachdir'],'',$target1);
	$targetpath = dirname($target1);
	dmkdir($targetpath);
	if(file_put_contents($target1, $data)){
		if(@filesize($target1)<1) {
			@unlink($target1);
			return false;
		}
		return $target;
	}else return false;
}*/
//判断附件是否已经存在，返回附件数组
/*function dzz_linktoattach($link){
	global $_G,$space;
	 $md5=md5_file($link);
	if($md5 && $attach=DB::fetch_first("select * from ".DB::table('dzz_attachment')." where md5='{$md5}'")){
		return $attach;
	}else{
		if($target=linktolocal($link,'dzz')){
			$attach=array(
							'uid'=>$space['uid'],
							'filesize'=>@filesize($_G['setting']['attachdir'].$target),
							'attachment'=>$target,
							'filetype'=>strtolower(substr(strrchr($link, '.'), 1, 10)),
							'filename' =>substr(strrchr($link, '/'), 1, 50),
							'remote'=>0,
							'copys' => 0,
							'md5'=>$md5,
							'dateline' => $_G['timestamp'],
			);
			if($attach['aid']=DB::insert('dzz_attachment',daddslashes($attach),1)){
				return $attach;
			}
		}
	}
	return false;
}*/
function linktoimage($link,$uid,$friend,$container){
	global $_G,$space;
	if(!$cimage=DB::fetch_first("select * from ".DB::table('dzz_cimage')." where ourl='{$link}'")){
		if($attach=dzz_imagetoattach($link)){
			if($attach['error']) return $attach;
			//生成缩略图
			require_once dzz_libfile('class/image');
			$image = new image;
			if($thumb = $image->Thumb($_G['setting']['attachurl'].$attach['attachment'],'',101, 101,1)){
				DB::update('dzz_attachment',array('thumb'=>$thumb),"aid='{$attach[aid]}'");
			}
			
			$cimage=array(	
							'filepath'=>$attach['attachment'],
							'filename' =>strtolower(substr(strrchr($link, '/'), 1, 50)),
							'type'=>strtolower(substr(strrchr($link, '.'), 1, 10)),
							'title' => strtolower(substr(strrchr($link, '/'), 1, 50)),
							'size'=>$attach['filesize'],
							'type'=>$attach['filetype'],
							'thumb' => $thumb,
							'remote' => $attach['remote'],
							'ourl'=>$link,
							'aid'=>$attach['aid'],
							'copys'=>0,
							'dateline'=>$_G['timestamp']
							);
			$cimage['cid']=DB::insert('dzz_cimage',daddslashes($cimage),1);
			
		}else{
			return false;
		}
	}
		//判断空间大小
		  if($space['maxspacesize']>0 && ($cimage['filesize']+$space['usesize'])>$space['maxspacesize']){
			 return array('error' => dzzlang('message','inadequate_capacity_space'));
		 }
		$imginfo=@getimagesize($_G['setting']['attachdir'].$cimage['filepath']);
		$sourcedata=array(
					'uid'=>$space['uid'],
					'username'=>$space['username'],
					'dateline' => $_G['timestamp'],
					'filepath'=>$cimage['filepath'],
					'filename' =>$cimage['filename'],
					'postip' => $_G['clientip'],
					'title' => $cimage['title'],
					'size'=>$cimage['size'],
					'type'=>$cimage['type'],
					'thumb' => $cimage['thumb'],
					'remote' => $cimage['remote'],
					'copys' => 1,
					'cid'=>$cimage['cid'],
					'aid'=>$cimage['aid'],
					'friend'=>$friend,
					'width'=>$imginfo[0],
					'height'=>$imginfo[1]
		);
		if($sourcedata['picid']=DB::insert('dzz_image',daddslashes($sourcedata),1)){
			if($cimage['aid']) DB::query("update ".DB::table('dzz_attachment')." set copys=copys+1 where aid='{$cimage[aid]}'");
			DB::update('dzz_cimage',array('copys'=>$cimage['copys']+1),"cid='{$cimage[cid]}'");
			$icoarr=array(
							'uid'=>$space['uid'],
							'username'=>$space['username'],
							'oid'=>$sourcedata['picid'],
							'name'=>strtolower(substr(strrchr($link, '/'), 1, 50)),
							'url'=>$_G['setting']['attachurl'].$sourcedata['filepath'],
							'img'=>$sourcedata['thumb']?getimgthumbname($_G['setting']['attachurl'].$sourcedata['filepath']):$_G['setting']['attachurl'].$sourcedata['filepath'],
							'type'=>'image',
							'size'=>$sourcedata['size'],
							'wwidth'=>$sourcedata['width'],
							'wheight'=>$sourcedata['height'],
							'friend'=>$friend,
							'dateline'=>$_G['timestamp'],
							'open'=>0,
							'titlebuttons'=>'home,refresh,detail,min,max,close'
			);
			$icoarr['icoid']=DB::insert('dzz_icos',daddslashes($icoarr),1);
			
			if($icoarr['size']) DB::query("update ".DB::table('dzz_userconfig')." set usesize=usesize+$icoarr[size] where uid='{$space[uid]}'");
		}
			
		if($icoarr['icoid'] ){
			if(addtoconfig($icoarr['icoid'],$container)){
				$icoarr['container']=$container;
				$icoarr['url']=replace_canshu($icoarr['url']);
				$icoarr['fsize']=formatsize($icoarr['size']);
				$icoarr['ftype']=getFileTypeName($icoarr['type'],$icoarr['ext']);
				$icoarr['fdateline']=dgmdate($icoarr['dateline']);
				return $icoarr;
			}else{
				dzz_delete_ico($icoarr['icoid']);
				return false;
			}
		}
}
function linktomusic($link,$uid,$friend,$container){
	global $_G,$space,$videoext,$ext;
	
	if(!$cmusic=DB::fetch_first("select * from ".DB::table('dzz_cmusic')." where ourl='{$link}'")){
		
			$cmusic=array(	
							'url'=>$link,
							'ourl'=>$link,
							'img'=>'',
							'desc' =>$link,
							'title' => strtolower(substr(strrchr($link, '/'), 1, 50)),
							'size'=>@filesize($link),
							'ext'=>strtolower(substr(strrchr($link, '.'), 1, 10)),
							'copys' => 0,
							'aid'=>0,
							'dateline'=>$_G['timestamp']
							);
			$cmusic['cid']=DB::insert('dzz_cmusic',daddslashes($cmusic),1);	
		
	}
	$sourcedata=array(
						'uid'=>$space['uid'],
						'username'=>$space['username'],
						'url'=>$cmusic['url'],
						'img'=>$cmusic['img'],
						'desc' =>$cmusic['desc'],
						'title' =>$cmusic['title'],
						'size'=>$cmusic['size'],
						'ext'=>$cmusic['ext'],
						'copys' => 1,
						'aid'=>$cmusic['aid'],
						'cid'=>$cmusic['cid'],
						'dateline' => $_G['timestamp'],
						'friend'=>$friend
	
	);
	if($sourcedata['mid']=DB::insert('dzz_music',daddslashes($sourcedata),1)){
		if($cmusic['aid']) DB::query("update ".DB::table('dzz_attachment')." set copys=copys+1 where aid='{$cmusic[aid]}'");
		DB::update('dzz_cmusic',array('copys'=>$cmusic['copys']+1),"cid='{$cmusic[cid]}'");
		$icoarr=array(
						'uid'=>$space['uid'],
						'username'=>$space['username'],
						'oid'=>$sourcedata['mid'],
						'name'=>$sourcedata['title'],
						'url'=>$sourcedata['url'],
						'img'=>$sourcedata['img']?$sourcedata['img']:geticonfromext($ext,'music'),
						'size'=>$sourcedata['size'],
						'ext'=>$sourcedata['ext'],
						'type'=>'music',
						'friend'=>$friend,
						'dateline'=>$_G['timestamp'],
						'titlebuttons'=>'home,refresh,detail,min,max,close'
		);
		$icoarr['icoid']=DB::insert('dzz_icos',daddslashes($icoarr),1);
	}
	
	if($icoarr['icoid'] ){
		if(addtoconfig($icoarr['icoid'],$container)){
				$icoarr['container']=$container;
				$icoarr['url']=replace_canshu($icoarr['url']);
				$icoarr['fsize']=formatsize($icoarr['size']);
				$icoarr['ftype']=getFileTypeName($icoarr['type'],$icoarr['ext']);
				$icoarr['fdateline']=dgmdate($icoarr['dateline']);
			return $icoarr;
		}else{
			dzz_delete_ico($icoarr['icoid']);
			return array('error' => dzzlang('message','unknow_error'));
		}
	}
	
}
function linktovideo($link,$uid,$friend,$container){
	global $_G,$space,$videoext,$ext;
	if(!$cvideo=DB::fetch_first("select * from ".DB::table('dzz_cvideo')." where ourl='{$link}'")){
		$arr=array();
		if(in_array($ext, $videoext)){
			$arr['ourl']=$link;
			$arr['url']=$link;
			$arr['title']=strtolower(substr(strrchr($link, '/'), 1, 50));
			
		}else{
			require_once dzz_libfile('function/dzz_discuzcode');
			if(!$arr=parseflv($link)){
				return false;
			}
			//采集标题和描述
			if(!$arr['title'] || !$arr['description']){
				if($info=getmetatags($link)){
					if($info['title']) $arr['title']=$info['title'];
					if($info['description']) $arr['description']=$info['description'];
				}
			}
		}
		
		$cvideo=array(	
						'url'=>$arr['url'],
						'ourl'=>$link,
						'img'=>$arr['img'],
						'desc' =>$arr['description'],
						'title' => $arr['title'],
						'size'=>0,
						'copys' => 0,
						'aid'=>0,
						'dateline'=>$_G['timestamp']
						);
		$cvideo['cid']=DB::insert('dzz_cvideo',daddslashes($cvideo),1);
	}
	//如果原先的标题和描述没采集到，重新采集
	if(!$cvideo['title'] || !$cvideo['desc']){
		if($info=getmetatags($link)){
			$flag=0;
			if($info['title']) {
				$cvideo['title']=$info['title'];
				$flag=1;
			}
			if($info['description']) {
				$cvideo['desc']=$info['description'];
				$flag=1;
			}
			if($flag) DB::update('dzz_cvideo',daddslashes(array('title'=>$cvideo['title'],'desc'=>$cvideo['desc'])),"cid='{$cvideo[cid]}'");
		}
	}
	$sourcedata=array(
			'uid'=>$space['uid'],
			'username'=>$space['username'],
			'url'=>$cvideo['url'],
			'img'=>$cvideo['img'],
			'desc' =>$cvideo['desc'],
			'title' =>$cvideo['title'],
			'size'=>$cvideo['size'],
			'copys' => 1,
			'aid'=>$cvideo['aid'],
			'cid'=>$cvideo['cid'],
			'dateline' => $_G['timestamp'],
			'friend'=>$friend
	);
	if($sourcedata['vid']=DB::insert('dzz_video',daddslashes($sourcedata),1)){
		if($cvideo['aid']) DB::query("update ".DB::table('dzz_attachment')." set copys=copys+1 where aid='{$cvideo[aid]}'");
		DB::update('dzz_cvideo',array('copys'=>$cvideo['copys']+1),"cid='{$cvideo[cid]}'");
		$icoarr=array(
						'uid'=>$space['uid'],
						'username'=>$space['username'],
						'oid'=>$sourcedata['vid'],
						'name'=>$sourcedata['title'],
						'url'=>$sourcedata['url'],
						'img'=>$sourcedata['img']?$sourcedata['img']:geticonfromext($ext,'video'),
						'type'=>'video',
						'friend'=>$friend,
						'dateline'=>$_G['timestamp'],
						'titlebuttons'=>'home,refresh,detail,min,max,close'
						
		);
		$icoarr['icoid']=DB::insert('dzz_icos',daddslashes($icoarr),1);
	}

	if($icoarr['icoid'] ){
		if(addtoconfig($icoarr['icoid'],$container)){
				$icoarr['container']=$container;
				$icoarr['url']=replace_canshu($icoarr['url']);
				$icoarr['fsize']=formatsize($icoarr['size']);
				$icoarr['ftype']=getFileTypeName($icoarr['type'],$icoarr['ext']);
				$icoarr['fdateline']=dgmdate($icoarr['dateline']);
			return $icoarr;
		}else{
			dzz_delete_ico($icoarr['icoid']);
			return array('error' => dzzlang('message','unknow_error'));
		}
	}
	
}
function geticonfromext($ext,$type){
	global $_G;
	$img='dzz/images/extimg/'.$ext.'.png';
	if(!is_file(DISCUZ_ROOT.$img)){
		switch($type){
			case 'video':
				$img='dzz/images/extimg/video.png';
				break;
			case 'music':
				$img='dzz/images/extimg/music.png';
				break;
			default:
				$img='dzz/images/extimg/unknow.png';
		}
	}
	return $img;
}
function linktourl($link,$uid,$friend,$container){
	global $_G,$space;
	$parseurl=parse_url($link);
	$host=$parseurl['host'];
	$clink=array();
	if(!$clink=DB::fetch_first("select * from ".DB::table("dzz_clink")." where url='{$link}'")){
		$arr=array();
		if($info=getmetatags($link)){
			$arr['title']=$info['title'];
			$arr['description']=$info['description'];
			$clink=array(
				'url'=>$link,
				'img'=>'',
				'desc' =>$arr['description'],
				'title' => $arr['title'],
				'copys' => 0,
				'dateline'=>$_G['timestamp']
			);
			$clink['cid']=DB::insert('dzz_clink',daddslashes($clink),1);
		}
	}
	$icondata=getUrlIcon($link,$uid);
	$sourcedata=array(
				'uid'=>$space['uid'],
				'username'=>$space['username'],
				'url'=>$link,
				'img'=>$icondata['img'],
				'desc' =>$clink['desc'],
				'title' => $clink['title'],
				'copys' => 1,
				'cid'=>$clink['cid'],
				'did'=>$icondata['did'],
				'dateline'=>$_G['timestamp']
				
				);
	if($sourcedata['lid']=DB::insert('dzz_link',daddslashes($sourcedata),1)){
			DB::update('dzz_clink',array('copys'=>$clink['copys']+1),"cid='{$clink[cid]}'");
			
			$icoarr=array(
							'uid'=>$space['uid'],
							'username'=>$space['username'],
							'oid'=>$sourcedata['lid'],
							'name'=>$sourcedata['title']?$sourcedata['title']:$host,
							'url'=>$sourcedata['url'],
							'img'=>$sourcedata['img'],
							'type'=>'link',
							'friend'=>$friend,
							'dateline'=>$_G['timestamp'],
							'titlebuttons'=>'home,refresh,detail,min,max,close'
							
			);
			$icoarr['icoid']=DB::insert('dzz_icos',daddslashes($icoarr),1);	
	}
		
	if($icoarr['icoid'] ){
		if(addtoconfig($icoarr['icoid'],$container)){
			$icoarr['container']=$container;
			$icoarr['url']=replace_canshu($icoarr['url']);
				$icoarr['fsize']=formatsize($icoarr['size']);
				$icoarr['ftype']=getFileTypeName($icoarr['type'],$icoarr['ext']);
				$icoarr['fdateline']=dgmdate($icoarr['dateline']);
			return $icoarr;
		}else{
			dzz_delete_ico($icoarr['icoid']);
			return array('error' => dzzlang('message','unknow_error'));
		}
	}
	
}
function getUrlIcon($link,$uid){
	global $_G,$space;
	$rarr=array();
	$parse_url=parse_url($link);
	$host=$parse_url['host'];
	$host=preg_replace("/^www./",'',$host);//strstr('.',$host);
	//查询用户自定义特征库
	if($usericon=DB::fetch_first("select * from ".DB::table('dzz_usericon')." where uid='{$uid}' and domain='{$host}'")){
		if($usericon['pdid']) DB::query("update ".DB::table('dzz_icon')." set copys=copys+1 where did='{$usericon[pdid]}'");
		return array('img'=>$usericon['pic'],'did'=>$usericon['pdid']);
	}elseif($icon=DB::fetch_first("select * from ".DB::table('dzz_icon')." where domain='{$host}' and `check`>0  order by `check` DESC")){
		DB::update('dzz_icon',array('copys'=>$icon['copys']+1),"did='{$icon[did]}'");
		return array('img'=>$_G['setting']['attachurl'].$icon['pic'],'did'=>$icon['did']);
	}else{
		$source='';
		$ico=$parse_url['scheme'].'://'.$host.'/favicon.ico';
		$ico_not_www=$parse_url['scheme'].'://www.'.$parse_url['host_not_www'].'/favicon.ico';
		if($ico && check_remote_file_exists($ico)) $source=$ico;
		elseif($ico_not_www && check_remote_file_exists($ico_not_www)) $source=$ico_not_www;
		if($source){
			$subdir = $subdir1 = $subdir2 = '';
			$subdir1 = date('Ym');
			$subdir2 = date('d');
			$subdir = $subdir1.'/'.$subdir2.'/';
			$target='icon/'.$subdir.''.$host.'_'.strtolower(random(8)).'.png';
			$target_attach=$_G['setting']['attachdir'].$target;
			$targetpath = dirname($target_attach);
			dmkdir($targetpath);
			ico_png($source,$target_attach);
			if(is_file($target_attach)){
				if($did=DB::insert("dzz_icon",array('domain'=>$host,'pic'=>$target,'dateline'=>$_G['timestamp'],'check'=>1,'uid'=>$uid,'username'=>$space['username'],'copys'=>1),1)){
					return array('img'=>$_G['setting']['attachurl'].$target,'did'=>$did);
				}
			}
		}
	}
	return array('img'=>'dzz/images/default/e.png','did'=>0);
}
function addtoconfig($icoid,$container){
	global $_G,$space;
	if(strpos($container,'icosContainer_body_')!==false){
		$desktop=str_replace('icosContainer_body_','',$container);
		if(!$desktop) return false;
		if(strpos($desktop,'sys_')!==false) $duid=0;
		else $duid=$space['uid'];
		if($space['self']<2 && strpos($desktop,'sys_')!==false){ 
			return false;
		}else{
			if($config=DB::fetch_first("select screenlist from ".DB::table('dzz_userconfig')." where uid='{$duid}'")){
				$screenlist=unserialize(stripslashes($config['screenlist']));
				if($screenlist[$desktop]){
					$screenlist[$desktop]['icos'][]=$icoid;
					DB::update('dzz_userconfig',array('screenlist'=>addslashes(serialize($screenlist))),"uid='{$duid}'");
				}
				return true;
			}
		}
	}elseif(strpos($container,'icosContainer_folder_')!==false){
		$fid=str_replace('icosContainer_folder_','',$container);
		if(intval($fid)<1) return false;
		if($folder=DB::fetch_first("select ids from ".DB::table('dzz_folder')." where fid='{$fid}'")){
			if($folder['ids']) $ids=explode(',',$folder['ids']);
			else $ids=array();
			$ids[]=$icoid;
			DB::update('dzz_folder',array('ids'=>implode(',',$ids)),"fid='{$fid}'");
			return true;
		}
	}
	return false;
}
function getmetatags($link){
	global $_G;
	$arr=array(
					'title'=>'',
					'charset'=>'',
					'keywords'=>'',
					'description'=>'',
					);
	$chararr=array('GBK','GB2312','UTF-8','BIG5','iso-8859-1');
	$str = dzz_file_get_contents($link);
	if(!$str) return array();
	$arr=array();
	if(	preg_match("/charset=\"*(.*?)\"/i",$str,$matches2)){
		$arr['charset']=$matches2[1];
	}elseif(function_exists('mb_convert_encoding')) {
		if($char=mb_detect_encoding($str,$chararr)){
			$arr['charset']=$char;
		}else{
			$arr['charset']='';
		}
	}
	
	if(preg_match("/<title>(.*?)<\/title>/ims",$str, $matches1)){
		$arr['title']=trim(getstr($matches1[1],80),'...');
		if($arr['charset']) $arr['title']=diconv($arr['title'],$arr['charset']);
	}
	if(preg_match("/<meta\s+name=\"*description\"*\s+content=\"(.*?)\"/i",$str,$desc)||preg_match("/<meta\s+content=\"(.*?)\"\s+name=\"*description\"*/i",$str,$desc)){
		$arr['description']=$desc[1];
		if($arr['charset']) $arr['description']=diconv($arr['description'],$arr['charset']);
	}
	if(preg_match("/<meta\s+name=\"*keywords\"*\s+content=\"(.*?)\"/i",$str,$keyword) || preg_match("/<meta\s+content=\"(.*?)\"\s+name=\"*keywords\"*/i",$str,$keyword)){
		$arr['keywords']=$keyword[1];
		if($arr['charset']) $arr['keywords']=diconv($arr['keywords'],$arr['charset']);
	}
	return $arr;
}
function uploadToattachment($attach,$uid,$friend,$container){
	global $_G,$space;
	$imgext  = array('jpg', 'jpeg', 'gif', 'png', 'bmp');
	/*$musicext  = array('mp3','wma','ram','ra','mid');
	$videoext  = array('swf', 'flv','rmvb','rtsp','asx','wmv','mms','avi','mpg','mpeg','mov');*/
	
	if(in_array($attach['filetype'],$imgext)){
		//生成缩略图
		require_once dzz_libfile('class/image');
		$image = new image;
		if($thumb = $image->Thumb($_G['setting']['attachurl'].$attach['attachment'],'',101, 101,1)){
				DB::update('dzz_attachment',array('thumb'=>$thumb),"aid='{$attach[aid]}'");
		}
		$imginfo=@getimagesize($_G['setting']['attachdir'].$attach['attachment']);
		$sourcedata=array(
							'uid'=>$space['uid'],
							'username'=>$space['username'],
							'dateline' => $_G['timestamp'],
							'filepath'=>$attach['attachment'],
							'filename' =>$attach['filename'],
							'postip' => $_G['clientip'],
							'title' => $attach['filename'],
							'size'=>$attach['filesize'],
							'thumb' => $thumb,
							'remote' => 0,
							'aid'=>$attach['aid'],
							'copys' => 1,
							'type'=>$attach['filetype'],
							'width'=>$imginfo[0],
							'height'=>$imginfo[1],
							'dateline'=>$_G['timestamp']
		);
		if($sourcedata['picid']=DB::insert('dzz_image',daddslashes($sourcedata),1)){
			if($thumb) DB::update('dzz_attachment',array('thumb'=>$thumb),"aid='{$attach[aid]}'");
			$icoarr=array(
					'uid'=>$space['uid'],
					'username'=>$space['username'],
					'oid'=>$sourcedata['picid'],
					'name'=>$sourcedata['title'],
					'url'=>$_G['setting']['attachurl'].$attach['attachment'],
					'img'=>$thumb?getimgthumbname($_G['setting']['attachurl'].$attach['attachment']):$_G['setting']['attachurl'].$attach['attachment'],
					'type'=>'image',
					'wwidth'=>$sourcedata['width'],
					'wheight'=>$sourcedata['height'],
					'size'=>$sourcedata['size'],
					'ext'=>$attach['filetype'],
					'friend'=>$friend,
					'dateline'=>$_G['timestamp'],
					'titlebuttons'=>'home,refresh,detail,min,max,close'
					
			);
			$icoarr['icoid']=DB::insert('dzz_icos',daddslashes($icoarr),1);	
			if($icoarr['size']) DB::query("update ".DB::table('dzz_userconfig')." set usesize=usesize+$icoarr[size] where uid='{$space[uid]}'");
		}
		
	/*}elseif(in_array($attach['filetype'],$videoext)){
		$sourcedata=array(
							'uid'=>$space['uid'],
							'username'=>$space['username'],
							'url'=>$_G['setting']['attachurl'].$attach['attachment'],
							
							'img'=>geticonfromext($attach['filetype'],'video'),
							'desc' =>'',
							'title' => $attach['filename'],
							'size'=>$attach['filesize'],
							'ext'=>$attach['filetype'],
							'copys' => 1,
							'aid'=>$attach['aid'],
							'dateline' => $_G['timestamp'],
		
		);
		if($sourcedata['vid']=DB::insert('dzz_video',daddslashes($sourcedata),1)){
			$icoarr=array(
							'uid'=>$space['uid'],
							'username'=>$space['username'],
							'oid'=>$sourcedata['vid'],
							'name'=>$sourcedata['title'],
							'url'=>$sourcedata['url'],
							'img'=>$sourcedata['img'],
							'type'=>'video',
							'size'=>$sourcedata['size'],
							'ext'=>$attach['filetype'],
							'friend'=>$friend,
							'dateline'=>$_G['timestamp'],
							
			);
			$icoarr['icoid']=DB::insert('dzz_icos',daddslashes($icoarr),1);
			if($icoarr['size']) DB::query("update ".DB::table('dzz_userconfig')." set usesize=usesize+$icoarr[size] where uid='{$space[uid]}'");
		}
	}elseif(in_array($attach['filetype'],$musicext)){
		$sourcedata=array(
							'uid'=>$space['uid'],
							'username'=>$space['username'],
							'url'=>$_G['setting']['attachurl'].$attach['attachment'],
							'img'=>geticonfromext($attach['filetype'],'music'),
							
							'desc' =>'',
							'title' => $attach['filename'],
							'size'=>$attach['filesize'],
							'ext'=>$attach['filetype'],
							'copys' => 1,
							'aid'=>$attach['aid'],
							'dateline' => $_G['timestamp'],
		
		);
		if($sourcedata['mid']=DB::insert('dzz_music',daddslashes($sourcedata),1)){
			$icoarr=array(
							'uid'=>$space['uid'],
							'username'=>$space['username'],
							'oid'=>$sourcedata['mid'],
							'name'=>$sourcedata['title'],
							'url'=>$sourcedata['url'],
							'img'=>$sourcedata['img'],
							'type'=>'music',
							'friend'=>$friend,
							'size'=>$attach['filesize'],
							'ext'=>$attach['filetype'],
							'dateline'=>$_G['timestamp'],
							
			);
			$icoarr['icoid']=DB::insert('dzz_icos',daddslashes($icoarr),1);
			if($icoarr['size']) DB::query("update ".DB::table('dzz_userconfig')." set usesize=usesize+$icoarr[size] where uid='{$space[uid]}'");
		}*/
	}else{
		$sourcedata=array(
							'uid'=>$space['uid'],
							'username'=>$space['username'],
							'filesize'=>$attach['filesize'],
							'attachment'=>$attach['attachment'],
							'filetype'=>$attach['filetype'],
							'filename' =>$attach['filename'],
							'remote'=>$attach['remote'],
							'copys' => 1,
							'img'=>geticonfromext($attach['filetype']),
							'friend'=>$friend,
							'dateline' => $_G['timestamp'],
							'aid'=>$attach['aid']
			);
		if($sourcedata['qid']=DB::insert('dzz_attach',daddslashes($sourcedata),1)){
			$icoarr=array(
								'uid'=>$space['uid'],
								'username'=>$space['username'],
								'oid'=>$sourcedata['qid'],
								'name'=>$sourcedata['filename'],
								'url'=>$_G['setting']['attachurl'].$attach['attachment'],
								'img'=>$sourcedata['img'],
								'type'=>'attach',
								'size'=>$attach['filesize'],
								'ext'=>$attach['filetype'],
								'friend'=>$friend,
								'dateline'=>$_G['timestamp'],
								'titlebuttons'=>'home,refresh,detail,min,max,close'
								
				);
			$icoarr['icoid']=DB::insert('dzz_icos',daddslashes($icoarr),1);
			if($icoarr['size']) DB::query("update ".DB::table('dzz_userconfig')." set usesize=usesize+$icoarr[size] where uid='{$space[uid]}'");
		}
	}
	DB::update('dzz_attachment',array('copys'=>$attach['copys']+1),"aid='{$attach[aid]}'");
	
		
	if($icoarr['icoid'] ){
		if(addtoconfig($icoarr['icoid'],$container)){
			$icoarr['container']=$container;
			$icoarr['url']=replace_canshu($icoarr['url']);
				$icoarr['fsize']=formatsize($icoarr['size']);
				$icoarr['ftype']=getFileTypeName($icoarr['type'],$icoarr['ext']);
				$icoarr['fdateline']=dgmdate($icoarr['dateline']);
			return $icoarr;
		}else{
			dzz_delete_ico($icoarr['icoid']);
			return false;
		}
	}
	
}

?>