$_v) { ${$_k} = $_v; } foreach($vs AS $_k=>$_v) { ${$_k} = $_v; } include template($tFile); return render_hook(ob_get_clean()); } function render_hook($c) { global $INI; $c = preg_replace('#href="/#i', 'href="'.WEB_ROOT.'/', $c); $c = preg_replace('#src="/#i', 'src="'.WEB_ROOT.'/', $c); $c = preg_replace('#action="/#i', 'action="'.WEB_ROOT.'/', $c); /* theme */ $page = strval($_SERVER['REQUEST_URI']); if($INI['skin']['theme'] && !preg_match('#/manage/#i',$page)) { $themedir = WWW_ROOT. '/static/theme/' . $INI['skin']['theme']; $checkfile = $themedir. '/css/index.css'; if ( file_exists($checkfile) ) { $c = preg_replace('#/static/css/#', "/static/theme/{$INI['skin']['theme']}/css/", $c); $c = preg_replace('#/static/img/#', "/static/theme/{$INI['skin']['theme']}/img/", $c); } } if (strtolower(cookieget('locale','zh_cn'))=='zh_tw') { require_once(DIR_FUNCTION . '/tradition.php'); $c = str_replace(explode('|',$_charset_simple), explode('|',$_charset_tradition),$c); } return $c; } function output_hook($c) { global $INI; if ( 0==abs(intval($INI['system']['gzip']))) die($c); $HTTP_ACCEPT_ENCODING = $_SERVER["HTTP_ACCEPT_ENCODING"]; if( strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false ) $encoding = 'x-gzip'; else if( strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false ) $encoding = 'gzip'; else $encoding == false; if (function_exists('gzencode')&&$encoding) { $c = gzencode($c); header("Content-Encoding: {$encoding}"); } $length = strlen($c); header("Content-Length: {$length}"); die($c); } $lang_properties = array(); function I($key) { global $lang_properties, $LC; if (!$lang_properties) { $ini = DIR_ROOT . '/i18n/' . $LC. '/properties.ini'; $lang_properties = Config::Instance($ini); } return isset($lang_properties[$key]) ? $lang_properties[$key] : $key; } function json($data, $type='eval') { $type = strtolower($type); $allow = array('eval','alert','updater','dialog','mix', 'refresh'); if (false==in_array($type, $allow)) return false; Output::Json(array( 'data' => $data, 'type' => $type,)); } function redirect($url=null) { header("Location: {$url}"); exit; } function write_php_file($array, $filename=null){ $v = ""; return file_put_contents($filename, $v); } function write_ini_file($array, $filename=null){ $ok = null; if ($filename) { $s = ";;;;;;;;;;;;;;;;;;\r\n"; $s .= ";; SYS_INIFILE\r\n"; $s .= ";;;;;;;;;;;;;;;;;;\r\n"; } foreach($array as $k=>$v) { if(is_array($v)) { if($k != $ok) { $s .= "\r\n[{$k}]\r\n"; $ok = $k; } $s .= write_ini_file($v); }else { if(trim($v) != $v || strstr($v,"[")) $v = "\"{$v}\""; $s .= "$k = \"{$v}\"\r\n"; } } if(!$filename) return $s; return file_put_contents($filename, $s); } function save_config($type='ini') { global $INI; $q = ZSystem::GetSaveINI($INI); if ( strtoupper($type) == 'INI' ) { if (!is_writeable(SYS_INIFILE)) return false; return write_ini_file($q, SYS_INIFILE); } if ( strtoupper($type) == 'PHP' ) { if (!is_writeable(SYS_PHPFILE)) return false; return write_php_file($q, SYS_PHPFILE); } return false; } function save_system($ini) { $system = Table::Fetch('system', 1); $ini = ZSystem::GetUnsetINI($ini); $value = Utility::ExtraEncode($ini); $table = new Table('system', array('value'=>$value)); if ( $system ) $table->SetPK('id', 1); return $table->update(array( 'value')); } /* user relative */ function need_login($force=false) { if ( isset($_SESSION['user_id']) ) { if (is_post()) { unset($_SESSION['loginpage']); unset($_SESSION['loginpagepost']); } return $_SESSION['user_id']; } if ( is_get() ) { Session::Set('loginpage', $_SERVER['REQUEST_URI']); } else { Session::Set('loginpage', $_SERVER['HTTP_REFERER']); Session::Set('loginpagepost', json_encode($_POST)); } return redirect(WEB_ROOT . '/account/loginup.php'); } function need_post() { return is_post() ? true : redirect(WEB_ROOT . '/index.php'); } function need_manager($super=false) { if ( ! is_manager() ) { redirect( WEB_ROOT . '/manage/login.php' ); } if ( ! $super ) return true; if ( abs(intval($_SESSION['user_id'])) == 1 ) return true; return redirect( WEB_ROOT . '/manage/misc/index.php'); } function need_partner() { return is_partner() ? true : redirect( WEB_ROOT . '/biz/login.php'); } function need_partner_id($id=0) { $pid = $_SESSION['partner_id']; return $id == $pid ? true : redirect( WEB_ROOT . '/biz/login.php'); } function need_auth($b=true) { global $AJAX, $INI, $login_user; if (is_string($b)) { $auths = $INI['authorization'][$login_user['id']]; $b = is_manager(true)||in_array($b, $auths); } if (true===$b) { return true; } if ($AJAX) json('无权操作', 'alert'); Session::Set('error', '无权操作'); redirect( WEB_ROOT . '/account/login.php'); } function is_manager($super=false, $weak=false) { global $login_user; if ( $weak===false && ( !$_SESSION['admin_id'] || $_SESSION['admin_id'] != $login_user['id']) ) { return false; } if ( ! $super ) return ($login_user['manager'] == 'Y'); return $login_user['id'] == 1; } function is_partner() { return ($_SESSION['partner_id']>0); } function is_newbie(){ return (cookieget('newbie')!='N'); } function is_get() { return ! is_post(); } function is_post() { return strtoupper($_SERVER['REQUEST_METHOD']) == 'POST'; } function is_login() { return isset($_SESSION['user_id']); } function get_loginpage($default=null) { $loginpage = Session::Get('loginpage', true); if ($loginpage) return $loginpage; if ($default) return $default; return WEB_ROOT . '/index.php'; } function cookie_city($city) { global $INI; if($city) { cookieset('city', $city['id']); return $city; } $city_id = cookieget('city'); if (!$city_id) { $city = get_city(); if (!$city) { $city = Table::Fetch('category', $INI['hotcity'][0]); } if ($city) cookie_city($city); return $city; } else { if (in_array($city_id, $INI['hotcity'])) { return Table::Fetch('category', $city_id); } $INI['hotcity'] = array_diff($INI['hotcity'], array(0,NULL)); $city = Table::Fetch('category', $INI['hotcity'][0]); } return $city; } function cookieset($k, $v, $expire=0) { $pre = substr(md5($_SERVER['HTTP_HOST']),0,4); $k = "{$pre}_{$k}"; if ($expire==0) { $expire = time() + 365 * 86400; } else { $expire += time(); } setCookie($k, $v, $expire, '/'); } function cookieget($k, $default='') { $pre = substr(md5($_SERVER['HTTP_HOST']),0,4); $k = "{$pre}_{$k}"; return isset($_COOKIE[$k]) ? strval($_COOKIE[$k]) : $default; } function moneyit($k) { return rtrim(rtrim(sprintf('%.2f',$k), '0'), '.'); } function debug($v, $e=false) { global $login_user_id; if ($login_user_id==100000) { echo "
";
		var_dump( $v);
		if($e) exit;
	}
}

function getparam($index=0, $default=0) {
	if (is_numeric($default)) {
		$v = abs(intval($_GET['param'][$index]));
	} else $v = strval($_GET['param'][$index]);
	return $v ? $v : $default;
}
function getpage() {
	$c = abs(intval($_GET['page']));
	return $c ? $c : 1;
}
function pagestring($count, $pagesize, $wap=false) {
	$p = new Pager($count, $pagesize, 'page');
	if ($wap) {
		return array($pagesize, $p->offset, $p->genWap());
	}
	return array($pagesize, $p->offset, $p->genBasic());
}

function uencode($u) {
	return base64_encode(urlEncode($u));
}
function udecode($u) {
	return urlDecode(base64_decode($u));
}

/* share link */
function share_renren($team) {
	global $login_user_id;
	global $INI;
	if ($team)  {
		$query = array(
				'link' => $INI['system']['wwwprefix'] . "/team.php?id={$team['id']}&r={$login_user_id}",
				'title' => $team['title'],
				);
	}
	else {
		$query = array(
				'link' => $INI['system']['wwwprefix'] . "/r.php?r={$login_user_id}",
				'title' => $INI['system']['sitename'] . '(' .$INI['system']['wwwprefix']. ')',
				);
	}

	$query = http_build_query($query);
	return 'http://share.renren.com/share/buttonshare.do?'.$query;
}

function share_kaixin($team) {
	global $login_user_id;
	global $INI;
	if ($team)  {
		$query = array(
				'rurl' => $INI['system']['wwwprefix'] . "/team.php?id={$team['id']}&r={$login_user_id}",
				'rtitle' => $team['title'],
				'rcontent' => strip_tags($team['summary']),
				);
	}
	else {
		$query = array(
				'rurl' => $INI['system']['wwwprefix'] . "/r.php?r={$login_user_id}",
				'rtitle' => $INI['system']['sitename'] . '(' .$INI['system']['wwwprefix']. ')',
				'rcontent' => $INI['system']['sitename'] . '(' .$INI['system']['wwwprefix']. ')',
				);
	}
	$query = http_build_query($query);
	return 'http://www.kaixin001.com/repaste/share.php?'.$query;
}

function share_douban($team) {
	global $login_user_id;
	global $INI;
	if ($team)  {
		$query = array(
				'url' => $INI['system']['wwwprefix'] . "/team.php?id={$team['id']}&r={$login_user_id}",
				'title' => $team['title'],
				);
	}
	else {
		$query = array(
				'url' => $INI['system']['wwwprefix'] . "/r.php?r={$login_user_id}",
				'title' => $INI['system']['sitename'] . '(' .$INI['system']['wwwprefix']. ')',
				);
	}
	$query = http_build_query($query);
	return 'http://www.douban.com/recommend/?'.$query;
}

function share_sina($team) {
	global $login_user_id;
	global $INI;
	if ($team)  {
		$query = array(
				'url' => $INI['system']['wwwprefix'] . "/team.php?id={$team['id']}&r={$login_user_id}",
				'title' => $team['title'],
				);
	}
	else {
		$query = array(
				'url' => $INI['system']['wwwprefix'] . "/r.php?r={$login_user_id}",
				'title' => $INI['system']['sitename'] . '(' .$INI['system']['wwwprefix']. ')',
				);
	}
	$query = http_build_query($query);
	return 'http://v.t.sina.com.cn/share/share.php?'.$query;
}

function share_mail($team) {
	global $login_user_id;
	global $INI;
	if (!$team) {
		$team = array(
				'title' => $INI['system']['sitename'] . '(' . $INI['system']['wwwprefix'] . ')',
				);
	}
	$pre[] = "发现一好网站--{$INI['system']['sitename']},他们每天组织一次团购,超值!";
	if ( $team['id'] ) {
		$pre[] = "今天的团购是:{$team['title']}";
		$pre[] = "我想你会感兴趣的:";
		$pre[] = $INI['system']['wwwprefix'] . "/team.php?id={$team['id']}&r={$login_user_id}";
		$pre = mb_convert_encoding(join("\n\n", $pre), 'GBK', 'UTF-8');
		$sub = "有兴趣吗:{$team['title']}";
	} else {
		$sub = $pre[] = $team['title'];
	}
	$sub = mb_convert_encoding($sub, 'GBK', 'UTF-8');
	$query = array( 'subject' => $sub, 'body' => $pre, );
	$query = http_build_query($query);
	return 'mailto:?'.$query;
}

function domainit($url) {
	if(strpos($url,'//')) { preg_match('#[//]([^/]+)#', $url, $m);
} else { preg_match('#[//]?([^/]+)#', $url, $m); }
return $m[1];
}

// that the recursive feature on mkdir() is broken with PHP 5.0.4 for
function RecursiveMkdir($path) {
	if (!file_exists($path)) {
		RecursiveMkdir(dirname($path));
		@mkdir($path, 0777);
	}
}

function upload_image($input, $image=null, $type='team', $scale=false) {
	$year = date('Y'); $day = date('md'); 
	$n = time().rand(1000,9999).'.jpg';
	$z = $_FILES[$input];
	$filename = $z["tmp_name"];
    $image_size = getimagesize($filename);
	if ($z && strpos($z['type'], 'image')===0 && $z['error']==0) {
		if (!$image) { 
			RecursiveMkdir( IMG_ROOT . '/' . "{$type}/{$year}/{$day}" );
			$image = "{$type}/{$year}/{$day}/{$n}";
			$path = IMG_ROOT . '/' . $image;
		} else {
			RecursiveMkdir( dirname(IMG_ROOT .'/' .$image) );
			$path = IMG_ROOT . '/' .$image;
		}
		if ($type=='user') {
			Image::Convert($z['tmp_name'], $path, 48, 48, Image::MODE_CUT);
		} 
		else if($type=='team') {
			move_uploaded_file($z['tmp_name'], $path);
			mark_image($image_size, $path, IMG_ROOT .'/logo.png');
		}
		if($type=='team' && $scale) {
			$npath = preg_replace('#(\d+)\.(\w+)$#', "\\1_index.\\2", $path); 
			Image::Convert($path, $npath, 190, 120, Image::MODE_CUT);
		}
		return $image;
	} 
	return $image;
}

function mark_image($image_size, $path, $markimgpath) {
	$iinfo = getimagesize($path,$iinfo);
	$nimage = imagecreatetruecolor($image_size[0], $image_size[1]);
	$white=imagecolorallocate($nimage,255,255,255);
	$black = imagecolorallocate($nimage,0,0,0);
	$red=imagecolorallocate($nimage,255,0,0);
	imagefill($nimage,0,0,$white);
	switch ($iinfo[2])
	{ 
		case 1:
		$simage = imagecreatefromgif($path);
		break;

		case 2:
		$simage = imagecreatefromjpeg($path);
		break;

		case 3:
		$simage = imagecreatefrompng($path);
		break;

		case 6:
		$simage = imagecreatefromwbmp($path);
		break;

		default:
		die("不支持的文件类型");
		exit;
	 }
	 
	 imagecopy($nimage,$simage,0,0,0,0,$image_size[0],$image_size[1]);
	$simage1 = imagecreatefrompng($markimgpath);
	imagecopy($nimage,$simage1,40,40,0,0,263,58);
	imagedestroy($simage1);
	switch ($iinfo[2])
	{ 
		case 1:
		//imagegif($nimage, $destination);
		imagejpeg($nimage, $path);
		break;

		case 2:
		imagejpeg($nimage, $path);
		break;

		case 3:
		imagepng($nimage, $path);
		break;

		case 6:
		imagewbmp($nimage, $path);
		//imagejpeg($nimage, $destination);
		break;
	 }
	imagedestroy($nimage);
	imagedestroy($simage);
}


function user_image($image=null) {
	global $INI;
	if (!$image) { 
		return $INI['system']['imgprefix'] . '/static/img/user-no-avatar.gif';
	}
	return $INI['system']['imgprefix'] . '/static/' .$image;
}

function team_image($image=null, $index=false) {
	global $INI;
	if (!$image) return null;
	if ($index) {
		$path = WWW_ROOT . '/static/' . $image;
		$image = preg_replace('#(\d+)\.(\w+)$#', "\\1_index.\\2", $image); 
		$dest = WWW_ROOT . '/static/' . $image;
		if (!file_exists($dest) && file_exists($path) ) {
			Image::Convert($path, $dest, 200, 120, Image::MODE_SCALE);
		}
	}
	return $INI['system']['imgprefix'] . '/static/' .$image;
}

function userreview($content) {
	$line = preg_split("/[\n\r]+/", $content, -1, PREG_SPLIT_NO_EMPTY);
	$r = '';
}

function invite_state($invite) {
	if ('Y' == $invite['pay']) return '已返利';
	if ('C' == $invite['pay']) return '审核未通过';
	if ('N' == $invite['pay'] && $invite['buy_time']) return '待返利';
	if (time()-$invite['create_time']>7*86400) return '已过期';
	return '未购买';
}

function team_state(&$team) {
	if ( $team['now_number'] >= $team['min_number'] ) {
		if ($team['max_number']>0) {
			if ( $team['now_number']>=$team['max_number'] ){
				if ($team['close_time']==0) {
					$team['close_time'] = $team['end_time'];
				}
				return $team['state'] = 'soldout';
			}
		}
		if ( $team['end_time'] <= time() ) {
			$team['close_time'] = $team['end_time'];
		}
		return $team['state'] = 'success';
	} else {
		if ( $team['end_time'] <= time() ) {
			$team['close_time'] = $team['end_time'];
			return $team['state'] = 'failure';
		}
	}
	return $team['state'] = 'none';
}

function current_team($city_id=0) {
	$today = strtotime(date('Y-m-d'));
	$cond = array(
			'city_id' => array(0, abs(intval($city_id))),
			'team_type' => 'normal',
			"begin_time <= {$today}",
			"end_time > {$today}",
			"audit" => 1, //所有已审核的团购
			);
	$order = 'ORDER BY city_id DESC,sort_order DESC,begin_time DESC,id DESC';

	/* normal team */
	$team = DB::LimitQuery('team', array(
				'condition' => $cond,
				'one' => true,
				'order' => $order,
				));
	if ($team) return $team;

	/* seconds team */
	$cond['team_type'] = 'seconds';
	unset($cond['begin_time']);	
	$order = 'ORDER BY city_id DESC,begin_time ASC,sort_order DESC,id DESC';
	$team = DB::LimitQuery('team', array(
				'condition' => $cond,
				'one' => true,
				'order' => $order,
				));

	return $team;
}

function current_teams($city_id=0) {
	$today = strtotime(date('Y-m-d'));
	$cond = array(
			'city_id' => array(0, abs(intval($city_id))),
			'team_type' => 'normal',
			"begin_time <= {$today}",
			"end_time > {$today}",
			"audit" => 1, //所有已审核的团购
			);
	$order = 'ORDER BY city_id DESC,sort_order DESC,begin_time DESC,id DESC';

	/* normal team */
	$teams = DB::LimitQuery('team', array(
				'condition' => $cond,
				'order' => $order,
				));
	if ($teams) return $teams;

	/* seconds team */
	$cond['team_type'] = 'seconds';
	unset($cond['begin_time']);	
	$order = 'ORDER BY city_id DESC,begin_time ASC,sort_order DESC,id DESC';
	$teams = DB::LimitQuery('team', array(
				'condition' => $cond,
				'order' => $order,
				));

	return $teams;
}

function state_explain($team, $error='false') {
	$state = team_state($team);
	$state = strtolower($state);
	switch($state) {
		case 'none': return '正在进行中';
		case 'soldout': return '已售光';
		case 'failure': if($error) return '团购失败';
		case 'success': return '团购成功';
		default: return '已结束';
	}
}

function get_zones($zone=null) {
	$zones = array(
			'city' => '城市列表',
			'group' => '项目分类',
			'public' => '讨论区分类',
			'grade' => '用户等级',
			'express' => '快递公司',
			'partner' => '商户分类',
			);
	if ( !$zone ) return $zones;
	if (!in_array($zone, array_keys($zones))) {
		$zone = 'city';
	}
	return array($zone, $zones[$zone]);
}

function down_xls($data, $keynames, $name='dataxls') {
	$xls[] = "";
	$xls[] = "';
	foreach($data As $o) {
		$line = array(++$index);
		foreach($keynames AS $k=>$v) {
			$line[] = $o[$k];
		}
		$xls[] = '';
	}
	$xls[] = '
ID" . implode("", array_values($keynames)) . '
'. implode("", $line) . '
'; $xls = join("\r\n", $xls); header('Content-Disposition: attachment; filename="'.$name.'.xls"'); die(mb_convert_encoding($xls,'UTF-8','UTF-8')); } function option_category($zone='city', $force=false, $all=false) { $cache = $force ? 0 : 86400*30; $cates = DB::LimitQuery('category', array( 'condition' => array( 'zone' => $zone, ), 'order' => 'ORDER BY sort_order DESC, id DESC', 'cache' => $cache, )); return $all ? $cates : Utility::OptionArray($cates, 'id', 'name'); } function option_yes($n, $default=false) { global $INI; if (false==isset($INI['option'][$n])) return $default; $flag = trim(strval($INI['option'][$n])); return abs(intval($flag)) || strtoupper($flag) == 'Y'; } function option_yesv($n, $default='N') { return option_yes($n, $default=='Y') ? 'Y' : 'N'; } function magic_gpc($string) { if(SYS_MAGICGPC) { if(is_array($string)) { foreach($string as $key => $val) { $string[$key] = magic_gpc($val); } } else { $string = stripslashes($string); } } return $string; } function team_discount($team, $save=false) { if ($team['market_price']<0 || $team['team_price']<0 ) { return '?'; } return moneyit((10*$team['team_price']/$team['market_price'])); } function error_handler($errno, $errstr, $errfile, $errline) { switch ($errno) { case E_PARSE: case E_ERROR: echo "Fatal ERROR [$errno] $errstr
\n"; echo "Fatal error on line $errline in file $errfile"; echo "PHP " . PHP_VERSION . " (" . PHP_OS . ")
\n"; exit(1); break; default: break; } return true; } set_error_handler('error_handler');