<?php
/**
 * functions.php
 * 本文件定义了网站及手机端接口的一些函数。
 */

require_once("database.php");
require_once("config.php");
require_once("EmayClient.class.php");
require_once ('printFunctions.php');

function welcome_guest() {
	if(isset($_REQUEST['changecity'])){
		$cityid = addslashes(trim($_REQUEST['changecity']));
		$db = db_connect();
		$sql = "SELECT `Name`, `Latitude`, `Longitude`, `ZoomLevel` FROM `City` WHERE `ID`='{$cityid}' AND `Hide`=0; ";
		$rs = $db->query($sql);
		if($row = $rs->fetch_assoc()) {
			$_SESSION['session_city'] = $row['Name'];
			$_SESSION['session_latitude'] = $row['Latitude'];
			$_SESSION['session_longitude'] = $row['Longitude'];
			$_SESSION['session_zoomLevel'] = $row['ZoomLevel'];
			$_SESSION['session_cityid'] = $cityid;
		}
		
		if( isset($_COOKIE['guestid']) ) {
			set_guest_city();
		}
		
		if( isset($_SESSION['session_customid']) ) {
			set_custom_city();
		}
		
		set_success_notification('设置城市成功！当前城市为'.$_SESSION['session_city'].'。');
		
		$db->close();
	}
	
	elseif ( ! isset($_SESSION['session_city']) ){
		
		//注意：如果客人已经登录，则$_SESSION['session_city']应该是已经被设置了的。
		
		if( isset($_COOKIE['guestid']) ) {
			$db = db_connect();
			$sql = "SELECT `City`.`ID`, `City`.`Name`, `City`.`Latitude`, `City`.`Longitude` ,`City`.`ZoomLevel`, " .
					"`Guest`.`CityHint`, `Guest`.`WelcomeHint` , `Guest`.`MapHint` , `Guest`.`CustomID` , `Guest`.`IsLogined` " .
					" FROM `City`, `Guest` " .
					" WHERE `Guest`.`GuestID`='{$_COOKIE['guestid']}' AND `Guest`.`LastCityID`=`City`.`ID` AND `City`.`Hide`=0; ";
			$rs = $db->query($sql);
			if($row = $rs->fetch_assoc()) {
				$_SESSION['session_city'] = $row['Name'];
				$_SESSION['session_latitude'] = $row['Latitude'];
				$_SESSION['session_longitude'] = $row['Longitude'];
				$_SESSION['session_zoomLevel'] = $row['ZoomLevel'];
				$_SESSION['session_cityid'] = $row['ID'];
				$_SESSION['session_cityhint'] = $row['CityHint'];
				$_SESSION['session_welcomehint'] = $row['WelcomeHint'];
				$_SESSION['session_maphint'] = $row['MapHint'];
				set_guest_city();
				
				if(!empty($row['CustomID']) && !empty($row['IsLogined'])) {
					$sql = "SELECT `ID`, `Email`, `Mobile`, `Username`, `CityHint`, `WelcomeHint`, " .
							"`MapHint`, `LastCityID`,`LastCity`, `EmailVerified`, `MobileVerified`, `MobileVerifying` " .
							"FROM `Custom` WHERE `ID`='{$row['CustomID']}'; ";
					$rs = $db->query($sql);
					if( $row = $rs->fetch_assoc() ) {
						$_SESSION['session_customid'] = $row['ID'];
						$_SESSION['session_customEmail'] = $row['Email'];
						$_SESSION['session_customMobile'] = $row['Mobile'];
						$_SESSION['session_customUsername'] = $row['Username'];
						$_SESSION['session_customEmailVerified'] = $row['EmailVerified'];
						$_SESSION['session_customMobileVerified'] = $row['MobileVerified'];
						$_SESSION['session_customMobileVerifying'] = $row['MobileVerifying'];
						$_SESSION['session_cityhint'] = $row['CityHint'];
						$_SESSION['session_welcomehint'] = $row['WelcomeHint'];
						$_SESSION['session_maphint'] = $row['MapHint'];
						$cityid = $row['LastCityID'];
					
						$sql = "SELECT `Name`, `Latitude`, `Longitude`, `ZoomLevel` FROM `City` WHERE `ID`='{$cityid}' AND `Hide`=0; ";
						$rs = $db->query($sql);
						if( $row = $rs->fetch_assoc() ) {
							$_SESSION['session_city'] = $row['Name'];
							$_SESSION['session_latitude'] = $row['Latitude'];
							$_SESSION['session_longitude'] = $row['Longitude'];
							$_SESSION['session_zoomLevel'] = $row['ZoomLevel'];
							$_SESSION['session_cityid'] = $cityid;
						}
						$_SESSION['session_rememberlogin'] = 1;
						
						process_long_time();
						
						//进一步看看客户是否有活动订单。
						$sql = "SELECT `ID`,UNIX_TIMESTAMP(`CreateTime`) AS CreateTime,`Status` FROM `Order` " .
								"WHERE `CustomID`='{$_SESSION['session_customid']}' " .
								"AND (`Status`<>'已取消' AND `Status`<>'成功结束') " .
								"ORDER BY `ID` ASC; ";
						$rs = $db->query($sql);
						while( $row = $rs->fetch_assoc() ) { //有活动订单
							$_SESSION['session_hasActiveOrder'] = 1;
							$_SESSION['session_lastOrderStartAt'] = $row['CreateTime'];;
							$_SESSION['session_Order'.$row['ID'].'StartAt'] = $row['CreateTime'];
							$_SESSION['session_Order'.$row['ID'].'Status'] = $row['Status'];
							$_SESSION['session_hasFailedOrder'] = ($row['Status']=='自动删除') ? 1 : 0;
						}
						custom_log('登录', '成功。');
					}
					
				}
			}
			$db->close();
		}
		else { //该访客首次访问。
			$db = db_connect();
			$sql = "SELECT `ID`, `Name`, `Latitude`, `Longitude`, `ZoomLevel` FROM `City` WHERE `Hide`=0 " .
					" ORDER BY `Sequence` ASC LIMIT 1 "; //选择第一个记录
			$rs = $db->query($sql);
			if($row = $rs->fetch_assoc()) {
				//添加当前访客的信息
				add_guest();
				$_SESSION['session_city'] = $row['Name'];
				$_SESSION['session_cityid'] = $row['ID'];
				$_SESSION['session_latitude'] = $row['Latitude'];
				$_SESSION['session_longitude'] = $row['Longitude'];
				$_SESSION['session_zoomLevel'] = $row['ZoomLevel'];
				
				
			}
			$db->close();
		}
	}
}

/**
 * 添加一个guest
 */
function add_guest() {
	$guestid = uuid();
	setcookie("guestid", $guestid, time()+60*60*24*180);
	
	$db = db_connect();
	$sql = "INSERT INTO `Guest`(`GuestID`,`LastCityID`,`LastCity`,`LastIp`,`LastTime`) " .
			"VALUES('{$guestid}','{$_SESSION['session_cityid']}','{$_SESSION['session_city']}'," .
			"'".get_client_ip()."','".get_datetime()."')";
	$db->query($sql);
	$db->close();
	
	
	$_SESSION['session_cityhint'] = '1';
	$_SESSION['session_welcomehint'] = '1';
	$_SESSION['session_maphint'] = '1';
}

/**
 * 将当前访客的城市设置保存在数据库里
 * 兼职（不太好的一个东西，应该另写函数专门实现）：记录访客的IP和上次访问时间
 */
function set_guest_city() {
	if( isset($_COOKIE['guestid']) && isset($_SESSION['session_cityid']) ) {
		$db = db_connect();
		$sql = "UPDATE `Guest` SET `LastCityID`='{$_SESSION['session_cityid']}', `LastCity`='{$_SESSION['session_city']}', `LastIp`='".get_client_ip()."', " .
				"`LastTime`='".get_datetime()."' WHERE `GuestID`='{$_COOKIE['guestid']}'; ";
		$db->query($sql);
		$db->close();
	}
}

/**
 * 将当前顾客的城市设置保存在数据库里
 * 兼职（不太好的一个东西，应该另写函数专门实现）：记录顾客的IP和上次访问时间
 */
function set_custom_city() {
	if( isset($_SESSION['session_customid'] ) && isset($_SESSION['session_cityid']) ) {
		$db = db_connect();
		$sql = "UPDATE `Custom` SET `LastCityID`='{$_SESSION['session_cityid']}', `LastCity`='{$_SESSION['session_city']}', `LastIp`='".get_client_ip()."', " .
				"`LastTime`='".get_datetime()."' WHERE `ID`='{$_SESSION['session_customid']}'; ";
		$db->query($sql);
		$db->close();
	}
}

/**
 * 获取当前的餐馆总数和外卖美食总数（用于主页的WelcomeHint显示
 * @return array 形式如下：array("restaurantTotal"=>123, "dishTotal"=>456)
 */
function get_total_count() {
	$total = array();
	$db = db_connect();
	$sql = "SELECT COUNT(`ID`) FROM `Restaurant` WHERE `Hide`=0;";
	$rs = $db->query($sql);
	if( $row = $rs->fetch_row() ){
		$total["restaurantTotal"] = $row[0];
	}
	$sql = "SELECT COUNT(`Dish`.`ID`) " .
			"FROM `Dish`,`Restaurant`,`Section` " .
			"WHERE `Dish`.`SectionID`=`Section`.`ID` " .
			" AND `Dish`.`RestaurantID`=`Section`.`RestaurantID` " .
			" AND `Dish`.`Hide`=0 AND `Section`.`Hide`=0 AND `Restaurant`.`Hide`=0 " .
			" AND `Restaurant`.`ID`=`Dish`.`RestaurantID` " .
			""; //TODO 
	$rs = $db->query($sql);
	if( $row = $rs->fetch_row() ){
		$total["dishTotal"] = $row[0];
	}
	$db->close();
	return $total;
}

/**
 * 关闭欢迎提示
 */
function close_welcome_hint() {
	$db = db_connect();
	if ( isset($_SESSION['session_customid']) ) {
		$sql = "UPDATE `Custom` SET `WelcomeHint`=0 WHERE `ID`='{$_SESSION['session_customid']}';";
		$db->query($sql);
	}
	if ( isset($_COOKIE['guestid']) ) {
		$sql = "UPDATE `Guest` SET `WelcomeHint`=0 WHERE `GuestID`='{$_COOKIE['guestid']}';";
		$db->query($sql);
	}
	
	$_SESSION['session_welcomehint'] = 0;
	
	$db->close();
}

/**
 * 关闭城市选择提示
 */
function close_city_hint() {
	$db = db_connect();
	if ( isset($_SESSION['session_customid']) ) {
		$sql = "UPDATE `Custom` SET `CityHint`=0 WHERE `ID`='{$_SESSION['session_customid']}';";
		$db->query($sql);
	}
	if ( isset($_COOKIE['guestid']) ) {
		$sql = "UPDATE `Guest` SET `CityHint`=0 WHERE `GuestID`='{$_COOKIE['guestid']}';";
		$db->query($sql);
	}
	
	$_SESSION['session_cityhint'] = 0;
	
	$db->close();
}

/**
 * 关闭城市选择提示
 */
function close_map_hint() {
	$db = db_connect();
	if ( isset($_SESSION['session_customid']) ) {
		$sql = "UPDATE `Custom` SET `MapHint`=0 WHERE `ID`='{$_SESSION['session_customid']}';";
		$db->query($sql);
	}
	if ( isset($_COOKIE['guestid']) ) {
		$sql = "UPDATE `Guest` SET `MapHint`=0 WHERE `GuestID`='{$_COOKIE['guestid']}';";
		$db->query($sql);
	}
	
	$_SESSION['session_maphint'] = 0;
	
	$db->close();
}
function last_notification() {
	$re = '';
	if(isset($_SESSION['session_last_notification'])) {
		$re = '<div class="flash_notification '.$_SESSION['session_last_notification_status'].'">'.$_SESSION['session_last_notification'].'</div>';
		$_SESSION['session_last_notification'] = null;
	}
	return $re;
}
function getSectionByRid ($rid){
	$sql="select * from section where `Hide`=0 and RestaurantID=".$rid;
	$db=dao();
	$secionsArray=array();
	$result=$db->query($sql);
	while($row=$result->fetch_assoc()){
		$sql="select * from dish where `Hide`=0 and  SectionID=".$row['ID'];
		$re=$db->query($sql);
		$secion=$row;
		while($r=$re->fetch_assoc()){
			$secion['dishes'][]=$r;
		}
		$secionsArray[]=$secion;
		
	}
	$db->close();
	return $secionsArray;
}
/**
 * 获取客户定制的餐馆列表（左边）
 */
function get_faver_restaurants() {
	$faver_counts = all_city_faver_count();
	
	$city = (substr($_SESSION['session_city'], -3, 3)=="市" ? $_SESSION['session_city'] : $_SESSION['session_city'] . "市");
	echo '<div id="toc_outer"><ul id="toc">' . "\n";
	//标题：在天津市您定制的餐厅 (从外卖地图定制)在北京您定制了7家餐厅   在广州您定制了1家餐厅  
	echo '<li id="toc_title_outer">' . "\n";
	echo '<h2 class="toc_title">' . "\n";
	echo '在'.$city.'您定制的餐厅' . "\n";
	echo '<span>(<a href="map.php" title="去外卖地图查看">从外卖地图定制</a>)</span>' . "\n";
	foreach ($faver_counts as $cityname => $faver_count) {
		if( ($faver_count[0]+0) > 0 && $faver_count[2]!=$_SESSION['session_cityid']) {
			echo '&nbsp;&nbsp;<span>在<a href="index.php?changecity='.$faver_count[2].'">'.$faver_count[1].'</a>您定制了'.$faver_count[0].'家餐厅</span>' . "\n";
		}
	}
	echo '</h2>' . "\n";
	echo '</li>' . "\n";
	
	$restaurants = get_current_city_faver_restaurants_list();
	//dump($restaurants);
	//定制的餐厅及其餐品分类列表
	foreach($restaurants as $restaurant) {
		echo '<li class="restaurant restaurant'.$restaurant['ID'].' rate'.$restaurant['Rating'].' no_discount" id="toc_restaurant_'.$restaurant['ID'].'">' . "\n";
		echo '<div class="restaurant_name">' . "\n";
		echo '<a rel="nofollow" class="jump_to_restaurant" title="'.$restaurant['Name'].'的外卖菜单" href="#restaurant'.$restaurant['ID'].'">'.$restaurant['Name'].'</a>' . "\n";
		echo '<a rel="nofollow" title="从首页删除" class="remove_restaurant" href="favrestaurants_remove.php?id='.$restaurant['ID'].'"><img alt="" src="images/toc_delete.gif"></a>' . "\n";
	//	echo '<a rel="" href="orders_table.php?rid='.$restaurant['ID'].'">预定座位</a>';
		echo '</div>' . "\n";
		
		echo '<div>' . "\n";
		//echo '<a  style = "display:none" >'.$restaurant['Memo'].'</a>';
		echo '</div>' . "\n";
		echo '<ul class="sections">' . "\n";
		//$sections = $restaurant['sections'];
		$sections =getSectionByRid($restaurant['ID']);
		foreach($sections as $section) {
			echo '<li>' . "\n";
			echo '<a href="#section'.$section['ID'].'" title="'.$restaurant['Name'].'的外卖菜单：'.$section['Name'].'">'.$section['Name'].'</a>' . "\n";
			echo '</li>' . "\n";
		}
		echo '</ul>' . "\n";
	}
	
	echo '<li style="display:none" class="empty_toc">(空)</li>' . "\n";
	echo '<li style="display:none" id="search_empty_toc">(本页内没有搜索到符合的结果。)</li>' . "\n";
	echo '</ul></div>' . "\n";
	
	//定制的餐厅及//其餐品列表
	echo '<ul class="restaurant_list" id="restaurant_list">' . "\n";
	foreach($restaurants as $restaurant) {
		//dump($restaurant['sections']);
		$isBusiness=isBusiness($restaurant['ID']);
		$img='';
		if(!$isBusiness){
			$img='<div class="tel"><img src="images/restaurant_not_in_opening_time_icon.gif"/></div>'. "\n";;
		}
		echo '<li id="restaurant'.$restaurant['ID'].'" ' .
				'class="restaurant restaurant'.$restaurant['ID'].' rate'.$restaurant['Rating'].' '.(empty($restaurant['NOService']) ? '' : 'no_service ' ).'no_discount" ' .
				'itemtype="http://schema.org/Restaurant" itemscope="" data-deny_order="false" ' . //此处固定了餐馆不接受订单为false
				'data-rev="'.$restaurant['ID'].'" data-tel="'.$restaurant['Telephone'].'' .
				'" data-takeout="'.$restaurant['Takeout'].'" ' .'" data-memo="'.$restaurant['Memo'].
				'" data-staple="'.$restaurant['Staple'].'" ' .
				'" data-name="'.$restaurant['Name'].'" data-id="'.$restaurant['ID'].'">' . "\n";
		echo '<div class="meta rate'.$restaurant['Rating'].' '.(empty($restaurant['NOService']) ? '' : 'no_service ' ).'no_discount">' . "\n";
		echo '<meta content="restaurant.php?id='.$restaurant['ID'].'" itemprop="menu">' . "\n";
		echo '<meta content="map.php?restaurantid='.$restaurant['ID'].'" itemprop="maps">' . "\n";
		echo '<meta content="'.$restaurant['Telephone'].'" itemprop="telephone">' . "\n";
		echo '<a class="bm" name="restaurant'.$restaurant['ID'].'">&nbsp;</a>' . "\n";
		echo '<h1 class="name">' . "\n";
		echo '<a class="value" title="'.$restaurant['Name'].'的外卖菜单" href="restaurant.php?uuid='.$restaurant['UUID'].'" itemprop="name">'.$restaurant['Name'].'</a>' . "\n";
		echo '</h1>' . "\n";
		echo '<div class="tel">'.$restaurant['Telephone'].'</div>' . "\n";
		echo $img;//显示是不是休息
		echo '<div class="actions">' . "\n";
		echo '<a id="add_id_'.$restaurant['ID'].'" class="btn fav-add" href="favrestaurants_add.php?id='.$restaurant['ID'].'" rel="nofollow">加到首页</a>' . "\n";
		echo '<a id="rm_id_'.$restaurant['ID'].'" class="btn delete fav-remove" href="favrestaurants_remove.php?id='.$restaurant['ID'].'" rel="nofollow">移出首页</a>' . "\n";
		echo '<span class="timestamp">'.get_last_update_text($restaurant['LastUpdate']).'前更新</span>' . "\n";
		echo '</div>' . "\n";//actions
		echo '</div>' . "\n";//meta
		echo '<div class="restaurant_rate rate2 no_discount">' . "\n";
		echo '<span class="icon" itemtype="http://schema.org/AggregateRating" itemscope="" itemprop="aggregateRating">' .
				'<meta content="'.$restaurant['Rating'].'" itemprop="ratingValue">' .
				'<meta content="3" itemprop="bestRating">' .
				'<meta content="1" itemprop="worstRating">' .
				'<meta content="1" itemprop="ratingCount">' .
			 '</span>' . "\n";
		echo '<span class="words">'.$restaurant['BusinessMemo'].' / 起送金额'.$restaurant['MinMoney'].'元 ' .
				($restaurant['Takeout'] ? '' : ' / 该餐厅不支持送餐上门') .
				'</span>' . "\n";
		echo '</div>' . "\n"; //restaurant_rate
		echo '<ul class="dishes">' . "\n";
		
		//$sections = $restaurant['sections'];
		//dump($restaurant);
		//
		$sections =getSectionByRid($restaurant['ID']);
		
		
		
		
		
		//
		foreach($sections as  $section) {
			echo '<li class="dish dish'.$section['ID'].' is-section">' . "\n";
			echo '<a class="bm" name="section'.$section['ID'].'">&nbsp;</a>' . "\n";
			echo '<span class="name">'.$section['Name'].'</span>' . "\n";
			echo '<a class="back_top" href="#top">TOP</a>' . "\n";
			echo '</li>' . "\n";
			
			$dishes = $section['dishes'];
			if(!empty($dishes)){
			foreach($dishes as $k=>$dish) {
				if($dish['DenyOrder']==1){
					continue;
				}
					$imgInfo=getDishImgByDishId($dish['ID']);
					$path=empty($imgInfo['imgPath'])?'dishimg/nopic.gif':$imgInfo['imgPath'];
					$width=empty($imgInfo['width'])?150:$imgInfo['width'];
					$height=empty($imgInfo['height'])?177:$imgInfo['width'];
				echo '<li id="dish'.$dish['ID'].'" ' .
						'class="dish dish'.$dish['ID'].'" ' .
						'data-name="'.$dish['Name'].''.$dish['Annotation'].'" ' .
						'data-id="'.$dish['ID'].'" ' .
						'data-price="'.$dish['Price'].'" dishimg="'.$path.'" wi="'.$width.'" hi="'.$height.'">' . "\n";
				echo '<span class="name">'.$dish['Name'].' <span class="annotation">'.$dish['Annotation'].'</span></span>' . "\n";
				echo '<span class="price_outer">' . "\n";
				echo '<span class="price">'.$dish['Price'].'</span>' . "\n";
				echo '</span>' . "\n";
				echo '<a class="cart_count"></a>' . "\n";
				echo '</li>' . "\n";
			}
		}
		}
		echo '</ul>' . "\n"; //dishes
		echo '</li>' . "\n";
	}
	echo '</ul>' . "\n";
}

/**
 * 查询当前城市的定制餐厅及餐厅内的菜式列表，供get_faver_restaurants()使用，返回一个数组，数组形式如下：
 * array(
 * 	"[餐馆id_1]" => array(
 * 		"ID" => "[餐馆id_1]",
 * 		"UUID" => "[餐馆uuid]",
 * 		"Name" => "[餐馆名称]",
 * 		"Rating" => "[餐馆评级]",
 * 		"Takeout" => "[餐馆是否支持送餐上门]",
 * 		"LastUpdate" => "LastUpdate",
 * 		"sections" => array(array("ID"=>"[sectionId]", "Name"=>"sectionName"), ...)
 * 		"dishes" => array(array("", "")... )
 * 	),
 * 	...
 * 	"[餐馆id_n]" => array(
 * 		...
 * 	)
 * )
 */
function get_current_city_faver_restaurants_list() {
	$re = array();
	$db = db_connect();
	
	$sql = "SELECT DISTINCT `Restaurant`.`ID`, `Restaurant`.`UUID`, `Restaurant`.`Name`, `Restaurant`.`Rating`, " .
			"`Restaurant`.`Takeout` ,  `Restaurant`.`LastUpdate`, `Restaurant`.`Staple`," .
			"`Restaurant`.`Telephone`,  `Restaurant`.`BusinessMemo`, `Restaurant`.`MinMoney`, " .
			"`Dish`.`ID` AS `DishID`, `Dish`.`Name` AS `DishName`, `Dish`.`SectionID`, `Dish`.`Section`, " .
			"`Dish`.`Annotation`, `Dish`.`Price`, `Dish`.`DiscountPrice`, `Dish`.`DenyOrder` " .
			"FROM `Restaurant`, `Dish`, `Section`, `FavRestaurant` " .
			"WHERE " .
			( isset($_SESSION['session_customid']) ? 
				"`FavRestaurant`.`CustomID`='{$_SESSION['session_customid']}'" 
				: "`FavRestaurant`.`GuestID`='{$_COOKIE['guestid']}'" ) . 
			" AND `Dish`.`SectionID`=`Section`.`ID` " .
			" AND `Dish`.`RestaurantID`=`Section`.`RestaurantID` " .
			" AND `Dish`.`Hide`=0 AND `Section`.`Hide`=0 AND `Restaurant`.`Hide`=0 " .
			" AND `FavRestaurant`.`RestaurantID`=`Restaurant`.`ID` " .
			" AND `Restaurant`.`CityId`='{$_SESSION['session_cityid']}' " .
			" AND `Restaurant`.`ID`=`Dish`.`RestaurantID` " .
			"ORDER BY `Restaurant`.`ID`, `Section`.`Sequence` ASC, `Dish`.`Sequence` ASC ";
	$rs = $db->query($sql);
	
	$cur_restaurant_added = true;
	$cur_restaurant_id = null;
	$cur_restaurant = array();
	$cur_section_added = true;
	$cur_section_id = null;
	$cur_section = null;
	$sections = null;
	$dishes = null;
	
	while ( $row = $rs->fetch_assoc() ) {
		if( $cur_restaurant_id != $row['ID'] ) {
			if( $cur_restaurant_id != null ) { //添加当前餐馆到结果中
				$cur_restaurant["sections"] = $sections;
				$re[$cur_restaurant_id] = $cur_restaurant;
				$cur_restaurant_added = true;
			}
			
			$cur_restaurant_id = $row['ID'];
			$cur_restaurant = array();
			$cur_restaurant["ID"] = $row['ID'];
			$cur_restaurant["UUID"] = $row['UUID'];
			$cur_restaurant["Name"] = $row['Name'];
			$cur_restaurant["Rating"] = $row['Rating'];
			$cur_restaurant["Takeout"] = $row['Takeout'];
			$cur_restaurant["Staple"] = $row['Staple'];
			$cur_restaurant["LastUpdate"] = $row['LastUpdate'];
			$cur_restaurant["Telephone"] = $row['Telephone'];
			$cur_restaurant["BusinessMemo"] = $row['BusinessMemo'];
			$cur_restaurant["MinMoney"] = $row['MinMoney'];
			
			$cur_restaurant_added = false;
			$cur_section_id = null;
			$sections = array();
		}
//		echo $row['SectionID'].'<br>';
		if( $cur_section_id != $row['SectionID'] ) {
			if( $cur_section_id != null ) {
				$cur_section["dishes"] = $dishes;
				array_push($sections, $cur_section);
				//dump($cur_section);
				$cur_section_added = true;
			}
			$cur_section_id = $row['SectionID'];
			$cur_section = array(
				"ID" => $row['SectionID'],
				"Name" => $row['Section']
			);
		
			$dishes = array();
			$cur_section_added = false;
		}
		$cur_dish = array(
			"ID" => $row['DishID'],
			"Name" => $row['DishName'],
			"Annotation" => $row['Annotation'],
			"Price" => $row['Price'] + 0,
			"DiscountPrice" => $row['DiscountPrice'],
			"DenyOrder" => $row['DenyOrder']
		);
		array_push($dishes, $cur_dish);
	}
	
	if( ! $cur_section_added ) {
		$cur_section["dishes"] = $dishes;
		array_push($sections, $cur_section);
	}
	
	
	if( ! $cur_restaurant_added ) {
		$cur_restaurant["sections"] = $sections;
		$re[$cur_restaurant_id] = $cur_restaurant;
		
	}

	if( $rs->num_rows == 0 ) {
		$re = get_current_city_default_restaurants();
	}
	
	$db->close();
	
	return $re;
}

function  get_current_city_faver_restaurants_list1()
{
	$ris = array();
	$db = db_connect();
	
	$sql = "selec ";
}

/**
 * 取当前城市的默认餐馆列表，返回格式同get_current_city_faver_restaurants_list
 */
function get_current_city_default_restaurants() {
	$re = array();
	$db = db_connect();
	
	$sql = "SELECT DISTINCT `Restaurant`.`ID`, `Restaurant`.`UUID`, `Restaurant`.`Name`, `Restaurant`.`Rating`, " .
			"`Restaurant`.`Takeout` ,  `Restaurant`.`LastUpdate`, " .
			"`Restaurant`.`Telephone`,  `Restaurant`.`BusinessMemo`, `Restaurant`.`MinMoney`, `Restaurant`.`Memo`," .
			"`Dish`.`ID` AS `DishID`, `Dish`.`Name` AS `DishName`, `Dish`.`SectionID`, `Dish`.`Section`, " .
			"`Dish`.`Annotation`, `Dish`.`Price`, `Dish`.`DiscountPrice`, `Dish`.`DenyOrder` " .
			"FROM `Restaurant`, `Dish`, `Section` " .
			"WHERE `Restaurant`.`CityDefault`=1 " .
			" AND `Restaurant`.`CityId`='{$_SESSION['session_cityid']}' " .
			" AND `Dish`.`SectionID`=`Section`.`ID` " .
			" AND `Dish`.`RestaurantID`=`Section`.`RestaurantID` " .
			" AND `Dish`.`Hide`=0 AND `Section`.`Hide`=0 AND `Restaurant`.`Hide`=0 " .
			" AND `Restaurant`.`ID`=`Dish`.`RestaurantID` " .
			"ORDER BY `Restaurant`.`ID`, `Section`.`Sequence` ASC, `Dish`.`Sequence` ASC ";
	$rs = $db->query($sql);
	
	$cur_restaurant_added = true;
	$cur_restaurant_id = null;
	$cur_restaurant = array();
	$cur_section_added = true;
	$cur_section_id = null;
	$cur_section = null;
	$sections = null;
	$dishes = null;
	while ( $row = $rs->fetch_assoc() ) {
		if( $cur_restaurant_id != $row['ID'] ) {
			if( $cur_restaurant_id != null ) { //添加当前餐馆到结果中
				$cur_restaurant["sections"] = $sections;
				$re[$cur_restaurant_id] = $cur_restaurant;
				$cur_restaurant_added = true;
			}
			
			$cur_restaurant_id = $row['ID'];
			$cur_restaurant = array();
			$cur_restaurant["ID"] = $row['ID'];
			$cur_restaurant["UUID"] = $row['UUID'];
			$cur_restaurant["Name"] = $row['Name'];
			$cur_restaurant["Rating"] = $row['Rating'];
			$cur_restaurant["Takeout"] = $row['Takeout'];
			$cur_restaurant["LastUpdate"] = $row['LastUpdate'];
			$cur_restaurant["Telephone"] = $row['Telephone'];
			$cur_restaurant["BusinessMemo"] = $row['BusinessMemo'];
			$cur_restaurant["MinMoney"] = $row['MinMoney'];
			$cur_restaurant["Memo"] = $row['Memo'];
			$cur_restaurant_added = false;
			$cur_section_id = null;
			$sections = array();
		}
		if( $cur_section_id != $row['SectionID'] ) {
			if( $cur_section_id != null ) {
				$cur_section["dishes"] = $dishes;
				array_push($sections, $cur_section);
				$cur_section_added = true;
			}
			$cur_section_id = $row['SectionID'];
			$cur_section = array(
				"ID" => $row['SectionID'],
				"Name" => $row['Section']
			);
			$dishes = array();
			$cur_section_added = false;
		}
		$cur_dish = array(
			"ID" => $row['DishID'],
			"Name" => $row['DishName'],
			"Annotation" => $row['Annotation'],
			"Price" => $row['Price'] + 0,
			"DiscountPrice" => $row['DiscountPrice'],
			"DenyOrder" => $row['DenyOrder']
		);
		array_push($dishes, $cur_dish);
	}
	
	if( ! $cur_section_added ) {
		$cur_section["dishes"] = $dishes;
		array_push($sections, $cur_section);
	}
	
	if( ! $cur_restaurant_added ) {
		$cur_restaurant["sections"] = $sections;
		$re[$cur_restaurant_id] = $cur_restaurant;
	}
	
	$db->close();
	return $re;
}

function get_last_update_text( $time_str ) {
	date_default_timezone_set('PRC');
	$t1 = strtotime($time_str);
	$t2 = strtotime("now");
	$s = $t2 - $t1;
	if($s > 60*60*24) {
		return ceil($s/60/60/24) . '天';
	}
	elseif($s > 60*60) {
		return ceil($s/60/60) . '小时';
	}
	elseif($s > 60) {
		return ceil($s/60) . '分';
	}
	else {
		return $s . '秒';
	}
}

/**
 * 获取城市的列表（<li>）
 */
function get_city_list() {
	$re = '';
	$db = db_connect();
	$sql = "SELECT `ID`, `Name` FROM `City` WHERE `Hide`=0 ORDER BY `Sequence` ASC; ";
	$rs = $db->query($sql);
	while( $row = $rs->fetch_assoc() ) {
		$uri = merge_request_uri( array( "changecity" => $row['ID'] ) );
		$re .= '<li class="city' .
				($_SESSION['session_cityid']==$row['ID'] ? ' current' : '') .
				'"> <a href="'.$uri.'">'.$row['Name'].'</a> </li>';
	}
	
	$db->close();
	return $re;
}

/**
 * 合并requests数组的内容到当前的URL中
 */
function merge_request_uri( $requests ) {
	$uri = $_SERVER['PHP_SELF'];
	if ( is_array($requests) && !empty($requests) ) {
		$_GET = array_merge($_GET, $requests);
	}
	
	if ( !empty($_GET) ) {
		$uri .= '?';
		foreach($_GET as $p => $value) {
			$uri .= $p . '=' . urlencode($value) . '&';
		}
	}
	return $uri;
}

/**
 * 地图里面的获取城市
 * @return array 一个城市数据的数组，数组每个元素是一个城市的数据（数据库查询结果的一个记录的数组）
 */
function get_cities() {
	$re = array();
	$db = db_connect();
	$sql = "SELECT `ID`, `Name`, `Latitude`, `Longitude`, `ZoomLevel` " .
			"FROM `City` WHERE `Hide`=0 ORDER BY `Sequence` ASC; ";
	$rs = $db->query($sql);
	while( $row = $rs->fetch_assoc()) {
		array_push($re, $row);
	}
	$db->close();
	return $re;
}

/**
 * 地图里的获取地区列表
 * @return array 一个关于区域的数组，数组每个元素是个城市的区域数组。
 */
function get_regions() {
	$re = array();
	$db = db_connect();
	
	$sql = "SELECT `Region`.`ID`, `Region`.`Name`, `Region`.`CityID`, `Region`.`City`, " .
			"`Region`.`Latitude`, `Region`.`Longitude`, `Region`.`ZoomLevel` " .
			"FROM `Region`, `City` " .
			"WHERE `Region`.`Hide`=0 AND `City`.`Hide`=0 " .
			"AND `Region`.`CityID`=`City`.`ID` " .
			"ORDER BY `City`.`Sequence` ASC, `Region`.`Sequence` ASC; ";
	$rs = $db->query($sql);
	
	$current_city_id = null;
	$current_city_regions = null;
	$current_city_added = true;
	while( $row = $rs->fetch_assoc() ) {
		$city_id = $row['CityID'];
		if( $city_id != $current_city_id ) { //我们遇到了一个新城市
			//先保存原来城市的数据
			if(!empty($current_city_regions)) {
				$re[$current_city_id] = $current_city_regions;
				$current_city_added = true;
			}
			
			$current_city_id = $city_id;
			$current_city_regions = array();
			$current_city_added = false;
		}
		array_push($current_city_regions, $row);
	}
	
	if( !$current_city_added ) $re[$current_city_id] = $current_city_regions;
	
	$db->close();
	return $re;
}

/**
 * 根据输入参数，在指定的范围内查找餐馆，并将结果以json形式返回
 * GET参数：
 * bounds	23.12722826610129,113.25159024684376,23.139659621819277,113.27905606715626
 * center	23.133444088,113.26532315700001
 * cityName	广州
 * q		麦当劳（用户在餐厅输入条中的输入）
 * 返回：JSON数组，如下形式：
 	[
		{
			"id":5515,
			"uuid":"640c61",
			"name":"Costa Coffee(\u65B0\u4E1C\u5B89\u5E97)",
			"rating":2,
			"added":false,
			"latLng":[39.915031684496,116.411909020081]
		}
		,{
			"id":5516,
			"uuid":"adb638",
			"name":"\u5FEB\u4E50\u67E0\u6AAC(\u65B0\u4E1C\u5B89\u5E97)",
			"rating":2,
			"added":false,
			"latLng":[39.914949394613,116.412166512146]
		}
	]
 * 
 */
function map_bounds() {
	$bounds = explode(",", $_GET['bounds']);;
	$city = $_GET['cityName'];
	$q = addslashes(trim($_GET['q']));
	
	if( count($bounds) != 4 ) return;
	$lat_min = $bounds[0];
	$lng_min = $bounds[1];
	$lat_max = $bounds[2];
	$lng_max = $bounds[3];
	
	$db = db_connect();
	$sql = "SELECT TR.`ID`, TR.`UUID`, TR.`Name`, TR.`Rating`, TR.`Latitude`, TR.`Longitude`, " .
			"TFR.`GuestID`, TFR.`CustomID` " .
			"FROM " .
			"(SELECT `ID`, `UUID`, `Name`, `Rating`, `Latitude`, `Longitude` FROM `Restaurant` " .
			"WHERE `Hide`=0 " .
			(empty($q) ? "AND `Latitude`>{$lat_min} AND `Latitude`<{$lat_max} AND `Longitude`>{$lng_min} AND `Longitude`<{$lng_max} " : "AND (`Name` LIKE '{$q}%' OR `Name` LIKE '%{$q}' OR `Name` LIKE '%{$q}%') ") .
			") AS TR " .
			" LEFT JOIN " .
			"(SELECT `GuestID`, `CustomID`, `RestaurantID` FROM `FavRestaurant` WHERE ".
			(isset($_SESSION['session_customid']) ? "`CustomID`='{$_SESSION['session_customid']}'" : "`GuestID`='{$_COOKIE['guestid']}'" ).
			") AS TFR " .
			" ON TR.`ID`=TFR.`RestaurantID`; ";
//	echo "\nSQL: " . $sql . "\n\n";
	$rs = $db->query($sql);
	$json_array = array();
	while( $row = $rs->fetch_assoc() ){
		$added = (isset($_SESSION['session_customid']) ? ($_SESSION['session_customid']==$row['CustomID']) : ($_COOKIE['guestid']==$row['GuestID']) );
		$json = '{"id":'.$row['ID'].', ' .
				'"uuid":"'.$row['UUID'].'", ' .
				'"name":"'.$row['Name'].'", ' .
				'"rating":'.$row['Rating'].', ' .
				'"added":'.( $added ? 'true' : 'false' ) .',' .
				'"latLng":['.$row['Latitude'].','.$row['Longitude'].']}';
		array_push($json_array, $json);
	}
	$db->close();
	return "[\n" . implode(",\n", $json_array) . "\n]";
}

/**
 *根据$_GET['uuid']查询数据库Restaurant表、Dish表，返回一个数组，形式如下：
 *array(
 *	'restaurant' => Restaurant表记录,
 *	'added' => true/false, 
 *	'sections' => Section表记录数组,
 *	'sectiontext' => 由Section名称用逗号隔开的一个字符串,
 *	'dishes'=>Dish表记录数组
 *)
 */
function get_restaurant() {
	$uuid = addslashes(trim($_GET['uuid']));
	$RestaurantID = 0;
	$re = array();
	$db = db_connect();
	
	$sql = "SELECT `ID`, `UUID`, `Name`, `CityId`,`City`,`RegionID`,`Region`," .
			"`Rating`, `BusinessHour`, `BusinessMemo`, `Scope`, `Latitude`, `Longitude`, " .
			"`BusinessHour`, `Fee`, `MinMoney`, `Notice`,`Telephone`,`Keyword`," .
			"`SaleAd`,`DiscountIn`,`Takeout` " .
			"FROM `Restaurant` " .
			"WHERE `UUID`='{$uuid}' AND `Hide`=0; ";
	$rs = $db->query($sql);
	if( $row = $rs->fetch_assoc() ) {
		$row['Takeout'] = empty($row['Takeout']) ? '不支持' : '支持';
		$salead = preg_replace('/#name#/', $row['Name'],  $row['SaleAd']);
		$salead = preg_replace('/#discount#/', '<span class="discount">'.($row['DiscountIn']+0).'</span>',  $salead);
		$row['SaleAd'] = $salead;
		$re['restaurant'] = $row;
		$RestaurantID = $row['ID'];
	}
	
	if ( isset($_SESSION['session_customid']) ) {
		$sql = "SELECT `ID` FROM `FavRestaurant` " .
				"WHERE `CustomID`='{$_SESSION['session_customid']}' AND `RestaurantID`='{$RestaurantID}';";
	}
	else {
		$sql = "SELECT `ID` FROM `FavRestaurant` " .
				"WHERE `GuestID`='{$_COOKIE['guestid']}' AND `RestaurantID`='{$RestaurantID}';";
	}
	$rs = $db->query($sql);
	$re['added'] =  ($rs->num_rows > 0);
	
	$sections = array();
	$sectiontext = array();
	$sql = "SELECT `Section`.`ID`, `Section`.`Name`, `Section`.`Sequence` " .
			"FROM `Section` " .
			"WHERE `RestaurantID`='{$RestaurantID}' " .
			"ORDER BY `Section`.`Sequence` ASC ";
	$rs = $db->query($sql);
	while($row = $rs->fetch_assoc()) {
		array_push($sections, $row);
		array_push($sectiontext, $row['Name']);
	}
	$re['sections'] = $sections;
	$re['sectiontext'] = implode(',' ,$sectiontext);
	
	$dishes = array();
	$sql = "SELECT `Dish`.`Name`, `Dish`.`Price`, `Dish`.`Section`, `Dish`.`Annotation`, " .
			"`Dish`.`SectionID`,`Dish`.`ID`  " .
			"FROM `Dish`,`Section` " .
			"WHERE `Dish`.`RestaurantID`='{$RestaurantID}' " .
			"AND `Dish`.`SectionID`=`Section`.`ID` " .
			"AND `Dish`.`RestaurantID`=`Section`.`RestaurantID` " .
			"AND `Dish`.`Hide`=0 AND `Section`.`Hide`=0 and `Dish`.`DenyOrder`=0 " .
			"ORDER BY `Section`.`Sequence` ASC, `Dish`.`Sequence` ASC ";
	$rs = $db->query($sql);
	while( $row = $rs->fetch_assoc() ) {
		array_push($dishes, $row);
	}
	$re['dishes'] = $dishes;
	
	$db->close();
	return $re;
}

/**
 * 查找指定坐标附近的餐馆，附近，指的是纬度范围在±0.02以内，经度范围在±0.03以内，返回数组
 * array(
 * 	0=> array('Name'=>餐馆名称,'UUID'=>餐馆uuid),
 * 	1=> array('Name'=>餐馆名称,'UUID'=>餐馆uuid),
 * 	2=> array('Name'=>餐馆名称,'UUID'=>餐馆uuid)
 * 	...
 * )
 */
function get_nearby_restaurant($lat, $lng) {
	$db = db_connect();
	$sql = "SELECT `UUID`, `Name`, " .
			"(`Latitude`-{$lat})*(`Latitude`-{$lat}) + (`Longitude`-{$lng})*(`Longitude`-{$lng}) AS DISTANCE " .
			" FROM `Restaurant` " .
			"WHERE ABS(`Latitude`-{$lat})<0.02 AND ABS(`Longitude`-{$lng}<0.03) " .
			"AND `Hide`=0 " .
			"ORDER BY DISTANCE ASC " .
			"LIMIT 10 ";
	$rs = $db->query($sql);
	$result = array();
	while($row=$rs->fetch_assoc()) {
		$result[] = $row;
	}
	$db->close();
	return $result;
}

/**
 * 当前用户对特定城市的订制数目
 */
function city_faver_count($city) {
	$re = 0;
	$db = db_connect();
	
	$sql = "SELECT COUNT(`FavRestaurant`.`ID`) FROM `FavRestaurant`, `Restaurant` WHERE " .
			( isset($_SESSION['session_customid']) ? "`FavRestaurant`.`CustomID`='{$_SESSION['session_customid']}'" : "`FavRestaurant`.`GuestID`='{$_COOKIE['guestid']}'" ) .
			" AND `FavRestaurant`.`RestaurantID`=`Restaurant`.`ID` " .
			" AND `Restaurant`.`City` LIKE '{$city}%';" ;
	$rs = $db->query($sql);
	if ( $row = $rs->fetch_row() ) {
		$re = $row[0] + 0;
	}
	
	$db->close();
	return $re;
}

/**
 * 返回结果
 * array(
 * 	"广州" => array("2", "广州", "<广州的CityId"),
 * 	"东莞" => array("3", "东莞", "<东莞的CityId")
 * )
 */
function all_city_faver_count() {
	$re = array();
	$db = db_connect();
	
	$sql = "SELECT COUNT(`FavRestaurant`.`ID`), `Restaurant`.`City` , `Restaurant`.`CityId` " .
			"FROM `FavRestaurant`, `Restaurant` WHERE " .
			( isset($_SESSION['session_customid']) ? "`FavRestaurant`.`CustomID`='{$_SESSION['session_customid']}'" : "`FavRestaurant`.`GuestID`='{$_COOKIE['guestid']}'" ) .
			" AND `FavRestaurant`.`RestaurantID`=`Restaurant`.`ID` " .
			" GROUP BY `Restaurant`.`City`;" ;
	$rs = $db->query($sql);
	while ( $row = $rs->fetch_row() ) {
		$re[$row[1]] = $row;
	}
	
	$db->close();
	return $re;
}

/**
 * 根据$_GET['id']添加餐馆到主页，返回操作结果
 * @return array 形式如下：
 * array(
 * 	"ret" => 0/1
 * 	"saveStatus" => 0/1
 * 	"favRestaurantsCount" => 当前城市的定制数
 * )
 */
function add_fav_restaurant() {
	$id = addslashes(trim($_GET['id']));
	
	$re = array();
	$db = db_connect();
	
	$sql = "INSERT INTO `FavRestaurant`(`CustomID`, `GuestID`, `RestaurantID`) " .
			"VALUES(" .
			( isset($_SESSION['session_customid']) ? "'{$_SESSION['session_customid']}', ": "NULL, ") .
			( isset($_COOKIE['guestid']) ? "'{$_COOKIE['guestid']}', ": "NULL, ") . 
			"'{$id}')";
	$db->query($sql);
	
	$re['ret'] = ($db->result !== FALSE ? 1 : 0);
	$re['saveStatus'] = ($db->result !== FALSE ? 1 : 0);
	
	$re['favRestaurantsCount'] = city_faver_count($_SESSION['session_city']);

	$db->close();
	return $re;
}

/**
 * 根据$_GET['id']从主页删除餐馆订制，返回操作结果
 * @return array 形式如下：
 * array(
 * 	"ret" => 0/1
 * 	"favRestaurantsCount" => 当前城市的定制数
 * )
 */
function remove_fav_restaurant() {
	$id = addslashes(trim($_GET['id']));
	
	$re = array();
	$db = db_connect();
	
	$condition = ( isset($_SESSION['session_customid']) ? "`CustomID`='{$_SESSION['session_customid']}' ": "");
	$condition .= empty($condition) ? ( isset($_COOKIE['guestid']) ? "`GuestID`='{$_COOKIE['guestid']}' ": "") : "";
	$condition .= empty($condition) ? "" : " AND ";
	
	$sql = "DELETE FROM `FavRestaurant` WHERE " . $condition . 
			" `RestaurantID`='{$id}'";
	$db->query($sql);
	
	$re['ret'] = ($db->result !== FALSE ? 1 : 0);
	
	$re['favRestaurantsCount'] = city_faver_count($_SESSION['session_city']);

	$db->close();
	return $re;
}

/**
 * 根据$_POST创建客户账户，
 */
function account_create() {
	$email = addslashes(trim($_POST['email']));
	$username = addslashes(trim($_POST['username']));
	$password = addslashes(trim($_POST['password']));
//	if( empty($email) ) {
//		set_error_notification('Email不能为空。');
//		redirect_with_post("signup.php");
//		return false;
//	}
//	if( !is_email_well_form($email) ) {
//		set_error_notification('Email格式不对');
//		redirect_with_post("signup.php");
//		return false;
//	}
	if( empty($username) ) {
		set_error_notification('用户名不能为空。');
		redirect_with_post("signup.php");
		return false;
	}
	if( strlen($username)<2 || strlen($username)>16 ) {
		set_error_notification('用户名长度不符合要求。');
		redirect_with_post("signup.php");
		return false;
	}
	if( empty($password) ) {
		set_error_notification('密码不能为空。');
		redirect_with_post("signup.php");
		return false;
	}
	if( strlen($username)<4 || strlen($username)>32 ) {
		set_error_notification('密码长度不符合要求。');
		redirect_with_post("signup.php");
		return false;
	}
	
	$re = false;
	$db = db_connect();
	
	//查询email是否已经被使用了
	$sql = "SELECT `Username` FROM `Custom` WHERE " .
//			"`Email`='{$email}' OR " .
			"`Username`='{$username}'; ";
	$rs = $db->query($sql);
	if ( $row = $rs->fetch_assoc() ) {
//		if( $row['Email'] == $email ) {
//			set_error_notification('此邮箱已注册，可直接<a href="login.php">登录</a>');
//		}
//		else
		if( $row['Username'] == $username ) {
			set_error_notification('用户名已被占用，请另选一个用户名');
		}
		redirect_with_post("signup.php");
		return false;
	}
	
	$sql = "INSERT INTO `Custom`(`Email`, `Username`, `Password`, `LastIp`,`RegTime`,`LastTime`) " .
			"VALUES('{$email}', '{$username}', MD5('{$password}'), '".get_client_ip()."', " .
			"'".get_datetime()."','".get_datetime()."'); ";
	$db->query($sql);
	$customid = $db->insert_id();
	if($db->result !== FALSE) {
		$re = true;
		//设置$_SESSION，使状态类似已登录状态
	
		$_SESSION['session_customid'] = $customid;
		$_SESSION['session_customEmail'] = $email;
		$_SESSION['session_customMobile'] = null;
		$_SESSION['session_customUsername'] = $username;
		$_SESSION['session_customEmailVerified'] = 0;
		$_SESSION['session_customMobileVerified'] = 0;
		$_SESSION['session_customMobileVerifying'] = 0;
		
		if( isset($_COOKIE['guestid']) ) {
			$id = $db->insert_id();
			
			//拷贝Guest的设置
			$sql = "SELECT `CityHint`, `WelcomeHint`, `MapHint`, `LastCityID`, `LastCity` " .
					"FROM `Guest` WHERE `GuestID`='{$_COOKIE['guestid']}';";
			$rs = $db->query($sql);
			if ( $row = $rs->fetch_assoc() ) {
				$sql = "UPDATE `Custom` SET `CityHint`='{$row['CityHint']}', `WelcomeHint`='{$row['WelcomeHint']}'," .
						"`MapHint`='{$row['MapHint']}', `LastCityID`='{$row['LastCityID']}', `LastCity`='{$row['LastCity']}' " .
						" WHERE `ID`='{$id}'";
				$db->query($sql);
			}
			
			//拷贝Guest的餐馆定制
			$sql = "INSERT INTO `FavRestaurant`(`CustomID`, `RestaurantID`) " .
					"SELECT '{$id}', `RestaurantID` FROM `FavRestaurant` " .
					"WHERE `GuestID`='{$_COOKIE['guestid']}'; ";
			$db->query($sql);
			
			//拷贝Guest的订餐车情况
			$sql = "INSERT INTO `Cart`(`CustomID`, `Json`,`LastUpdate`) " .
					"SELECT '{$id}', `Json`,`LastUpdate` FROM `Cart` " .
					"WHERE `GuestID`='{$_COOKIE['guestid']}'; ";
			$db->query($sql);
			
			//设置Guest的CustomID和IsLogined（默认是记住登录状态的）
			
			$sql = "UPDATE `Guest` SET `CustomID`='{$_SESSION['session_customid']}', `IsLogined`=1, " .
					"`LastTime`='".get_datetime()."',`LastIp`='".get_client_ip()."' " .
					"WHERE `GuestID`='{$_COOKIE['guestid']}'; ";
			$db->query($sql);
			$_SESSION['session_rememberlogin'] = 1;
		}
		
		set_success_notification("注册成功。");
		
//		send_verify_email($username, $email); 
	}
	$db->close();
	return $re;
}

function send_verify_email($username, $email) {
	$baseurl = "http://".$_SERVER['HTTP_HOST']."/";
	$code = uuid();
	$info = array(
		"username"=>$username, 
		"baseurl"=>$baseurl, 
		"code"=>$code
	);
		
	if( send_mail('VERIFICATION', $email, $info) ){
		$db = db_connect();
		date_default_timezone_set('PRC');
		$expire = date('Y-m-d H:i:s', strtotime('+1 day'));
		$sql = "INSERT INTO `EmailCode`(`Email`, `Code`, `Expire`) " .
				"VALUES('{$email}', '{$code}', '{$expire}');";
		$db->query($sql);
		$db->close();
		return true;
	}
	else {
		return false;
	}
}

/**
 * 根据$_GET['code']验证email，将验证结果更新到EmailCode表和Custom表，并返回操作结果（true/false）
 */
function verify_email() {
	$code = addslashes(trim($_GET['code']));
	if( empty($code) ) {
		set_error_notification("Email验证码为空。请直接点击验证地址，或者将验证地址复制到浏览器地址栏并回车确定。");
		return false;
	}
	
	$re = false;
	$db = db_connect();
	$sql = "SELECT `Email` FROM `EmailCode` WHERE `Code`='{$code}' " .
			"ORDER BY `ID` DESC LIMIT 1";
	$rs = $db->query($sql);
	if( $row = $rs->fetch_assoc() ) {
		$email = $row['Email'];
		$sql = "UPDATE `EmailCode` SET `Passed`=1, `PassedTime`='".get_datetime()."';";
		$db->query($sql);
		
		$sql = "UPDATE `Custom` SET `EmailVerified`=1, `LastIp`='".get_client_ip()."', " .
				"`LastTime`='".get_datetime()."' WHERE `Email`='{$email}'; ";
		$db->query($sql);
		
		$sql = "SELECT `ID`, `Email`, `Mobile`, `Username`, `CityHint`, `WelcomeHint`, `MapHint`, " .
				"`LastCityID`, `LastCity`, `MobileVerified`, `MobileVerifying` " .
				"FROM `Custom` WHERE `Email`='{$email}'; ";
		$rs = $db->query($sql);
		if( $row = $rs->fetch_assoc() ) {
			$_SESSION['session_customid'] = $row['ID'];
			$_SESSION['session_customEmail'] = $row['Email'];
			$_SESSION['session_customMobile'] = $row['Mobile'];
			$_SESSION['session_customUsername'] = $row['Username'];
			$_SESSION['session_customEmailVerified'] = 1;
			$_SESSION['session_customMobileVerified'] = $row['MobileVerified'];
			$_SESSION['session_customMobileVerifying'] = $row['MobileVerifying'];
			$_SESSION['session_cityhint'] = $row['CityHint'];
			$_SESSION['session_welcomehint'] = $row['WelcomeHint'];
			$_SESSION['session_maphint'] = $row['MapHint'];
			$cityid = $row['LastCityID'];
		
			$sql = "SELECT `Name`, `Latitude`, `Longitude`, `ZoomLevel` FROM `City` WHERE `ID`='{$cityid}' AND `Hide`=0; ";
			$rs = $db->query($sql);
			if($row = $rs->fetch_assoc()) {
				$_SESSION['session_city'] = $row['Name'];
				$_SESSION['session_latitude'] = $row['Latitude'];
				$_SESSION['session_longitude'] = $row['Longitude'];
				$_SESSION['session_zoomLevel'] = $row['ZoomLevel'];
				$_SESSION['session_cityid'] = $cityid;
			}
			
			$_SESSION['session_rememberlogin'] = 1;
		}
				
		set_success_notification("恭喜您，邮箱验证成功！");
		$re = true;
	}
	else {
		set_error_notification("Email验证码不正确。请验证连接是否完整。");
	}
	$db->close();
	return $re;
}

function check_login() {
	if( isset($_SESSION['session_customid']) ){
		return true;
	}
	else {
		clear_session();
		header("Location: index.php");
	}
}

/**
 * 验证用户的用户名（或者email、手机号）和密码，
 * 如果通过验证，则转到主页（给出登陆成功提示），
 * 否则转到登陆界面，并给出登陆失败提示
 */
function authenticate() {
	$username = addslashes(trim($_POST['username']));
	$password = addslashes(trim($_POST['password']));
	$remember = addslashes(trim($_POST['remember']));
	if (empty($username) || empty($password)) {
		set_error_notification("用户名或者密码为空。");
		redirect_with_post("login.php");
		return false;
	}
	
	$re = false;
	$db = db_connect();
	
	$sql = "SELECT `ID`, `Email`, `Mobile`, `Username`, `CityHint`, `WelcomeHint`, `MapHint`, " .
			"`LastCityID`, `LastCity`, `EmailVerified`, `MobileVerified`, `MobileVerifying` " .
			"FROM `Custom` WHERE (`Email`='{$username}' OR `Mobile`='{$username}' OR `Username`='{$username}') " .
			"AND `Password`=MD5('{$password}'); ";
	$rs = $db->query($sql);
	if( $row = $rs->fetch_assoc() ) {
		$_SESSION['session_customid'] = $row['ID'];
		$_SESSION['session_customEmail'] = $row['Email'];
		$_SESSION['session_customMobile'] = $row['Mobile'];
		$_SESSION['session_customUsername'] = $row['Username'];
		$_SESSION['session_customEmailVerified'] = $row['EmailVerified'];
		$_SESSION['session_customMobileVerified'] = $row['MobileVerified'];
		$_SESSION['session_customMobileVerifying'] = $row['MobileVerifying'];
		$_SESSION['session_cityhint'] = $row['CityHint'];
		$_SESSION['session_welcomehint'] = $row['WelcomeHint'];
		$_SESSION['session_maphint'] = $row['MapHint'];
		$cityid = $row['LastCityID'];
		
		//更新Custom的LastTime和LastIp
		$sql = "UPDATE `Custom` SET `LastIp`='".get_client_ip()."', " .
				"`LastTime`='".get_datetime()."' " .
				"WHERE `ID`='".$_SESSION['session_customid']."'; ";
		$db->query($sql);
	
		//获取城市信息
		$sql = "SELECT `Name`, `Latitude`, `Longitude`, `ZoomLevel` FROM `City` WHERE `ID`='{$cityid}' AND `Hide`=0; ";
		$rs = $db->query($sql);
		if( $row = $rs->fetch_assoc() ) {
			$_SESSION['session_city'] = $row['Name'];
			$_SESSION['session_latitude'] = $row['Latitude'];
			$_SESSION['session_longitude'] = $row['Longitude'];
			$_SESSION['session_zoomLevel'] = $row['ZoomLevel'];
			$_SESSION['session_cityid'] = $cityid;
		}
		
		if( $remember=='true' && isset($_COOKIE['guestid'])) {
			$sql = "UPDATE `Guest` SET `CustomID`='{$_SESSION['session_customid']}', `IsLogined`=1, " .
					"`LastTime`='".get_datetime()."', `LastIp`='".get_client_ip()."' " .
					"WHERE `GuestID`='{$_COOKIE['guestid']}'; ";
			$db->query($sql);
			$_SESSION['session_rememberlogin'] = 1;
		}
		
		//保存客户当前的订单
		if(!empty($_SESSION['session_cartjson'])) {
			$sql = "SELECT `ID` FROM `Cart` WHERE `CustomID`='{$_SESSION['session_customid']}';";
			$rs = $db->query($sql);
			if($row = $rs->fetch_assoc()) {
				$sql = "UPDATE `Cart` SET `Json`='{$_SESSION['session_cartjson']}', " .
						"`LastUpdate`='".get_datetime()."' " .
						"WHERE `CustomID`='{$_SESSION['session_customid']}';";
				
				$db->query($sql);
			}
			else {
				$sql = "INSERT INTO `Cart`(`CustomID`,`GuestID`,`Json`,`LastUpdate`) " .
						" VALUES('{$_SESSION['session_customid']}', NULL, " .
						"'{$_SESSION['session_cartjson']}', '".get_datetime()."');";
				$db->query($sql);
			}
		}
			
		
		process_long_time();
		
		//进一步看看客户是否有活动订单。
		$sql = "SELECT `ID`,UNIX_TIMESTAMP(`CreateTime`) AS CreateTime,`Status` FROM `Order` " .
				"WHERE `CustomID`='{$_SESSION['session_customid']}' " .
				"AND (`Status`<>'已取消' AND `Status`<>'成功结束') " .
				"ORDER BY `ID` ASC; ";
		$rs = $db->query($sql);
		while( $row = $rs->fetch_assoc() ) { //有活动订单
			$_SESSION['session_hasActiveOrder'] = 1;
			$_SESSION['session_lastOrderStartAt'] = $row['CreateTime'];;
			$_SESSION['session_Order'.$row['ID'].'StartAt'] = $row['CreateTime'];
			$_SESSION['session_Order'.$row['ID'].'Status'] = $row['Status'];
			$_SESSION['session_hasFailedOrder'] = ($row['Status']=='自动删除') ? 1 : 0;
		}
		
		custom_log('登录', '成功。');
		
		$re = true;
	}
	else {
		set_error_notification("用户名或者密码错误。");
		redirect_with_post("login.php");
		$re = false;
	}
	
	$db->close();
	if( $re ) {
		set_success_notification("登录成功。");
		if(!empty($_SESSION['session_login_from_orders'])){
			header("Location: orders_create.php");
			$_SESSION['session_login_from_orders'] = 0;
		}
		else {
			header("Location: index.php");
		}
	}
	return $re;
}

/**
 * 登出，如果成功，则设置成功notification，并转到login.php
 */
function logout() {
	if(!empty($_SESSION['session_rememberlogin']) && !empty($_SESSION['session_customid']) && isset($_COOKIE['guestid'])) {
		$db = db_connect();
		$sql = "UPDATE `Guest` SET `IsLogined`=0 " .
				"WHERE `GuestID`='{$_COOKIE['guestid']}' AND `CustomID`='{$_SESSION['session_customid']}';";
		$db->query($sql);
		$db->close();
	}
	
	custom_log('登出', '成功。');
	
	clear_session();
	
	set_success_notification("你已成功退出。");
	header("Location: login.php");
}

/**
 * 清除session数据
 */
function clear_session() {
	session_destroy();
	setcookie(session_name(),'',time()-3600);
	$_SESSION = array();
}

function custom_account_update() {
	check_login();
	
	$email = addslashes(trim($_POST['email']));
	$username = addslashes(trim($_POST['username']));
	$password = addslashes(trim($_POST['password']));
	
	$db = db_connect();
	$msg = "";
	$change_email = false;
	
	//修改用户名
	if( !empty($username) ) { 
		$sql = "UPDATE `Custom` SET `Username`='{$username}' " .
				"WHERE `ID`='{$_SESSION['session_customid']}'; ";
		$db->query($sql);
		if ($db->affected_rows > 0) {
			custom_log('设置', '修改用户名成功：新用户名：'.$username);
			$msg .= "已成功修改用户名。";
			$_SESSION['session_customUsername'] = $username;
		}
		else {
			custom_log('设置', '修改用户名失败：数据库操作影响行数为0');
		}
	}
	
	//修改用户密码
	if( !empty($password) ) { 
		$sql = "UPDATE `Custom` SET `Password`=MD5('{$password}') " .
				"WHERE `ID`='{$_SESSION['session_customid']}'; ";
		$db->query($sql);
		if ($db->affected_rows > 0) {
			custom_log('设置', '修改用户密码成功。');
			$msg .= "已成功修改用户密码。";
		}
		else {
			custom_log('设置', '修改用户密码失败：数据库操作影响行数为0');
		}
	}
	
	//修改email地址
	if( !empty($email) && empty($_SESSION['session_customEmailVerified']) ) {
		$sql = "UPDATE `Custom` SET `Email`='{$email}' " .
				"WHERE `ID`='{$_SESSION['session_customid']}'; ";
		$db->query($sql);
		if ($db->affected_rows > 0) {
			custom_log('设置', '修改Email成功：新Email：'.$email);
			send_verify_email($username, $email);
			$change_email = true;
			$_SESSION['session_customEmail'] = $email;
		}
		else {
			custom_log('设置', '修改Email失败：数据库操作影响行数为0');
		}
	}
	
	$db->close();
	
	if($change_email) {
		redirect_with_post("verify_email_sent.php");
	}
	elseif(!empty($msg)){
		set_success_notification($msg);
	}
}

/**
 * 修改用户手机号吗，并重发验证码
 */
function custom_mobile_update() {
	check_login();
	
	$db= db_connect();
	if( !empty($_GET['reset']) ) {//重设手机号码，重置MobileVerifying为0
		$sql = "UPDATE `Custom` SET `MobileVerifying`=0, `MobileVerified`=0 WHERE `ID`='{$_SESSION['session_customid']}'; ";
		$db->query($sql);
		custom_log('设置', '修改重置手机号码成功。');
		$_SESSION['session_customMobileVerifying'] = 0;
		$_SESSION['session_customMobileVerified'] = 0;
		set_success_notification("已经重置了您的手机号码，请设置手机号码，并重新发送验证码。");
	}
	else {
		$mobile_number = addslashes(trim($_POST['mobile_number']));
		if(!empty($mobile_number)) {
			if( sent_verify_sms($mobile_number) ) {//发送手机号码验证短信
				$sql = "UPDATE `Custom` SET `Mobile`='{$mobile_number}' ,`MobileVerifying`=1, `MobileVerified`=0 WHERE `ID`='{$_SESSION['session_customid']}'; ";
				$db->query($sql);
				$_SESSION['session_customMobileVerifying'] = 1;
				$_SESSION['session_customMobileVerified'] = 0;
				set_success_notification("多谢，请稍候，我们发了验证短信给您。");
			}
			custom_log('设置', '修改手机号码成功：新手机号码：'.$mobile_number);
			$_SESSION['session_customMobile'] = $mobile_number;
		}
		elseif($_POST['fromsetting'] == 'true') {
			set_error_notification("手机号码为空");
			custom_log('设置', '修改手机号码失败：手机号码为空。');
		}
	}
	$db->close();
}

/**
 * 发送验证码短信
 */
function sent_verify_sms($mobile_number, $fromorders = false, $orderid = 0) {
	$code =generate_sms_code();
	
	if(!isset($_SESSION['session_Setting_SITE_NAME'])){
		read_setting();
	}

	//发送短信
	custom_log('设置', '发送手机号码验证短信，开始。');
	$ids = send_sms($mobile_number,"感谢您使用".$_SESSION['session_Setting_SITE_NAME']."的服务，请在网页中输入以下代码：".$code."，验证您的手机号码，以便我们为您提供更贴心的服务。", $_SESSION['session_customid']);
	
	if(is_array($ids) && !empty($ids)){ //发送成功
		custom_log('设置', '发送手机号码验证短信，成功。');
		$db = db_connect();
		date_default_timezone_set('PRC');
		$expire = date('Y-m-d H:i:s', strtotime('+1 day'));
		$sql = "INSERT INTO `SmsCode`(`Type`,`CustomID`,`OrderID`,`Mobile`,`Code`,`Expire`) " .
				"VALUES(" .
				($fromorders ? "'手机号码验证及订餐确认', " : "'手机号码验证',") .
				"'{$_SESSION['session_customid']}', " .
				($fromorders && $orderid ? "'{$orderid}', " : "NULL, ") .
				"'{$mobile_number}'," .
				"'{$code}', '{$expire}')";
		$db->query($sql);
		
		$db->close();
		return true;
	}
	else {
		if($ids === false) {
			custom_log('设置', '发送手机号码验证短信失败，由于手机号码错误等原因，根本没有发送。');
		}
		else {
			custom_log('设置', '发送手机号码验证短信失败，原因：' . $ids);
		}
	}
	return false;
}

/**
 * 重发短信验证码，根据$_REQUEST['from']而重发不同的短信验证码，
 * $_REQUEST['from'] == 'orders'，则重发订餐验证码，并且重定向到orders_verifymobile.php
 * $_REQUEST['from'] == 'login'，则重发登录验证码，并且重定向到mobile_login.php
 * 否则重发手机号码验证的验证码
 */
function resend_sms_code() {
	if(!isset($_SESSION['session_Setting_SITE_NAME'])){
		read_setting();
	}
	
//	if($_REQUEST['from'] == 'orders') { //重发订餐验证码
//		custom_log('订餐', '请求重新发送订餐验证短信。');
//		if(!empty($_SESSION['session_hasActiveOrder']) 
//			&& !empty($_SESSION['session_customMobile']) 
//			&& !empty($_SESSION['session_customid']))
//		{
//			$orderid = addslashes(trim($_REQUEST['orderid']));
//			$db = db_connect();
//			$sql = "SELECT `Code` FROM `SmsCode` " .
//					"WHERE `CustomID`='{$_SESSION['session_customid']}' " .
//					"AND `OrderID`='{$orderid}' " .
//					"AND `Mobile`='{$_SESSION['session_customMobile']}' " .
//					"AND (`Type`='订餐确认' OR  `Type`='手机号码验证及订餐确认') " .
//					"ORDER BY `ID` DESC LIMIT 1;";
//			$rs = $db->query($sql);
//			if ($row = $rs->fetch_assoc()) {
//				$ids = send_sms($_SESSION['session_customMobile'],
//					"感谢您在".$_SESSION['session_Setting_SITE_NAME']."订单，请在网站输入代码：".$row['Code']."，以确认您的订餐。",
//					$_SESSION['session_customid']);
//				if(is_array($ids) && !empty($ids)) {
//					custom_log('订餐', '重新订餐验证短信，成功。');
//					
//					if(!empty($_REQUEST['returnmsg'])){
//						echo '{"type":"success", "msg":"请稍候，我们给您重发了订餐验证短信，请查收，并重新填写验证码。"}';
//					}
//					else {
//						set_success_notification('请稍候，我们给您重发了订餐验证短信，请查收，并重新填写验证码。');
//					}
//				}
//				else {
//					if($ids === false) {
//						custom_log('设置', '重新发送订餐验证短信失败，由于手机号码错误等原因，根本没有发送。');
//					}
//					else {
//						custom_log('设置', '重新发送订餐验证短信失败，原因：' . $ids);
//					}
//				}
//			}
//			$db->close();
//		}
//		header('Location: orders_verifymobile.php');
//	}
//	else
	if($_REQUEST['from'] == 'login') {//重发登录验证码
		if(!empty($_SESSION['session_customMobile'])) {
			
			//TODO 重发登录验证码
			
		}
		header('Location: login_mobile.php');
	}
	else { //重发手机号码验证的验证码
		custom_log('设置', '请求重新发送手机号码验证短信。');
		if(!empty($_SESSION['session_customMobileVerifying']) 
			&& !empty($_SESSION['session_customMobile']) 
			&& !empty($_SESSION['session_customid']))
		{
			$db = db_connect();
			$sql = "SELECT `Code` FROM `SmsCode` " .
					"WHERE `CustomID`='{$_SESSION['session_customid']}' " .
					"AND `Mobile`='{$_SESSION['session_customMobile']}' " .
					"AND `Type`='手机号码验证' " .
					"ORDER BY `ID` DESC LIMIT 1;";
			$rs = $db->query($sql);
			if ($row = $rs->fetch_assoc()) {
				$ids = send_sms($_SESSION['session_customMobile'],
					"感谢您使用".$_SESSION['session_Setting_SITE_NAME']."的服务，请在网页中输入以下代码：".$row['Code']."，验证您的手机号码，以便我们为您提供更贴心的服务。重发：".date('H:i:s'),
					$_SESSION['session_customid']);
				if(is_array($ids) && !empty($ids)) { 
					custom_log('设置', '重新发送手机号码验证短信，成功。');
					set_success_notification('请稍候，我们给您重发了验证短信，请查收，并重新填写验证码。');
				}
				else {
					if($ids === false) {
						custom_log('设置', '重新发送手机号码验证短信失败，由于手机号码错误等原因，根本没有发送：手机号码：'.$_SESSION['session_customMobile']);
					}
					else {
						custom_log('设置', '重新发送手机号码验证短信失败，原因：' . $ids);
					}
				}
			}
			$db->close();
		}
		if($_REQUEST['from'] == 'orders') {
			header('Location: orders_verifymobile.php');
		}
		else {
			header('Location: custom_mobile.php');
		}
	}
}

/**
 * 根据$_POST['activationCode']以及当前的$_SESSION，验证用户的手机号码是否正确。
 */
function custom_activate_mobile() {
	check_login();
	
	if(empty($_SESSION['session_customMobileVerifying'])) {
		exit;
	}
	
	if(empty($_POST['activationCode'])) {
		set_error_notification("请输入您收到的验证码");
		exit;
	}
	$activationCode = addslashes(trim($_POST['activationCode']));
	
	$db = db_connect();
	$sql = "SELECT `ID` FROM `SmsCode` WHERE `CustomID`='{$_SESSION['session_customid']}' AND `Code`='{$activationCode}';";
	$rs = $db->query($sql);
	if($row = $rs->fetch_assoc()) {
		$sql = "UPDATE `SmsCode` SET `Passed`=1, `PassedTime`='".get_datetime()."' WHERE `ID`='{$row['ID']}'";
		$db->query($sql);
		set_success_notification("手机号码验证成功，感谢您的支持！");
	}
	else {
		set_error_notification("您输入的验证码有误，请重新输入。");
	}
	$db->close();
}


/**
 * 添加、更新或者删除用户地址
 */
function custom_addresses_update() {
	check_login();
	
	$do = addslashes(trim($_POST['do']));
	$address = addslashes(trim($_POST['address']));
	$addressid = addslashes(trim($_POST['addressid']));
	
	if($do!='add' && $do!='edit' && $do!='delete'){
		return;
	}
	
	if($do=='add' && !empty($address)) {//添加地址
		add_custom_address($address);
	}
	elseif($do=='edit' && !empty($address) && !empty($addressid)) {
		edit_custom_address($address, $addressid);
	}
	elseif($do=='delete' && !empty($addressid)){
		delete_custom_address($addressid);
	}
}

function add_custom_address($address) {
	$db = db_connect();
	$sql = "INSERT INTO `CustomAddress`(`CustomID`, `Address`)  " .
			"VALUES('{$_SESSION['session_customid']}', '{$address}')";
	$db->query($sql);
	if($db->result!==FALSE) {
		custom_log('设置', '添加地址成功：'.$address.'，id：'.$db->insert_id());
		set_success_notification("添加地址成功。");
	}
	else {
		custom_log('设置', '添加地址失败数据库操作失败。');
	}
	$db->close();
}

function edit_custom_address($address, $addressid) {
	$db = db_connect();
	$sql = "UPDATE `CustomAddress` SET `Address`='{$address}' " .
			"WHERE `ID`='{$addressid}';";
	$db->query($sql);
	if($db->result!==FALSE) {
		custom_log('设置', '修改地址成功：'.$address.'，id：'.$addressid);
		set_success_notification("修改地址成功。");
	}
	else {
		custom_log('设置', '修改地址失败数据库操作失败。');
	}
	$db->close();
}

function delete_custom_address($addressid) {
	$db = db_connect();
	$sql = "DELETE FROM `CustomAddress` WHERE `ID`='{$addressid}';";
	$db->query($sql);
	if($db->result!==FALSE) {
		custom_log('设置', '删除地址成功，地址id：'.$addressid);
		set_success_notification("删除地址成功。");
	}
	else {
		custom_log('设置', '删除地址失败数据库操作失败。');
	}
	$db->close();
}

function get_custom_addresses() {
	$re = array();
	$db = db_connect();
	$sql = "SELECT `ID`, `Address` FROM `CustomAddress` WHERE `CustomID`='{$_SESSION['session_customid']}';";
	$rs = $db->query($sql);
	while ( $row = $rs->fetch_assoc() ) {
		array_push($re, $row);
	}
	$db->close();
	
	return $re;
}

/**
 * 获取答疑（显示在主页的）
 * 输入：$_GET['limit']，$_GET['from']，如果不指定，这两个值默认分别为10，0
 */
function get_messages() {
	$limit = addslashes(trim($_GET['limit'])) + 0;
	$from = addslashes(trim($_GET['from'])) + 0;
	if(empty($limit)) $limit = 10;
	
	$re = array();
	$db = db_connect();
	$sql = "SELECT `Name`, `Question`, `Answer` " .
			"FROM `QA` WHERE `Show`=1 AND `Hide`=0 " .
			"ORDER BY `QTime` DESC " .
			"LIMIT {$from},{$limit}";
	$rs = $db->query($sql);
	while ( $row = $rs->fetch_assoc() ) {
		array_push($re, $row);
	}
	$db->close();
	
	return $re;
}

/**
 * 获取当前客户的答疑
 */
function get_custom_messages() {
	$re = array();
	$db = db_connect();
	$sql = "SELECT `ID`, `CustomID`, `Name`, `Question`, `QTime`, `Answer`, `ATime`  " .
			"FROM `QA` WHERE `CustomID`='{$_SESSION['session_customid']}' " .// AND `Hide`=0
			"ORDER BY `QTime` DESC;"; 
	$rs = $db->query($sql);
	while ( $row = $rs->fetch_assoc() ) {
		array_push($re, $row);
	}
	$db->close();
	
	return $re;
}

/**
 * 根据$_POST数据添加一个答疑留言
 */
function add_message() {
	$content = addslashes(trim($_POST['content']));
	$email = addslashes(trim($_POST['email']));
	if(empty($content)) {
		set_error_notification("请输入您的留言。");
		return;
	}
	if(!isset($_SESSION['session_customid']) && empty($email)) {
		set_error_notification("请输入您的Email地址，以便我们及时Email回复您。");
		return;
	}
	if(!isset($_SESSION['session_customid']) && !is_email_well_form($email)) {
		set_error_notification("Email格式错误。");
		return;
	}
	
	$name = isset($_SESSION['session_customUsername']) ? $_SESSION['session_customUsername'] : substr($email, 0, strpos($email, '@'));
	
	$db = db_connect();
	$sql = "INSERT INTO `QA`(`CustomID`, `Email`, `Name`, `IP`,`Question`,`QTime`) " .
			"VALUES(".(isset($_SESSION['session_customid']) ? "'{$_SESSION['session_customid']}'" : "NULL").", " . 
					"".(empty($email) ? "NULL" : "'{$email}'").", " .
						"'{$name}', '".get_client_ip()."', '{$content}','".get_datetime()."')";
	$db->query($sql);
	if($db->result !==FALSE) {
		if(isset($_SESSION['session_customid'])) custom_log('留言', '添加留言成功，留言内容：'.$content);
		set_success_notification("多谢！您的留言已提交，我们会尽快处理。");
	}
	else {
		if(isset($_SESSION['session_customid'])) custom_log('留言', '添加留言失败：数据插入失败，留言内容：'.$content);
	}
	$db->close();
}

/**
 * 根据$_POST数据更新当前客户或访客的订餐车数据（数据表Cart）
 */
function cart_update() {
	$name = trim($_POST['name']);
	$value = trim($_POST['value']);
	if($name!='cart') {
		return;
	}
	
	$db = db_connect();
	$where = ( isset($_SESSION['session_customid']) ? " `CustomID`='{$_SESSION['session_customid']}'" : "`GuestID`='{$_COOKIE['guestid']}'" );
	$insertvalue = ( isset($_SESSION['session_customid']) ? "'{$_SESSION['session_customid']}', NULL, '{$value}'" : "NULL, '{$_COOKIE['guestid']}', '{$value}'" );
	$sql = "SELECT `ID` FROM `Cart` WHERE {$where};";
	$rs = $db->query($sql);
	if($row = $rs->fetch_assoc()) {
		$sql = "UPDATE `Cart` SET `Json`='{$value}',`LastUpdate`='".get_datetime()."' WHERE {$where};";
		$db->query($sql);
	}
	else {
		$sql = "INSERT INTO `Cart`(`CustomID`,`GuestID`,`Json`,`LastUpdate`)" .
				" VALUES({$insertvalue},'".get_datetime()."');";
		$db->query($sql);
	}
	$_SESSION['session_cartjson'] = $value;
	$db->close();
}

/**
 * 获取当前用户（客户/访客）的订餐车数据
 */
function get_cart_json() {
	$re = "{}";
	$db = db_connect();
	$where = ( isset($_SESSION['session_customid']) ? " `CustomID`='{$_SESSION['session_customid']}'" : "`GuestID`='{$_COOKIE['guestid']}'" );
	$sql = "SELECT `Json` FROM `Cart` WHERE {$where} LIMIT 1;";
	$rs = $db->query($sql);	
	if ($row = $rs->fetch_assoc() ){
		$re = $row['Json'];
		$_SESSION['session_cartjson'] = $row['Json'];
	}
	$db->query($sql);
	$db->close();
	return $re;
}

/**
 * 根据$_SESSION['session_cartjson']及查询数据库分析当前的订单情况，返回一个数组以供order_create.php使用。
 * 返回的数组形式如下：
 * array(
 * 		0 => array(
 * 			"restaurant" => array(
 * 				"ID" => "",
 * 				"Name" => "",
 * 				"Telphone" => "",
 * 				"Notice" => "",
 * 				"MinMoney" => 123,
 * 				"Takeout" => 0/1,
 * 				"DiscountIn" => 123,
 * 				"SaleAd" => ""
 * 			)
 * 			"dish_list" => array(
 * 				0 => array(
 * 					"ID" => "",
 * 					"Name" => "",
 * 					"Price" => 123,
 * 					"Count" => ""
 * 				)
 * 				1 => array(
 * 					"ID" => "",
 * 					"Name" => "",
 * 					"Price" => 231,
 * 					"Count" => ""
 * 				)
 * 				...
 * 			)
 * 			"mobile" => "",
 * 			"addresses" => array(
 * 				0 => array("ID"=>"", "Address"=>""),
 * 				1 => array("ID"=>"", "Address"=>"")
 * 				...
 * 			)
 * 		)
 * 		1 = > array(
 * 			...
 * 		)
 * 		...
 * )
 */
function parse_orders() {
	if(!isset($_SESSION['session_cartjson'])){
		return array();
	}
	
	$json = $_SESSION['session_cartjson'];
	$obj = json_decode($json);
	$sort = $obj->sort->sort;
	if(empty($sort)) return array();
	
	//变换数字字符串下标为字符串下标（因为似乎php有bug，不能访问到数字下标的复杂对象）
	foreach($sort as $s) {
		$json = str_replace('"'.$s.'":[{', '"a'.$s.'":[{', $json);
	}
	//重新分析json_decode
	$obj = json_decode($json);
	$arr = (array) $obj;
	$restaurants = get_restaurant_for_order($sort);
	$user_mobile_and_addresses = get_user_mobile_and_addresses();
	
	$orders = array();
	foreach($sort as $s) {
		$r = $arr["a".$s];
		$total = 0;
		$restaurant = array(
			"ID"   => $r[0]->restaurantId,
			"Name" => $r[0]->restaurantName,
			"Telphone" => $r[0]->restaurantTel,
			"Notice" => $restaurants[$s]['Notice'],
			"MinMoney" => $restaurants[$s]['MinMoney'],
			"Takeout" => $restaurants[$s]['Takeout'],
			"DiscountIn" => $restaurants[$s]['DiscountIn'],
			"SaleAd" => $restaurants[$s]['SaleAd']
		);
		
		$dish_list = array();
		foreach($r as $d) {
			$total += $d->price * $d->count;
			$dish = array(
				"ID" => $d->id,
 				"Name" => $d->name,
 				"Price" => $d->price,
 				"Count" => $d->count
			);
			array_push($dish_list, $dish);
		}
		
		$order = array(
			"restaurant" => $restaurant,
			"dish_list" => $dish_list,
			"mobile" => $user_mobile_and_addresses["mobile"],
			"addresses" => $user_mobile_and_addresses["addresses"],
			"total" => $total,
			"less_than_minmoney" => ($total < $restaurant["MinMoney"])
		);
		
		array_push($orders, $order);
	}
	
	return $orders;
}

/**
 * 根据给出的id数组，查找相关餐馆的有关信息，供parse_orders()使用
 */
function get_restaurant_for_order($ids_array) {
	$re = array();
	if(empty($ids_array)) return $re;
	
	$ids = implode(",", $ids_array);
	$db = db_connect();
	$sql = "SELECT `ID`,`Name`,`Notice`,`MinMoney`,`Takeout`,`DiscountIn`,`SaleAd` " .
			"FROM `Restaurant` WHERE `ID` IN ({$ids})";
	$rs = $db->query($sql);
	while ( $row = $rs->fetch_assoc() ) {
		$salead = preg_replace('/#name#/', $row['Name'],  $row['SaleAd']);
		$salead = preg_replace('/#discount#/', '<span class="discount">'.($row['DiscountIn']+0).'</span>',  $salead);
		$re[$row['ID']] = array(
			"Notice" => $row['Notice'],
			"MinMoney" => $row['MinMoney'] + 0,
			"Takeout" => $row['Takeout'] + 0,
			"DiscountIn" => $row['DiscountIn'] + 0,
			"SaleAd" =>$salead
		);
	}
	
	$db->close();
	return $re;
}

/**
 * 获取当前用户的手机号码和地址列表，供parse_orders()使用
 */
function get_user_mobile_and_addresses() {
	$re = array();
	if(!isset($_SESSION['session_customid'])) return $re;
	
	
	$db = db_connect();
	$sql = "SELECT `Mobile` FROM `Custom` WHERE `ID`='{$_SESSION['session_customid']}';";
	$rs = $db->query($sql);
	if ($row = $rs->fetch_assoc()) {
		$re["mobile"] = $row['Mobile'];
	}
	else {
		$re["mobile"] = "";
	}
	
	$sql = "SELECT `ID`, `Address` FROM `CustomAddress` WHERE `CustomID`='{$_SESSION['session_customid']}';";
	$rs = $db->query($sql);
	$addresses = array();
	while ( $row = $rs->fetch_assoc() ) {
		$address = array(
			"ID" => $row["ID"],
			"Address" => $row["Address"]
		);
		array_push($addresses, $address);
	} 
	$re["addresses"] = $addresses;
	$db->close();
	return $re;
}

/**
 * 在一个字符串中每隔三个中文字就插入一个<wbr></wbr>，以方便浏览器进行断句
 */
function insert_wbr( $str ) {
	return $str;
	$len = strlen($str);
	$fragArray = array();
	for($i = 0; $i<$len; $i=$i+9) {
		$frag = substr($str, $i, 9);
		$fragLen=9;
		// prevent breaking html code
		while( preg_match("/<[^>]+$/", $frag) && ($fragLen<$len-$i) ){
			$fragLen++;
			$frag = substr($str, $i, fragLen);
		}
		// prevent breaking &...;
		while( preg_match("/\&[a-zA-Z]{0,5}$/", $frag) 
			&& preg_match("/^[a-zA-Z]{0,5}\;/", substr($str, $i+$fragLen))
		){
			$fragLen++;
			$frag = substr($str, $i,fragLen);
		}
		$i += ($fragLen-9);
		array_push($fragArray, $frag);
	}
//	return implode("<wbr/>", $fragArray);
}

/**
 * 根据$_GET['restaurantid']删除当前订餐车中相应餐馆的订餐，并更新到数据库
 */
function orders_delete($rid=null){
	if(empty($rid))
		$restaurantid = addslashes(trim($_GET['restaurantid'])) + 0;
	else
		$restaurantid = $rid;
	
	if(!isset($_SESSION['session_cartjson']) || empty($restaurantid) || !isset($_SESSION['session_customid'])){
		return ;
	}
	
	$json = $_SESSION['session_cartjson'];
	$obj = json_decode($json);
	$sort = $obj->sort->sort;
	if(empty($sort)) return ;
	
	$index = -1;
	
	//变换数字字符串下标为字符串下标（因为似乎php有bug，不能访问到数字下标的复杂对象）
	foreach($sort as $i => $s) {
		if($s == $restaurantid) $index = $i;
		$json = str_replace('"'.$s.'":[{', '"a'.$s.'":[{', $json);
	}
	
	if($index==-1) return;
	
	//重新分析json_decode
	$obj = json_decode($json);
	$arr = (array) $obj;
	
	//删除sort中的相关项
	array_splice($arr["sort"]->sort, $index, 1);
	$sort = $arr["sort"]->sort;
	//删除餐馆的订餐
	unset($arr["a".$restaurantid]);
	
	//还原json字符串
	$json = custom_json_encode($arr);
	foreach($sort as $s) {
		$json = str_replace('"a'.$s.'":[{', '"'.$s.'":[{', $json);
	}
	
	//更新到数据库：
	$db = db_connect();
	$sql = "UPDATE `Cart` SET `Json`='{$json}',`LastUpdate`='".get_datetime()."' " .
			"WHERE `CustomID`='{$_SESSION['session_customid']}';";
	$db->query($sql);
	$db->close();
	
	//更新Session
	$_SESSION['session_cartjson'] = $json;
	
	set_success_notification("订单删除成功。");
}

/**
 * 根据$_POST[]进行下单
 */
function orders_drop() {
	check_login();
	
	$count = $_POST["count"];
	$dishes = $_POST["dishes"];
	$dishNames = $_POST["dishNames"];
	$dishPrices = $_POST["dishPrices"];
	$mobileNumber = addslashes(trim($_POST["mobileNumber"]));
	$addressOld = $_POST["addressOld"] + 0;
	$address = addslashes(trim($_POST["address"]));
	$notes = addslashes(trim($_POST["notes"]));
	$restaurantId = addslashes(trim($_POST["restaurantId"]));
	$restaurant = addslashes(trim($_POST["restaurant"])); 
	$takeout = addslashes(trim($_POST["takeout"])); 
	$takeout = (empty($takeout) ? 0 : 1);
	$discount = addslashes(trim($_POST["discount"]))+0;
	$discount = (empty($discount) ? 10 : $discount);
	
	//检查输入数据
	if(!is_array($count) || !is_array($dishes) || count($count)!=count($dishes)
		|| !is_array($dishNames) || count($dishNames)!=count($dishes)
		|| !is_array($dishPrices) || count($dishPrices)!=count($dishes)
		|| empty($restaurantId) || empty($restaurant)
	) {
		custom_log('订餐', '订餐失败：系统出错：订餐数据校验不正确。');
		set_error_notification('系统出错！');
		return false;
	}
	
	if( empty($mobileNumber) ) {
		custom_log('订餐', '订餐失败：没有填写手机号码。');
		set_error_notification('请填写有效的手机号码。');
		return false;
	}
	
	if(!empty($takeout) && (empty($addressOld) && empty($address))) {
		custom_log('订餐', '订餐失败：没有填写详细地址。');
		set_error_notification('请填写或选择一个详细地址。');
		return false;
	}
	$db = db_connect();
	
	if(!empty($address)) { //保存新地址
		$sql = "INSERT INTO `CustomAddress`(`CustomID`, `Address`) " .
				"VALUES('{$_SESSION['session_customid']}', '{$address}'); ";
		$db->query($sql);
		custom_log('设置', '订餐中添加了新地址：'.$address);
	}
	elseif(!empty($takeout)) { //没有新地址，又是送餐上门，使用旧地址
		$sql = "SELECT `Address` FROM `CustomAddress` WHERE `ID`='{$addressOld}'; ";
		$rs = $db->query($sql);
		if ( $row = $rs->fetch_assoc() ) {
			$address = $row['Address'];
		}
		else {
			custom_log('订餐', '订餐失败：系统出错：客户选用旧地址，但查询数据库查不到相应的地址。');
			set_error_notification('系统出错！');
			return false;
		}
	}
	
	$timeNote = "就餐时间没有要求";
	if(empty($takeout)) { //到店消费，分析一下就餐时间的输入
		$timeNote = ($_POST['time_type']=='1') ? 
			'在'.($_POST['time_type_1']+0).'分钟后就餐' 
			: (!empty($_POST['time_type_2']) ? 
				addslashes(trim($_POST["time_type_2"])) 
				: (empty($takeout) ? $timeNote : "") );
	}
	
	$need_verify_mobile = false;
	
	if(empty($_SESSION['session_customMobile']) || empty($_SESSION['session_customMobileVerified']) 
		|| $_SESSION['session_customMobile']!=$mobileNumber) 
	{ //新手机号码，或手机号码未验证，则更新手机号码，并发送验证短信
		$sql = "UPDATE `Custom` SET `Mobile`='{$mobileNumber}', `MobileVerified`=0, `MobileVerifying`=1 " .
				"WHERE `ID`='{$_SESSION['session_customid']}'";
		$db->query($sql);
		
		$_SESSION['session_customMobileVerifying'] = 1;
		$_SESSION['session_customMobileVerified'] = 0;
		$_SESSION['session_customMobile'] = $mobileNumber;
		custom_log('设置', '订餐中填写了新手机号码：'.$mobileNumber);
		
		$need_verify_mobile = true;
	}
	
	$vericode = rand(1000,9999);
	
	//保存订单信息
	$sql = "INSERT INTO `Order`(`CustomID`,`RestaurantID`,`Mobile`,`Address`,`Notes`,`CreateTime`," .
			"`Takeout`,`TimeNote`,`Discount`,`VeriCode`,`LastUpdate`)" .
			"VALUES('{$_SESSION['session_customid']}', '{$restaurantId}', '{$mobileNumber}', " .
			"'{$address}', '{$notes}', '".get_datetime()."', " .
			"'{$takeout}', '{$timeNote}','{$discount}','{$vericode}','".get_datetime()."')";
	$db->query($sql);
	if($db->result!==false) {
		$id = $db->insert_id();
		
		if($need_verify_mobile){
			sent_verify_sms($mobileNumber, true, $id);
			
		}
		
		
		custom_log('订餐', '保存订单信息成功：'.(empty($takeout) ? '送餐上门' : '到店消费'));
		$total = 0;
		//保存订单项
		foreach($dishes as $index => $dish) {
			$total += $dishPrices[$index] * $count[$index];
			$sql = "INSERT INTO `OrderItem`(`OrderID`,`DishID`,`Name`,`Price`," .
					"`Count`,`RestaurantID`,`Restaurant`)" .
					"VALUES('{$id}','{$dish}','{$dishNames[$index]}','{$dishPrices[$index]}'," .
					"'{$count[$index]}','{$restaurantId}','{$restaurant}')";
			$db->query($sql);
		}
		$discountTotal = $discount*$total/10;
		
		$sql = "UPDATE `Order` SET `Total`='{$total}',`DiscountTotal`='{$discountTotal}', " .
				"`LastUpdate`='".get_datetime()."' WHERE `ID`='{$id}';";
		$db->query($sql);
		
		//从订餐车中删除当前的订单
		orders_delete($restaurantId);
		
		//设置Session参数
		$_SESSION['session_hasActiveOrder'] = 1;
		$_SESSION['session_lastOrderStartAt'] = time();
		$_SESSION['session_Order'.$id.'StartAt'] = time();
		$_SESSION['session_Order'.$id.'Status'] = '创建';
		
		order_process($id, 1);
		
//		//发送短信验证码
//		if(send_orders_verify_sms($id)){
//			custom_log('订餐', '发送短信验证码成功。');
//			set_info_notification('请先验证您的手机。');
//			//发送成功则，更新当前订单的状态为"等待客户确认"
//			$sql = "UPDATE `Order` SET `Status`='等待客户确认' WHERE `ID`={$id}";
//			$db->query($sql);
//			$_SESSION['session_Order'.$id.'Status'] = '等待客户确认';
			custom_log('订餐', '订单创建。');
//		}

	
		if($need_verify_mobile) {
			$sql = "UPDATE `Order` SET `Status`='等待手机验证',`LastUpdate`='".get_datetime()."' WHERE `ID`={$id}";
			$db->query($sql);
			$_SESSION['session_Order'.$id.'Status'] = '等待手机验证';
			set_info_notification('请先验证您的手机。');
		}
		elseif($takeout) { //送餐上门
			$sql = "UPDATE `Order` SET `Status`='正在送餐',`CTime`='".get_datetime()."',`COperation`='确认',`LastUpdate`='".get_datetime()."' WHERE `ID`='{$id}'";
			$db->query($sql);
			//send_order_to_restaurant($id);//dll12345
			getPrintText($id,'送餐上门');
			order_process($id, 5);
			$_SESSION['session_Order'.$id.'Status'] = '正在送餐';
			set_success_notification('订单创建成功。');
		}
		else { //到店消费
			//send_indoor_sms($id);  // dll12345
			getPrintText($id,'到店消费');
			set_success_notification('订单创建成功。');
		}
	}
	else {
		custom_log('订餐', '保存订单信息失败。');
	}
	
	
	$db->close();
	return true;
}

/**
 * 发送到店消费的短信TODO
 */
function send_indoor_sms($orderid) {
	if(!isset($_SESSION['session_Setting_SITE_NAME'])){
		read_setting();
	}
	
	$db = db_connect();
	$sql = "SELECT `Restaurant`.`Mobile` AS RestaurantMobile, `Restaurant`.`Name`, " .
			"`Order`.`Mobile` AS CustomMobile, `Order`.`RestaurantID`, " .
			"`Order`.`TimeNote`, `Order`.`Notes`, `Order`.`CustomID`, `Order`.`DiscountTotal`, " .
			"`Order`.`VeriCode`, `Order`.`TimeNote`, `Custom`.`Username` " .
			"FROM `Restaurant`, `Order`, `Custom` " .
			"WHERE `Order`.`ID`='{$orderid}' " .
			"AND `Order`.`RestaurantID`=`Restaurant`.`ID` " .
			"AND `Custom`.`ID`=`Order`.`CustomID`";
	$rs = $db->query($sql);
	if($row = $rs->fetch_assoc() ) {
		$RestaurantMobile = $row['RestaurantMobile'];
		$Restaurant = $row['Name'];
		$RestaurantID = $row['RestaurantID'];
		$CustomMobile = $row['CustomMobile'];
		$TimeNote = $row['TimeNote'];
		$Notes = $row['Notes'];
		$CustomID = $row['CustomID'];
		$CustomName = $row['Username'];
		$DiscountTotal = $row['DiscountTotal'];
		$VeriCode = $row['VeriCode'];
		$TimeNote = $row['TimeNote'];
		
		//查找菜单项
		$sql = "SELECT `Name`, `Price`, `Count` " .
				"FROM `OrderItem` WHERE `OrderID`='{$orderid}';";
		$item_rs = $db->query($sql);
		$items = array();
		$total = 0;
		while($item = $item_rs->fetch_assoc() ){
			array_push($items, $item['Name'] . "，" . ($item['Price']+0) . "元x" . $item['Count']);
			$total += ($item['Price']+0) * ($item['Count']+0);
		}
		
		//发送短信给商家
		$content = $_SESSION['session_Setting_SITE_NAME']."到店消费：客户：" .$CustomName."，" .
				"验证码：".$VeriCode ."手机：" . $CustomMobile . "。". implode("；", $items) . "；原价" . $total . "元，" .
				"应收：" . $DiscountTotal . "元；" . $TimeNote . "；留言：" . (empty($Notes) ? "无" : $Notes) ;
		$ids = send_sms($RestaurantMobile, $content, $CustomID);
		if(is_array($ids) && !empty($ids)){
			$sql = "INSERT INTO `OrderSms`(`SmsID`,`CustomID`,`OrderID`,`RestaurantID`,`Restaurant`,`Content`,`SentTime`) " .
					"VALUES('".$ids[0]."','{$CustomID}', '{$orderid}', '{$RestaurantID}', '{$Restaurant}','{$content}','".get_datetime()."')" ;
			$db->query($sql);
			custom_log('订餐', '到店消费订单短信发送给餐馆成功：订单id'.$orderid);
		
			order_process($orderid, 3);
		}
		elseif($ids === false) {
			$sql = "UPDATE `Order` SET `Status`='已取消',`SmsSent`=0, EndTime='".get_datetime()."', `LastUpdate`='".get_datetime()."' WHERE `ID`='{$orderid}';";
			$db->query($sql);
			order_process($orderid, 8,"非常抱歉，未能通知餐馆，本单已自动删除");
			custom_log('订餐', '订单短信发送给餐馆失败：由于手机号码错误，根本就没有发送短信。');
		}
		else {
			$sql = "UPDATE `Order` SET `Status`='已取消',`SmsSent`=0, EndTime='".get_datetime()."', `LastUpdate`='".get_datetime()."' WHERE `ID`='{$orderid}';";
			$db->query($sql);
			order_process($orderid, 8,"非常抱歉，未能通知餐馆，本单已自动删除");
			custom_log('订餐', '订单短信发送给餐馆失败：原因：' + $ids);
		}
		
		//发送短信给客户
		$content = "您可以直接凭短信验证码".$VeriCode."去".$Restaurant."直接消费，" .
				"原价：".$total."元；优惠后：".$DiscountTotal."元" ;
		$ids = send_sms($CustomMobile, $content, $CustomID);
		
		if(is_array($ids) && !empty($ids)){
			$sql = "UPDATE `Order` SET `Status`='成功结束',`SmsSent`=1,`LastUpdate`='".get_datetime()."',`EndTime`='".get_datetime()."' WHERE `ID`='{$orderid}';";
			$db->query($sql);
			custom_log('订餐', '到店消费订单短信发送给客户成功：订单id'.$orderid);
			custom_log('订餐', '到店消费订单成功结束：订单id'.$orderid);
			order_process($orderid, 13);
			order_process($orderid, 7);
			save_customscore($orderid);
			
		}
		elseif($ids === false) {
			custom_log('订餐', '到店消费订单短信发送给客户失败：由于手机号码错误，根本就没有发送短信。');
			order_process($orderid, 14, ':由于手机号码错误，根本就没有发送短信。');
		}
		else {
			custom_log('订餐', '订单短信发送给餐馆失败：原因：' + $ids);
			order_process($orderid, 14, '原因：' + $ids);
		}
	}
	$db->close();
}

function send_orders_verify_sms($orderId) {
	if(empty($_SESSION['session_customMobile'])) {
		header('Location: custom_mobile.php');
		return false;
	}
	
	$code =generate_sms_code();
	
	if(!isset($_SESSION['session_Setting_SITE_NAME'])){
		read_setting();
	}
	//发送短信
	$ids = send_sms($_SESSION['session_customMobile'],"感谢您在".$_SESSION['session_Setting_SITE_NAME']."订单，请在网站输入代码：".$code."，以确认您的订餐。", $_SESSION['session_customid']);
	
	if(is_array($ids) && !empty($ids)){ //发送成功
		$db = db_connect();
		date_default_timezone_set('PRC');
		$expire = date('Y-m-d H:i:s', strtotime('+1 day'));
		$sql = "INSERT INTO `SmsCode`(`Type`,`CustomID`,`Mobile`,`Code`,`Expire`, `OrderID`) " .
				"VALUES(" .
				(empty($_SESSION['session_customMobileVerified']) ? "'手机号码验证及订餐确认'," : "'订餐确认',") .
				"'{$_SESSION['session_customid']}', '{$_SESSION['session_customMobile']}'," .
				"'{$code}', '{$expire}', '{$orderId}')";
		$db->query($sql);
		
		$db->close();
		return true;
	}
	return false;
}

/**
 * 随机创建一个6位的数字作为短信验证码
 */
function generate_sms_code() {
	return rand(100000,999999);
}


/**
 * 验证$_POST["activationCode"]是否是一个有效的手机短信验证码
 * @return boolean 如果通过验证，则返回true，否则返回false
 */
function verify_mobile() {
	$activationCode = addslashes(trim($_POST["activationCode"]));
	if(empty($activationCode)){
		if(!empty($_POST['returnmsg'])){
			echo '{"type":"error", "msg":"验证码为空。"}';
		}
		return false;
	}
	
	$re = false;
	$db = db_connect();
	$sql = "SELECT `ID`,`Type`,`Mobile`,`CustomID`,`OrderID` FROM `SmsCode` WHERE `Code`='{$activationCode}' " .
			"ORDER BY `ID` DESC LIMIT 1;";
	$rs = $db->query($sql);
	if($row = $rs->fetch_assoc()) {//验证成功。
		$sql = "UPDATE `SmsCode` SET `Passed`=1, `PassedTime`='".get_datetime()."' WHERE `ID`='{$row['ID']}';";
		$db->query($sql);
		switch ( $row['Type'] ) {
			case '登录'://TODO 用手机号码登陆，这里怎么办？
				$re = true;
				custom_log('登录', '使用手机验证码登录成功：'.$row['Mobile']);
				set_success_notification('使用手机验证码登录成功。');
				break;
				
			case '手机号码验证':
				check_login();
				$sql = "UPDATE `Custom` SET `Mobile`='{$row['Mobile']}', " .
						"`MobileVerified`=1, `MobileVerifying`=0 " .
						"WHERE `ID`='{$row['CustomID']}'";
				$db->query($sql);
				
				$_SESSION['session_customMobile'] = $row['Mobile'];
				$_SESSION['session_customMobileVerified'] = 1;
				$_SESSION['session_customMobileVerifying'] = 0;
				custom_log('设置', '手机号码验证成功：'.$row['Mobile']);
				if(!empty($_POST['returnmsg'])){
					echo '{"type":"success", "msg":"手机号码验证成功，感谢您的支持！"}';
				}
				else{
					set_success_notification('手机号码验证成功，感谢您的支持！');
				}
				$re = true;
				
				if($_REQUEST['from']=='orders') { //如果来自orders_verifymobile.php，则应该发送信息给餐馆。
					orders_verify_mobile_passed();
				}
				break;
				
			case '订餐确认': //其实已经没有这些了
				check_login();
				$sql = "UPDATE `Order` SET `Status`='客户已确认', " .
						"`CTime`='".get_datetime()."', `COperation`='确认', " .
						"`LastUpdate`='".get_datetime()."' " .
						"WHERE `ID`='{$row['OrderID']}';";
				$db->query($sql);
				custom_log('订餐', '短信验证成功：'.$row['Mobile']);
				if(!empty($_POST['returnmsg'])){
					echo '{"type":"success", "msg":"订餐已确认，餐馆很快将您的订餐送到府上，请等待。"}';
				}
				else {
					set_success_notification('订餐已确认，餐馆很快将您的订餐送到府上，请等待。');
				}
				$_SESSION['session_Order'.$row['OrderID'].'Status'] = '客户已确认';
				order_process($row['OrderID'], 2);
				send_order_to_restaurant($row['OrderID']);
				$re = true;
				break;
				
			case '手机号码验证及订餐确认': //其实已经没有这些了
				check_login();
				$sql = "UPDATE `Custom` SET `Mobile`='{$row['Mobile']}', " .
						"`MobileVerified`=1, `MobileVerifying`=0 " .
						"WHERE `ID`='{$row['CustomID']}'";
				$db->query($sql);
				custom_log('设置', '手机号码验证成功：'.$row['Mobile']);
				
				$_SESSION['session_customMobile'] = $row['Mobile'];
				$_SESSION['session_customMobileVerified'] = 1;
				$_SESSION['session_customMobileVerifying'] = 0;
				
//				$sql = "UPDATE `Order` SET `Status`='客户已确认', " .
//						"`CTime`='".get_datetime()."', `COperation`='确认', " .
//						"`LastUpdate`='".get_datetime()."' " .
//						"WHERE `ID`='{$row['OrderID']}';";
//				$db->query($sql);
				custom_log('订餐', '短信验证成功：'.$row['Mobile']);
				set_success_notification('订单创建成功。');
				$_SESSION['session_Order'.$row['OrderID'].'Status'] = '客户已确认';
//				order_process($row['OrderID'], 2);
				send_order_to_restaurant($row['OrderID']);
				
				$re = true;
				break;
				
			default:
				break;
		}
	}
	elseif(!empty($_POST['returnmsg'])){
		echo '{"type":"error", "msg":"您输入的验证码有误，请重新输入。"}';
	}
	else {
		set_error_notification("您输入的验证码有误，请重新输入。");
	}
	 
	$db->close();
	return true;
}

function orders_verify_mobile_passed() {
	
	check_login();
	$db = db_connect();
	$sql = "SELECT `ID` FROM `Order` WHERE `Status`='等待手机验证' AND `CustomID`='{$_SESSION['session_customid']}';";
	$rs = $db->query($sql);
	$ids = array();
	while ($row = $rs->fetch_assoc()) {
		$id = $row['ID'];
		send_order_to_restaurant($id);
		order_process($id, 5);
		$ids[] = $id;
	}
	file_put_contents("c:/test.txt", "手机号码颜泽哼".count($ids));
	if(!empty($ids)) {
		$sql = "UPDATE `Order` SET `Status`='正在送餐',`CTime`='".get_datetime()."',`COperation`='确认'," .
				"`LastUpdate`='".get_datetime()."'  " .
				"WHERE `ID` IN (".implode(",", $ids).")";
		$db->query($sql);
	}
	
	$db->close();
}


/**
 * 获取到上个订单到现在过去的时间。返回一个“时：分：秒”字符串
 */
function get_last_order_timer() {
	if(empty($_SESSION['session_hasActiveOrder']) || empty($_SESSION['session_lastOrderStartAt'])){
		return "";
	}
	$h = 0; $m = 0; $s = 0;
	$elapsed = time() - $_SESSION['session_lastOrderStartAt'];
	if($elapsed>60*60){
		$h = floor($elapsed/60/60);
		$elapsed = $elapsed - $h*60*60;
	}
	if($elapsed>60){
		$m = floor($elapsed/60);
		$elapsed = $elapsed - $m*60;
	}
	$s = $elapsed;
	
	return str_pad($h, 2, "0", STR_PAD_LEFT) . ":" . str_pad($m, 2, "0", STR_PAD_LEFT) .":" . str_pad($s, 2, "0", STR_PAD_LEFT);
}

/**
 * 获取某个id的订单开始的时间
 */
function get_order_timer($id) {
	if(empty($_SESSION['session_hasActiveOrder']) || empty($_SESSION['session_Order'.$id.'StartAt'])){
		return "";
	}
	$h = 0; $m = 0; $s = 0;
	$elapsed = time() - $_SESSION['session_Order'.$id.'StartAt'];
	if($elapsed>60*60){
		$h = floor($elapsed/60/60);
		$elapsed = $elapsed - $h*60*60;
	}
	if($elapsed>60){
		$m = floor($elapsed/60);
		$elapsed = $elapsed - $m*60;
	}
	$s = $elapsed;
	
	return str_pad($h, 2, "0", STR_PAD_LEFT) . ":" . str_pad($m, 2, "0", STR_PAD_LEFT) .":" . str_pad($s, 2, "0", STR_PAD_LEFT);
}

/**
 * 发送订餐的短信给餐馆
 * @param $orderid:订单id
 */
function send_order_to_restaurant($orderid) {
	if(!isset($_SESSION['session_Setting_SITE_NAME'])){
		read_setting();
	}
	
	$db = db_connect();
	$sql = "SELECT `Restaurant`.`Mobile` AS RestaurantMobile, `Restaurant`.`Name`, " .
			"`Order`.`Mobile` AS CustomMobile, `Order`.`RestaurantID`, " .
			"`Order`.`Address`, `Order`.`Notes`, `Order`.`CustomID` ,`Custom`.`Username` " .
			"FROM `Restaurant`, `Order`, `Custom` " .
			"WHERE `Order`.`ID`='{$orderid}' " .
			"AND `Order`.`RestaurantID`=`Restaurant`.`ID` " .
			"AND `Order`.`CustomID`= `Custom`.`ID` ";
	$rs = $db->query($sql);
	if($row = $rs->fetch_assoc() ) {
		$RestaurantMobile = $row['RestaurantMobile'];
		$Restaurant = $row['Name'];
		$RestaurantID = $row['RestaurantID'];
		$CustomMobile = $row['CustomMobile'];
		$Address = $row['Address'];
		$Notes = $row['Notes'];
		$CustomID = $row['CustomID'];
		$CustomName = $row['Username'];
		
		//准备菜单数据
		$sql = "SELECT `Name`, `Price`, `Count` " .
				"FROM `OrderItem` WHERE `OrderID`='{$orderid}';";
		$item_rs = $db->query($sql);
		$items = array();
		$total = 0;
		while($item = $item_rs->fetch_assoc() ){
			array_push($items, $item['Name'] . "，" . ($item['Price']+0) . "元x" . $item['Count']);
			$total += ($item['Price']+0) * ($item['Count']+0);
		}
		
		//发送短信给餐馆
		$content = $_SESSION['session_Setting_SITE_NAME']."送餐上门：客户：".$CustomName."；地址：" . $Address . "" .
				"；手机：" . $CustomMobile . "。" . implode("；", $items) . "。应收" . $total . "元。" .
				"留言：" . (empty($Notes) ? "无" : $Notes) .
//				"。请回复“1" . $orderid . "”确认订单，回复“2" . $orderid . "”取消订单，如有说明请在数字后面输入。" .
				"";
		$ids = send_sms($RestaurantMobile, $content, $CustomID);
		if(is_array($ids) && !empty($ids)){//发送成功
			$sql = "INSERT INTO `OrderSms`(`SmsID`,`CustomID`,`OrderID`,`RestaurantID`,`Restaurant`,`Content`,`SentTime`) " .
					"VALUES('".$ids[0]."','{$CustomID}', '{$orderid}', '{$RestaurantID}', '{$Restaurant}','{$content}','".get_datetime()."')" ;
			$db->query($sql);
			custom_log('订餐', '订单短信发送给餐馆成功：订单id'.$orderid);
		
//			$sql = "UPDATE `Order` SET `Status`='等待餐馆确认' WHERE `ID`='{$orderid}';";
			$sql = "UPDATE `Order` SET `Status`='正在送餐',`SmsSent`=1,`LastUpdate`='".get_datetime()."'  WHERE `ID`='{$orderid}';";
			$db->query($sql);
//			$_SESSION['session_Order'.$orderid.'Status'] = '等待餐馆确认';
			$_SESSION['session_Order'.$orderid.'Status'] = '正在送餐';
			order_process($orderid, 3);
			order_process($orderid, 5);
		}
		elseif($ids === false) {
			$sql = "UPDATE `Order` SET `Status`='已取消',`SmsSent`=0, EndTime='".get_datetime()."', `LastUpdate`='".get_datetime()."'  WHERE `ID`='{$orderid}';";
			$db->query($sql);
			order_process($orderid, 8,"非常抱歉，未能通知餐馆，本单已自动删除");
			custom_log('订餐', '订单短信发送给餐馆失败：由于手机号码错误，根本就没有发送短信。');
		}
		else {
			$sql = "UPDATE `Order` SET `Status`='已取消',`SmsSent`=0, EndTime='".get_datetime()."', `LastUpdate`='".get_datetime()."'  WHERE `ID`='{$orderid}';";
			$db->query($sql);
			order_process($orderid, 8,"非常抱歉，未能通知餐馆，本单已自动删除");
			custom_log('订餐', '订单短信发送给餐馆失败：原因：' + $ids);
		}
	}
	$db->close();
}

/**
 * 返回我的当前订单信息（同时设置了有关Session项）。返回形式如下：
 * array(
 * 	[0] => array(
 * 		"ID" => 123,
 * 		"Restaurant" => "餐馆名称",
 * 		"CreateTime" => "23:10:58",
 * 		"Telephone" => "餐馆电话号码",
 * 		"Mobile" => "客户手机号码",
 * 		"Address" => "地址",
 * 		"Notes" => "要求",
 * 		"Status" => "状态",
 * 		"total" => 合计金额,
 * 		"dishes" => array(
 * 			[0] => array("Name" => "餐品名称", "Price"=>价格, "Count"=>数量),
 * 			[1] => array("Name" => "餐品名称", "Price"=>价格, "Count"=>数量),
 * 			...
 * 		)
 * 	)
 * 	[1] => array(
 * 		...
 * 	)
 * 	...
 * )
 */
function get_my_active_orders() {
	check_login();
	
	$re = array();
	$db = db_connect();
	
	$sql = "SELECT `Order`.`ID`, `Order`.`RestaurantID`, `Restaurant`.`Name` as Restaurant, " .
			"`Restaurant`.`Telephone`, `Order`.`Mobile`, `Order`.`Address`, `Order`.`Notes`, " .
			"UNIX_TIMESTAMP(`Order`.`CreateTime`) AS CreateTime, `Order`.`Status` " .
			"FROM `Order`, `Restaurant` " .
			"WHERE `Order`.`CustomID`='{$_SESSION['session_customid']}' " .
			"AND `Order`.`RestaurantID`=`Restaurant`.`ID` " .
			"AND `Order`.`Status`<>'已取消' AND `Order`.`Status`<>'成功结束' " .
			"ORDER BY `Order`.`ID` ASC; ";
//	echo $sql . "\n===================================\n";
	$rs = $db->query($sql);
	while( $row = $rs->fetch_assoc() ) { //有活动订单
		$_SESSION['session_hasActiveOrder'] = 1;
		$_SESSION['session_lastOrderStartAt'] = $row['CreateTime'];;
		$_SESSION['session_Order'.$row['ID'].'StartAt'] = $row['CreateTime'];
		$_SESSION['session_Order'.$row['ID'].'Status'] = $row['Status'];
		$_SESSION['session_hasFailedOrder'] = ($row['Status']=='自动删除') ? 1 : 0;
		
		$dishes = array();
		$total = 0;
		$sql = "SELECT `Name`, `Price`, `Count` FROM `OrderItem` WHERE `OrderID`='{$row['ID']}'";
		$dish_rs = $db->query($sql);
		while($dish_row = $dish_rs->fetch_assoc() ) {
			$dish = array(
				"Name" => $dish_row['Name'],
				"Price" => $dish_row['Price'] + 0,
				"Count" => $dish_row['Count'] + 0
			);
			array_push($dishes, $dish);
			$total += ($dish_row['Price'] + 0) * ($dish_row['Count'] + 0);
		}
		
		$order = array(
	 		"ID" => $row['ID'],
	 		"Restaurant" => $row['Restaurant'],
	 		"CreateTime" => get_order_timer($row['ID']),
	 		"Telephone" => $row['Telephone'],
	 		"Mobile" => $row['Mobile'],
	 		"Address" => $row['Address'],
	 		"Notes" => $row['Notes'],
	 		"Status" => $row['Status'],
	 		"total" => $total,
	 		"dishes" => $dishes
		);
		
		array_push($re, $order);
	}
	
	if(empty($re)) { //没有活动订单
		$_SESSION['session_hasActiveOrder'] = 0;
		$_SESSION['session_hasFailedOrder'] = 0;
	}
	
	$db->close();
	return $re;
}

/**
 * 获取当前活动订单的处理情况，返回格式(JSON)：
 *[
 * 	{
 		"id" : 订单id,
 		"progress" : [
 		{
 			"id" : 处理记录id,
 			"activity" : "处理说明",
 			"type" : 处理类型码,
 			"timestamp" : "21:44:43"
 		},
 		{
 			"id" : 处理记录id,
 			"activity" : "处理说明",
 			"type" : 处理类型码,
 			"timestamp" : "21:44:43"
 		},
		...
 		]
 	}
 	...
 *]
 */
function get_order_progress() {
	check_login();
	
//	receive_sms();
	
	process_long_time();
	
	$db = db_connect();
	
	$sql = "SELECT `OrderProcess`.`ID`, `OrderProcess`.`OrderID`, `OrderProcess`.`Type`, " .
			"`OrderProcess`.`Time`, `OrderProcess`.`Activity` " .
			"FROM `OrderProcess`, `Order` " .
			"WHERE `Order`.`ID`=`OrderProcess`.`OrderID` " .
			"AND `Order`.`CustomID`={$_SESSION['session_customid']} " .
			"AND (`Order`.`Status`<>'已取消' AND `Order`.`Status`<>'成功结束') " .
			"ORDER BY `OrderProcess`.`OrderID` DESC, `OrderProcess`.`ID` ASC";
	$rs = $db->query($sql);
	
	$cur_order = "";
	$orders = array();
	$cur_order_added = true;
	$processes = array();
	while($row = $rs->fetch_assoc()) {
		if($row['OrderID']!=$cur_order) {
			if(!$cur_order_added){
				$order = '
					{
						"id":'.$cur_order.',
						"progress":
						['
							.implode(",", $processes).
						']
					}';
				array_push($orders, $order);
				$cur_order_added = true;
			}
			$cur_order = $row['OrderID'];
			$processes = array();
			$cur_order_added = false;
		}
		$process = ' 
		{
			"id":'.$row["ID"].',
			"activity":"'.$row["Activity"].'",
			"type":'.$row["Type"].',
			"timestamp":"'.substr($row["Time"], -8, 8).'"
		}';
		array_push($processes, $process);
	}
	
	if(!$cur_order_added){
		$order = '
			{
				"id":'.$cur_order.',
				"progress":
				['
					.implode(",", $processes).
				']
			}';
		array_push($orders, $order);
	}
	$db->close();
	return '['.implode(",", $orders).']';
}

/**
 * 接收短信并分析商家的反馈。
 */
function receive_sms() {
	$db = db_connect();
	$sql = "SELECT `Value` FROM `Setting` WHERE `Property`='LAST_TIME_RECEIVE_SMS'";
	$rs = $db->query($sql);
	if($row = $rs->fetch_assoc()){
		$lastTime = $row['Value'];
		if(time() - $lastTime < 60) { //每隔60秒处理一次
			$db->close();
			return;
		}
	}
	
	$sql = "UPDATE `Setting` SET `Value`='".time()."' WHERE `Property`='LAST_TIME_RECEIVE_SMS'";
	$db->query($sql);
	
	if(!isset($_SESSION['session_Setting_SMS_receive_url']) 
		|| !isset($_SESSION['session_Setting_SMS_userid']) 
		|| !isset($_SESSION['session_Setting_SMS_account']) 
		|| !isset($_SESSION['session_Setting_SMS_password']) )
	{
		read_setting();
	}
	
	$url=$_SESSION['session_Setting_SMS_receive_url'];  
	$id = urlencode($_SESSION['session_Setting_SMS_userid']);
	$account = urlencode($_SESSION['session_Setting_SMS_account']);
	$pwd = urlencode($_SESSION['session_Setting_SMS_password']);
	$postFields = "action=query&userid=".$id."&account=".$account."&password=".$pwd;
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
	
	//proxy for test
	curl_setopt($ch, CURLOPT_PROXYTYPE, 'HTTP');
	curl_setopt($ch, CURLOPT_PROXY, '174.139.255.194');
	curl_setopt($ch, CURLOPT_PROXYPORT, 80);
	
	$response = curl_exec($ch);
	curl_close($ch);
		
	if(!empty($response)) {
		$result = simplexml_load_string($response);
		$result->message;
		
		$re = null;	
		if($result->errorstatus){//接收失败
		}
		else {
			foreach($result->callbox as $callbox){
				process_receive_sms($callbox->mobile, $callbox->taskid, $callbox->content, $callbox->receivetime);
			}
		}
	}
	
	$db->close();
}

/**
 * 处理一条接收到的短信
 */
function process_receive_sms($mobile, $taskid, $content, $receivetime) {	
	//首先分析内容
	if(preg_match("/^(1|2)\d+/", $content)) { //格式符合
		$db = db_connect();
		
		$op = substr($content, 0, 1);
		$orderid = substr($content, 1)+0;
		$text = substr($content, strlen($content+0));
		
		//检查是否确实有该订单
		$sql = "SELECT `Order`.`ID` FROM `Order`, `Restaurant` " .
				"WHERE `Order`.`ID`='{$orderid}' " .
				"AND `Order`.`Status`='等待餐馆确认' " .
				"AND `Order`.`RestaurantID`=`Restaurant`.`ID` " .
				"AND `Restaurant`.`Mobile`='{$mobile}'";
		$rs = $db->query($sql);
		if(!$rs->fetch_assoc()) {
			$db->close();
			return;
		}
		
		//接收到的短信插入数据库中的ReceivedSms表
		$sql = "INSERT INTO `ReceivedSms`(`Mobile`,`Content`,`ReceiveTime`," .
				"`ReferenceID`,`OrderID`,`Operation`,`Text`) " .
				"VALUES('{$mobile}', '{$content}', '{$receivetime}', " .
				"'{$taskid}', '{$orderid}', '{$op}', '{$text}')";
		$db->query($sql);
		
		if($op == "1"){ //确认订单
			$sql = "UPDATE `Order` SET `Status`='正在送餐', " .
					"`RTime`='".get_datetime()."', `ROperation`='确认', " .
					"`RText`='{$text}',`LastUpdate`='".get_datetime()."'  " .
					"WHERE `ID`='{$orderid}';";
			$db->query($sql);
			order_process($orderid, 4, $text);
			order_process($orderid, 5);
		}
		else { //取消订单
			$sql = "UPDATE `Order` SET `Status`='自动删除', " .
					"`RTime`='".get_datetime()."', `ROperation`='取消', " .
					"`RText`='{$text}',`LastUpdate`='".get_datetime()."' ,`EndTime`='".get_datetime()."'  " .
					"WHERE `ID`='{$orderid}';";
			$db->query($sql);
			order_process($orderid, 11, $text);
		}
		
		$db->close();
	}
}

/**
 * 处理长时间没有响应的订单
 */
function process_long_time() {
	check_login();
	$db = db_connect();
	
	if(//!isset($_SESSION['session_Setting_TIME_FOR_LONG_RESPONSE']) ||
	!isset($_SESSION['session_Setting_TIME_FOR_LONG_CONFIRM']) ||
	!isset($_SESSION['session_Setting_TIME_FOR_LONG_NORECEIVE']) ) {
		read_setting();
	}
	
	$sql = "SELECT `ID` FROM `Order` WHERE (`Status`='等待手机验证' OR `Status`='创建') AND " .
			"UNIX_TIMESTAMP('".get_datetime()."')-UNIX_TIMESTAMP(`CreateTime`)>".($_SESSION['session_Setting_TIME_FOR_LONG_CONFIRM']+0)."*60 " . //
			"AND `CTime` IS NULL " .
			"AND `CustomID`='{$_SESSION['session_customid']}'";

	$rs = $db->query($sql);
	$ids = array();
	while($row = $rs->fetch_row()) {
		array_push($ids, $row[0]);
		$_SESSION['session_Order'.$row[0].'Status'] = '自动删除';
		$_SESSION['session_hasFailedOrder'] = 1;
	}
	
	if(!empty($ids)){
		$idset = implode(",", $ids);
		$sql = "UPDATE `Order` SET `Status`='自动删除', `EndTime`='".get_datetime()."' , `LastUpdate`='".get_datetime()."' WHERE `ID` IN (".$idset.")";
		$db->query($sql);
	}
	foreach( $ids as $id ) {
		order_process($id, 9);
		custom_log('取消订单', '订单由于客户长时间没有确认而自动取消：订单ID：'.$id);
	}
	
//	$sql = "SELECT `ID` FROM `Order` WHERE `Status`='等待餐馆确认' AND " .
//			"UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(`CTime`)>".($_SESSION['session_Setting_TIME_FOR_LONG_RESPONSE']+0)."*60 " . //
//			"AND  `RTime` IS NULL " .
//			"AND `CustomID`='{$_SESSION['session_customid']}'";
//	$rs = $db->query($sql);
//	$ids = array();
//	while($row = $rs->fetch_row()) {
//		array_push($ids, $row[0]);
//	}
//	
//	if(!empty($ids)){
//		$idset = implode(",", $ids);
//		$sql = "UPDATE `Order` SET `Status`='无法完成' WHERE `ID` IN (".$idset.")";
//		$db->query($sql);
//	}
//	foreach( $ids as $id ) {
//		order_process($id, 10);
//		custom_log('取消订单', '订单由于餐馆长时间没有确认而自动取消：订单ID：'.$id);
//	}
//
	//处理长时间没有确认送餐的“正在送餐”订单$
	date_default_timezone_set('PRC');
	$unixTime=time();
	$sql = "SELECT `ID` FROM `Order` WHERE `Status`='正在送餐' AND ". //"`COperation`='确认' AND " .
			"UNIX_TIMESTAMP('".get_datetime()."')-UNIX_TIMESTAMP(`CreateTime`)>".($_SESSION['session_Setting_TIME_FOR_LONG_NORECEIVE']+0)."*60 " . //正在送餐的订单，如果超过TIME_FOR_LONG_NORECEIVE分钟，则自动转为成功结束
			"AND `CustomID`='{$_SESSION['session_customid']}'";
//	echo $sql;//jingyifei
	$rs = $db->query($sql);
	$ids = array();
	while($row = $rs->fetch_row()) {
		array_push($ids, $row[0]);
	}
	
	if(!empty($ids)){
		$idset = implode(",", $ids);
		$sql = "UPDATE `Order` SET `Status`='成功结束',`EndTime`='".get_datetime()."',`LastUpdate`='".get_datetime()."'   WHERE `ID` IN (".$idset.")";
		$db->query($sql);
	}
	
	foreach( $ids as $id ) {
		order_process($id, 12);
		save_customscore($id);
		custom_log('确认送餐', '由于送餐后长时间没有确认收到送餐，本单已自动成功结束：订单ID：'.$id);
	}
	
	//处理长时间“自动删除”订单，将其变成已取消
	$sql = "SELECT `ID` FROM `Order` WHERE `Status`='自动删除' AND " .
			"UNIX_TIMESTAMP('".get_datetime()."')-UNIX_TIMESTAMP(`LastUpdate`)>24*60*60 " . //自动删除的订单，如果超过24小时，则自动转为已取消
			"AND  `RTime` IS NULL " .
			"AND `CustomID`='{$_SESSION['session_customid']}'";
	$rs = $db->query($sql);
	$ids = array();
	while($row = $rs->fetch_row()) {
		array_push($ids, $row[0]);
	}
	
	if(!empty($ids)){
		$idset = implode(",", $ids);
		$sql = "UPDATE `Order` SET `Status`='已取消',`EndTime`='".get_datetime()."',`LastUpdate`='".get_datetime()."'   WHERE `ID` IN (".$idset.")";
		$db->query($sql);
	}
	foreach( $ids as $id ) {
		order_process($id, 8, "自动删除的订单由于过期超过24小时，自动转为已取消状态。");
		custom_log('取消订单', '自动删除的订单由于过期超过24小时，自动转为已取消状态：订单ID：'.$id);
	}
	
	$db->close();
}

/**
 * 短信催单
 */
function orders_urge() {
	check_login();
	$orderId = addslashes(trim($_GET["orderId"]));
	if(empty($orderId)) return;
	$db  = db_connect();
	$sql = "SELECT `Restaurant`.`Mobile`, `Order`.`Mobile` AS CustomMobile, `Order`.`Address` " .
			"FROM `Order`, `Restaurant` " .
			"WHERE `Order`.`ID`='{$orderId}' " .
			"AND `Order`.`RestaurantID` = `Restaurant`.`ID` " .
			"AND `Order`.`Urged`=0 " .
			"AND (`Order`.`Status`='客户已确认' OR `Order`.`Status`='等待餐馆确认' OR `Order`.`Status`='正在送餐' )";
	$rs = $db->query($sql);
	if ($row = $rs->fetch_assoc()) {
		$mobile = $row['Mobile'];
		$content = '客户催单，请尽快处理。客户：' . $row['CustomMobile'] . '，地址：' . $row['Address'];
		send_sms($mobile, $content, $_SESSION['session_customid']);
		
		$sql = "UPDATE `Order` SET `Urged`=1,`LastUpdate`='".get_datetime()."'  WHERE `ID`='{$orderId}'; ";
		$db->query($sql);
	}
	set_success_notification('已经发短信催促餐馆，请耐心等待。');
	
	custom_log('订餐', '客户催单：订单ID：'.$orderId);
	$db->close();
}

/**
 * 已收到餐的处理
 */
function orders_arrive() {
	check_login();
	$orderId = addslashes(trim($_GET["orderId"]));
	if(empty($orderId)) return;
	$db  = db_connect();
	
	$re = false;
	$sql = "UPDATE `Order` SET `Status`='成功结束', `EndTime`='".get_datetime()."', " .
			"`LastUpdate`='".get_datetime()."'  " .
			"WHERE `ID`='{$orderId}' ";
	$db->query($sql);
	if($db->result!==false){
		if($db->affected_rows > 0) {
			set_success_notification('订单已成功结束，请享用您的美餐，感谢您的支持。');
			custom_log('确认送餐', '订单成功结束：订单ID：'.$orderId);
			$re = true;
			order_process($orderId, 6);
			order_process($orderId, 7);
			save_customscore($orderId);
		}
	}
	else{
		custom_log('确认送餐', '客户确认送餐失败，数据库操作失败：订单ID：'.$orderId);
	}
	$db->close();
	return $re;
}

function get_dingcanscore(){
	$db = dao ();
	$renum=0;
	$re = null;
	$sql = "select * from scorereg";
	$result = $db->query ( $sql );
	if ($row = $result->fetch_assoc ()) {
			$re = $row;
	}
	$renum=$re['dingcanscore'];
	return $renum;
	
}



function get_totalprice($orderid){
	$db = dao ();
	$re = null;
	$totalprice=0;
	$sql = "select * from `order` where  id=" . $orderid;
	$result = $db->query ( $sql );
	if ($row = $result->fetch_assoc ()) {
			$re = $row;
	}
	$totalprice=$re['DiscountTotal'];
	return $totalprice;
}

function save_customscore($orderid)
{
	
	$db = dao ();
	$totalscore=0;
	$totalmoney=0;
	$score=0;
	$re=null;
	$cid = $_SESSION['session_customid'];
	$myscore=getMyScore();
	if($myscore!=null)
		$score=$score + $myscore['score'];
	$totalmoney=get_totalprice($orderid);
	$totalscore = floor($totalmoney * get_dingcanscore()/100) + $score;
	if($myscore!=null){
		$sql = "UPDATE `customscore` SET `score`='".$totalscore."' ".
			"WHERE `customid`='{$cid}' ";
		
	}
	else {
		$sql = "INSERT INTO `customscore`(`customid`,`score`) " .
					"VALUES('{$cid}', '{$totalscore}')" ;
	}
	$db->query($sql);
}



/**
 * 订单取消的处理
 */
function orders_cancel() {
	check_login();
	$orderId = addslashes(trim($_GET["orderId"]));
	if(empty($orderId)) return;
	$db  = db_connect();
	
	$sql = "UPDATE `Order` SET `Status`='已取消', `CTime`='".get_datetime()."', `COperation`='取消', " .
			"`EndTime`='".get_datetime()."',`LastUpdate`='".get_datetime()."'  " .
			"WHERE `ID`='{$orderId}' " .
			"AND (`Status`='创建' OR `Status`='等待手机验证' OR `Status`='自动删除')";
	$db->query($sql);
	if($db->result!==false){
		if($db->affected_rows > 0) {
			set_success_notification('订单已取消。');
			custom_log('取消订单', '客户主动取消订单成功：订单ID：'.$orderId);
			order_process($orderId, 8);
		}
		else {
			set_error_notification('订单已无法取消。');
			custom_log('取消订单', '客户主动取消订单失败，影响行数为0：订单ID：'.$orderId);
		}
	}
	else{
		custom_log('取消订单', '客户主动取消订单失败，数据库操作失败：订单ID：'.$orderId);
	}
	$db->close();
}


/**
 * 获取历史订单数据，返回数组用于custom_orders_list.php：
 * array(
 * 	0 => array(
 * 		"ID" => 订单id
 * 		"CreateTime" => "订单创建时间"
 * 		"RestaurantID" => 餐馆ID	
 * 		"Restaurant" => "餐馆名称"
 * 		"Total" => "总价"（如果最后取消了，则为“-”）
 * 		"Status" => "状态"
 * 	)
 * 	...
 * )
 * 
 */
function get_history_orders_list() {
	check_login();
	
	$db = db_connect();
	$sql = "SELECT `Order`.`ID`, `Order`.`CreateTime`, `Order`.`RestaurantID`, " .
			"`Restaurant`.`Name` AS Restaurant, `Order`.`Total`, `Order`.`Status` " .
			"FROM `Order`, `Restaurant`" .
			"WHERE `Order`.`CustomID`='{$_SESSION['session_customid']}' " .
			"AND (`Order`.`Status`='已取消' OR `Order`.`Status`='成功结束') " .
			"AND `Order`.`RestaurantID`=`Restaurant`.`ID` " .
			"ORDER BY `Order`.`ID` ASC ";
			
	if (isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
	
	$re = array();
	$rs = $db->query($sql);
	while($row = $rs->fetch_assoc()) {
		$order = array(
			"ID" => $row['ID'],
	 		"CreateTime" => $row['CreateTime'],
	 		"RestaurantID" => $row['RestaurantID'],
	 		"Restaurant" => $row['Restaurant'],
	 		"Total" => $row['Status']=='已取消' ? "-" : $row['Total'],
	 		"Status" => $row['Status']
		);
		array_push($re, $order);
	}
	
	$db->close();
	return $re;
}

/**
 * 根据$_GET['id']获取指定id的订单详细情况，供oders_show.php使用。返回格式如下
 * array(
 * 		"ID" => 123,
 * 		"Restaurant" => "餐馆名称",
 * 		"Telephone" => "餐馆电话号码",
 * 		"Mobile" => "客户手机号码",
 * 		"Address" => "地址",
 * 		"Notes" => "要求",
 * 		"Status" => "状态",
 * 		"total" => 合计金额,
 * 		"dishes" => array(
 * 			[0] => array("Name" => "餐品名称", "Price"=>价格, "Count"=>数量),
 * 			[1] => array("Name" => "餐品名称", "Price"=>价格, "Count"=>数量),
 * 			...
 * 		),
 * 		"process" => array(
 * 			[0] => array(
 * 				"id" => 处理记录id,
 * 				"activity" => "处理说明",
 * 				"type" => 处理类型码,
 * 				"timestamp" => "21:44:43"
 *			)
 *			...
 * 		)
 * 	)
 */
function get_order_info () {
	check_login();
	
	$id = addslashes(trim($_GET["id"]));
	if(empty($id)) return array();
	
	$order = array();
	$db = db_connect();
	
	$sql = "SELECT `Order`.`ID`, `Order`.`RestaurantID`, `Restaurant`.`Name` as Restaurant, " .
			"`Restaurant`.`Telephone`, `Order`.`Mobile`, `Order`.`Address`, " .
			"`Order`.`Notes`, `Order`.`Status` " .
			"FROM `Order`, `Restaurant` " .
			"WHERE `Order`.`ID`='{$id}' " .
			"AND `Order`.`CustomID`='{$_SESSION['session_customid']}' " .
			"AND `Order`.`RestaurantID`=`Restaurant`.`ID` ";
	$rs = $db->query($sql);
	if( $row = $rs->fetch_assoc() ) {
		$dishes = array();
		$total = 0;
		$sql = "SELECT `Name`, `Price`, `Count` FROM `OrderItem` WHERE `OrderID`='{$row['ID']}'";
		$dish_rs = $db->query($sql);
		while($dish_row = $dish_rs->fetch_assoc() ) {
			$dish = array(
				"Name" => $dish_row['Name'],
				"Price" => $dish_row['Price'] + 0,
				"Count" => $dish_row['Count'] + 0
			);
			array_push($dishes, $dish);
			$total += ($dish_row['Price'] + 0) * ($dish_row['Count'] + 0);
		}
		
		$process = array();
		$sql = "SELECT `ID`, `OrderID`, `Type`, `Time`, `Activity` " .
				"FROM `OrderProcess` " .
				"WHERE `OrderID`='{$id}' " .
				"ORDER BY `ID` ASC";
		$process_rs = $db->query($sql);
		while($process_row = $process_rs->fetch_array() ){
			$p = array(
 				"id" => $process_row['ID'],
 				"activity" => $process_row['Activity'],
 				"type" => $process_row['Type'] + 0,
 				"timestamp" => $process_row['Time']
			);
			array_push($process, $p);
		}
	
		
		$order = array(
	 		"ID" => $row['ID'],
	 		"Restaurant" => $row['Restaurant'],
	 		"Telephone" => $row['Telephone'],
	 		"Mobile" => $row['Mobile'],
	 		"Address" => $row['Address'],
	 		"Notes" => $row['Notes'],
	 		"Status" => $row['Status'],
	 		"total" => $total,
	 		"dishes" => $dishes,
	 		"process" => $process
		);
	}
	
	$db->close();
	return $order;
}

//////////////////////////////////以下为私有函数//////////////////////////////


/**
 * 发送短信，并将有关结果写入数据库中
 * @return mix 如果根本就没有发送，则返回false，如果已经发送，但是发送失败，则返回失败原因，否则返回短信的数据库id号的数组
 */
function send_sms($receivers,$content, $customIds=null){
	if(!is_array($receivers)) $receivers = array($receivers);
	if(!empty($customIds) && !is_array($customIds)) $customIds = array($customIds);

	if(!empty($customIds) && count($customIds)!=count($receivers)) return false;

	if(!isset($content)) return false;
	
	if(empty($_SESSION['session_Setting_SITE_NAME'])) {
		read_setting();
	}
	$content .= "【".$_SESSION['session_Setting_SITE_NAME']."】";

	//创建数据库记录
	$db = db_connect();
	$ids = array();
	$delete_indexes = array();
	foreach($receivers as $index => $receiver) {
		if(is_mobile_number($receiver)) {
			$sql = "INSERT INTO `Sms`(`Receiver`, `Content`, `CustomID`, `SentTime`) " .
					"VALUES('{$receiver}', '{$content}', " .
					((empty($customIds) || empty($customIds[$index])) ? "NULL" : "'{$customIds[$index]}'") .
					", '".get_datetime()."')";
			$db->query($sql);
			if($db->result!==false){
				array_push($ids, $db->insert_id());
			}
			else { //插入数据库失败，将有关记录删除
				array_unshift($delete_indexes, $index);
			}
		}
		else {//不是有效的手机号码，将有关记录删除
			array_unshift($delete_indexes, $index);
		}
	}

	foreach($delete_indexes as $delete_index) {
		array_splice($receivers, $delete_index, 1);
		if(!empty($customIds)){
			array_splice($customIds, $delete_index, 1);
		}
	}

	if(empty($receivers)){
		$db->close();
		return false;
	}

	if(!isset($_SESSION['session_Setting_SMS_platform'])) {
		$sql = "SELECT `Property`,`Value` FROM `Setting` WHERE `Property` LIKE 'SMS_%'";
		$rs = $db->query($sql);
		while( $row = $rs->fetch_assoc() ) {
			$_SESSION['session_Setting_'.$row['Property']] = $row['Value'];
		}
	}
	$db->close();
	custom_log('订餐', '发送短信前');
	
	if($_SESSION['session_Setting_SMS_platform']=='企信') {
		custom_log('订餐', '开始发送企信短信');
		return send_qixin_sms($receivers, $content, $ids);
	}
	else {
		custom_log('订餐', '开始发送亿美短信');
		return send_emay_sms($receivers, $content, $ids);
	}
}


function get_emay_client() {
	$gwUrl = 'http://sdkhttp.eucp.b2m.cn/sdk/SDKService?wsdl';
	$serialNumber = $_SESSION['session_Setting_SMS_EMY_softwareSerialNo'];
	$password = $_SESSION['session_Setting_SMS_EMY_password'];
	$sessionKey = get_emay_session_key();
	$connectTimeOut = 2;
	$readTimeOut = 10;
	$proxyhost = false;
	$proxyport = false;
	$proxyusername = false;
	$proxypassword = false;

	$client = new EmayClient($gwUrl,$serialNumber,$password,$sessionKey,$proxyhost,$proxyport,$proxyusername,$proxypassword,$connectTimeOut,$readTimeOut);
	$client->setOutgoingEncoding("UTF-8");
	return $client;
}

function get_emay_session_key() {
	$re = "";
	if(empty($_SESSION['session_Setting_SMS_EMY_sessionkey'])) {
		die("请配置好亿美短信平台，然后关掉浏览器重试。本错误只在网站还没有配置好亿美短信平台时出现，配置好后，客户不会看到此提示。");
	}
	else {
		$re = $_SESSION['session_Setting_SMS_EMY_sessionkey'];
	}
	return $re;
}

function send_emay_sms($receivers, $content, $ids) {
	$db = db_connect();
	custom_log('订餐', '发送亿美短信...');
	if(!isset($_SESSION['session_Setting_SMS_EMY_softwareSerialNo'])
			|| !isset($_SESSION['session_Setting_SMS_EMY_password'])
			|| !isset($_SESSION['session_Setting_SMS_EMY_sessionkey']) )
	{
	custom_log('订餐', '发送亿美短信...session为空');
		$sql = "SELECT `Property`,`Value` FROM `Setting` WHERE `Property` LIKE 'SMS_%'";
		$rs = $db->query($sql);
		while( $row = $rs->fetch_assoc() ) {
			$_SESSION['session_Setting_'.$row['Property']] = $row['Value'];
		}
	}

	$client = get_emay_client();
	$statusCode = $client->sendSMS($receivers, $content);

	if ($statusCode!=null && $statusCode=="0"){
		//更新数据库中的有关记录
		$remain = $client->getBalance();
		foreach($ids as $id){
			$sql = "UPDATE `Sms` SET `RecvTime`='".get_datetime()."', `Success`=1, " .
					"`ReturnStatus`='{$statusCode}', `Result`='发送成功', " .
					"`ReferenceID`='', `Status`='已发送',`Remain`='{$remain}' " .
					"WHERE `ID`='{$id}'";
			$db->query($sql);
		}
		$db->close();
		return $ids;
	}
	else {
		$msg = get_emay_error($statusCode);
		$remain = $client->getBalance();
		//更新数据库中的有关记录
		foreach($ids as $id){
			$sql = "UPDATE `Sms` SET `RecvTime`='".get_datetime()."', `Success`=0, " .
					"`ReturnStatus`='{$statusCode}', `Result`='{$msg}', " .
					"`ReferenceID`='', `Status`='失败',`Remain`='{$remain}' " .
					"WHERE `ID`='{$id}'";
			$db->query($sql);
		}
		$db->close();
		return $msg;
	}
}

function get_emay_error($code) {
	switch($code + 0) {
		case 0	: return "";
		case 17	: return "发送信息失败";
		case 18	: return "发送定时信息失败";
		case 101: return "客户端网络故障";
		case 305: return "服务器端返回错误，错误的返回值（返回值不是数字字符串）";
		case 307: return "目标电话号码不符合规则，电话号码必须是以0、1开头";
		case 997: return "平台返回找不到超时的短信，该信息是否成功无法确定";
		case 998: return "由于客户端网络问题导致信息发送超时，该信息是否成功下发无法确定";
		default	: return "未知错误，错误号：" . $code;
	}
}

function send_qixin_sms($receivers, $content, $ids) {
	$db = db_connect();
	if(!isset($_SESSION['session_Setting_SMS_url'])
			|| !isset($_SESSION['session_Setting_SMS_userid'])
			|| !isset($_SESSION['session_Setting_SMS_account'])
			|| !isset($_SESSION['session_Setting_SMS_password']) )
	{
		$sql = "SELECT `Property`,`Value` FROM `Setting` WHERE `Property` LIKE 'SMS_%'";
		$rs = $db->query($sql);
		while( $row = $rs->fetch_assoc() ) {
			$_SESSION['session_Setting_'.$row['Property']] = $row['Value'];
		}
	}

	$strReceivers = implode(",", $receivers);
	$url=$_SESSION['session_Setting_SMS_url'];
	$id = urlencode($_SESSION['session_Setting_SMS_userid']);
	$account = urlencode($_SESSION['session_Setting_SMS_account']);
	$pwd = urlencode($_SESSION['session_Setting_SMS_password']);
	$to = urlencode($strReceivers);
	$postFields = "action=send&userid=".$id."&account=".$account."&password=".$pwd."&mobile=".$strReceivers."&content=".$content."&sendTime=";

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
	curl_setopt($ch, CURLOPT_TIMEOUT, 29*60);

	//	//proxy for test
	//	curl_setopt($ch, CURLOPT_PROXYTYPE, 'HTTP');
	//	curl_setopt($ch, CURLOPT_PROXY, '174.139.255.194');
	//	curl_setopt($ch, CURLOPT_PROXYPORT, 80);

	$response = curl_exec($ch);
	

	if(empty($response) || curl_errno($ch)!=0) {
		//更新数据库中的有关记录
		$msg = curl_error($ch);
		foreach($ids as $id){
			$sql = "UPDATE `Sms` SET `RecvTime`='".get_datetime()."', `Success`=0, " .
					"`ReturnStatus`='连接失败', `Result`='连接失败：{$msg}', " .
					"`ReferenceID`='', `Status`='失败',`Remain`='' " .
					"WHERE `ID`='{$id}'";
			$db->query($sql);
		}
		$db->close();
		return $msg;
	}

	//分析返回结果
	$result = @simplexml_load_string($response);

	if($result === FALSE){//返回结果不能分析成为XML文件
		//更新数据库中的有关记录
		$msg = "短信平台的返回不是一个有效xml文件。";
		foreach($ids as $id){
			$sql = "UPDATE `Sms` SET `RecvTime`='".get_datetime()."', `Success`=0, " .
					"`ReturnStatus`='短信平台返回格式有误。', `Result`='".substr($response,0,200)."', " .
					"`ReferenceID`='', `Status`='失败',`Remain`='' " .
					"WHERE `ID`='{$id}'";
			$db->query($sql);
		}
		$db->close();
		return $msg;
	}

	$re = null;
	if($result->returnstatus=='Success'){//发送成功
		//更新数据库中的有关记录
		foreach($ids as $id){
			$sql = "UPDATE `Sms` SET `RecvTime`='".get_datetime()."', `Success`=1, " .
					"`ReturnStatus`='{$result->returnstatus}', `Result`='发送成功', " .
					"`ReferenceID`='{$result->taskID}', `Status`='已发送',`Remain`='{$result->remainpoint}' " .
					"WHERE `ID`='{$id}'";
			$db->query($sql);
		}
		$re = $ids;
	}
	else {
		$msg = $result->message;
		//更新数据库中的有关记录
		foreach($ids as $id){
			$sql = "UPDATE `Sms` SET `RecvTime`='".get_datetime()."', `Success`=0, " .
					"`ReturnStatus`='{$result->returnstatus}', `Result`='{$msg}', " .
					"`ReferenceID`='{$result->taskID}', `Status`='失败',`Remain`='{$result->remainpoint}' " .
					"WHERE `ID`='{$id}'";
			$db->query($sql);
		}
		$re = $msg;
	}

	$db->close();
	curl_close($ch);
	return $re;
}

function order_process($orderid, $type, $text = null) {
	if($type>14 || $type<1) return;
	$activity = array(
		"",
		"订单创建",
		"订单确认",
		"已通知餐馆",
		"餐馆已确认",
		"餐馆正在处理您的订单…",
		"已收到餐",
		"成功结束",
		"已取消",
		"（自动）很抱歉，由于长时间未验证手机号码，本单已自动删除",
		"（自动）很抱歉，由于餐馆长时间未确认订单，本单已自动删除",
		"很抱歉，由于餐馆无法处理您的订餐，本单已自动删除",
		"（自动）由于送餐后长时间没有确认收到送餐，本单已自动成功结束",
		"已发送验证码给客户",
		"发送验证码给客户失败"
	);
	$at = $activity[$type] . (empty($text) ? "" : "：".$text);
	$db = db_connect();
	$sql = "INSERT INTO `OrderProcess`(`OrderID`, `Type`, `Activity`, `Time`) " .
			"VALUES('{$orderid}', '{$type}', '{$at}', '".get_datetime()."')";
	$db->query($sql);
	$db->close();
}

/**
 * 由于php的json扩展自带的函数json_encode会将汉字转换成unicode码
 * 所以我们在这里用自定义的json_encode，这个函数不会将汉字转换为unicode码
 */
function custom_json_encode($a = false) {
    if (is_null($a)) return 'null';
    if ($a === false) return 'false';
    if ($a === true) return 'true';
    if (is_scalar($a)) {
        if (is_float($a)) {
            // Always use "." for floats.
            return floatval(str_replace(",", ".", strval($a)));
        }

        if (is_string($a)) {
            static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
            return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
        } else {
            return $a;
        }
    }

    $isList = true;
    for ($i = 0, reset($a); $i < count($a); $i++, next($a)) {
        if (key($a) !== $i) {
            $isList = false;
            break;
        }
    }

    $result = array();
    if ($isList) {
        foreach ($a as $v) $result[] = custom_json_encode($v);
        return '[' . join(',', $result) . ']';
    } else {
        foreach ($a as $k => $v) $result[] = custom_json_encode($k).':'.custom_json_encode($v);
        return '{' . join(',', $result) . '}';
    }
}

function redirect_with_post( $url ) {
	if( $url ) {
		echo '<form id="__redirect_with_post_form__" action="'.$url.'" method="post">';
		foreach($_POST as $name => $value) {
			echo '<input type=hidden name="'.$name.'" value="'.$value.'" />';
		}
		echo '</form>';
		echo '<script type="text/javascript">';
		echo 'document.getElementById("__redirect_with_post_form__").submit();';
		echo '</script>';
	}
}
 
function is_mobile_number( $str ) {
	return  preg_match("/^((\+86)?|(86)?)(13[0-9]{9}|15[0|1|2|3|5|6|7|8|9]\d{8}|18[0|5|6|7|8|9]\d{8})$/", $str);
}

function is_email_well_form ( $email ) {
	return eregi("^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,4}$", $email);
}

function send_mail($type, $to, $info) {
	if(!isset($_SESSION['session_Setting_SITE_MASTER_EMAIL'])){
		read_setting();
	}
	$masteremail = $_SESSION['session_Setting_SITE_MASTER_EMAIL'];
	if( !is_email_well_form($to) ) {
		return false;
	}
	
	$db = db_connect();
	$sql = "SELECT `Subject`, `Content`, `IsHtml` FROM `EmailTemplate` WHERE `Type`='{$type}'";
	$rs = $db->query($sql);
	if($row = $rs->fetch_assoc()){
		$subject = $row["Subject"];
		$content = $row["Content"];
		$html = $row["IsHtml"] + 0;
		foreach ($info as $k =>  $v) {
			$subject = preg_replace('/#' . $k . '#/', $v, $subject);
			$content = preg_replace('/#' . $k . '#/', $v, $content);
		}
		$headers = '';
		if($html){
			$headers .= 'MIME-Version: 1.0' ."\r\n";
			$headers .= 'Content-type: text/html; charset=utf-8' ."\r\n";
		}
		$headers .= 'To: ' . $to ."\r\n";
		$headers .= 'From: ' . $masteremail ."\r\n";
		
		$config = "-f$masteremail"; 
				
		return mail ($to, $subject, $content, $headers, $config);
	}
	else {
		return false;
	}
}

function get_mail_url( $email ) {
	$domain = strtolower(strstr($email, '@'));
	if($domain == '@163.com') {
		return 'http://mail.163.com/';
	}
	elseif($domain == '@vip.163.com') {
		return 'http://vip.163.com/';
	}
	elseif($domain == '@139.com') {
		return 'http://mail.10086.cn/';
	}
	elseif($domain == '@sohu.com') {
		return 'http://mail.sohu.com/';
	}
	elseif($domain == '@vip.sohu.com') {
		return 'http://vip.sohu.com/';
	}
	elseif($domain == '@tom.com') {
		return 'http://mail.tom.com/';
	}
	elseif($domain == '@tom.com') {
		return 'http://vip.tom.com/';
	}
	elseif($domain == '@189.cn') {
		return 'http://mail.189.cn/';
	}
	elseif($domain == '@126.com') {
		return 'http://www.126.com/';
	}
	elseif($domain == '@vip.126.com') {
		return 'http://vip.126.com/';
	}
	elseif($domain == '@gmail.com') {
		return 'http://gmail.google.com/';
	}
	elseif($domain == '@sina.com') {
		return 'http://mail.sina.com.cn/';
	}
	elseif($domain == '@vip.sina.com') {
		return 'http://vip.sina.com.cn/';
	}
	elseif($domain == '@hotmail.com' || $domain == '@msn.com' || $domain == '@live.com') {
		return 'http://www.hotmail.com/';
	}
	elseif($domain == '@sogou.com') {
		return 'http://mail.sogou.com/';
	}
	elseif($domain == '@qq.com' || $domain == '@vip.qq.com') {
		return 'http://mail.qq.com/';
	}
	elseif($domain == '@yahoo.com.cn' || $domain == '@yahoo.cn') {
		return 'http://mail.cn.yahoo.com/';
	}
	elseif($domain == '@eyou.com') {
		return 'http://www.eyou.com/';
	}
	elseif($domain == '@21cn.com') {
		return 'http://mail.21cn.com/';
	}
	elseif($domain == '@21cn.net') {
		return 'http://mail.21cn.com/vip/';
	}
	elseif($domain == '@188.com') {
		return 'http://www.188.com/';
	}
	elseif($domain == '@yeah.net') {
		return 'http://www.yeah.net/';
	}
	elseif($domain == '@foxmail.com') {
		return 'http://www.foxmail.com/';
	}
	elseif($domain == '@wo.com.cn') {
		return 'http://mail.wo.com.cn/';
	}
	elseif($domain == '@263.net') {
		return 'http://www.263.net/';
	}
}

/**
 * 写log
 */
function custom_log( $operation, $data=null ) {
	$db = db_connect();
	$sql = "INSERT INTO `CustomLog`(`CustomID`, `Username`, `Email`, " .
			"`Mobile`, `IP`, `Operation`, `Data`, `OpTime`) " .
			"VALUES('{$_SESSION['session_customid']}','{$_SESSION['session_customUsername']}','{$_SESSION['session_customEmail']}'," .
			"'{$_SESSION['session_customMobile']}','".get_client_ip()."','" . $operation . "'," .
			( empty($data) ? "NULL" : "'{$data}' ") . ",'".get_datetime()."')";
	$db->query($sql);		
	
	$db->close();
}

/**
 * 设置提示消息
 */
function set_info_notification($msg){
	set_notification($msg, 'info');
}

/**
 * 设置成功消息
 */
function set_success_notification($msg){
	set_notification($msg, 'success');
}

/**
 * 设置失败消息
 */
function set_error_notification($msg){
	set_notification($msg, 'error');
}

function set_notification($msg, $status){
		$_SESSION['session_last_notification'] = $msg;
		$_SESSION['session_last_notification_status'] = $status;
}
/**
 * 组装一个错误json
 * @param string $msg 错误信息
 * @param string $url 跳转url，如果不提供，结果中将不包含跳转URL
 */
function error_json( $msg, $url=null ) {
	return '{"success":false, "msg":"'.$msg.'"'.(isset($url) ? ',"url": "'.$url.'"':'').'}';
}

function success_json_no_data() {
	return '{"success":true}';
}

function read_setting() {
	if(!empty($_SESSION['session_settings_read'])) return;
	$db = db_connect();
	$sql = "SELECT `Property`, `Value` FROM `Setting`;";
	$rs = $db->query($sql);
	while($setting = $rs->fetch_assoc()){
		$_SESSION['session_Setting_' . $setting['Property']] = $setting['Value'];
		$_SESSION['session_settings_read'] = 1;
	}
	$db->close();
}
function read_page_setting() {
	if(!empty($_SESSION['session_page_settings_read'])) return;
	$db = db_connect();
	$sql = "SELECT * FROM `PageSetting`;";
	$rs = $db->query($sql);
	if($setting = $rs->fetch_assoc()){
		foreach ( $setting as $key => $value ) {
			$_SESSION['session_Setting_' . $key] = $value;
		}
		$_SESSION['session_page_settings_read'] = 1;
	}
	$db->close();
}

/**
 * 连接数据库
 */
function db_connect() {
    global $dbhost;
    global $dbuser;
    global $dbpass;
    global $dbname;
    
    $db = new Database($dbhost, $dbuser, $dbpass, $dbname);
    return $db;
}

/**
 * 获取服务器当前的时间
 * @return string 时间字符串，格式: YYYY-mm-dd HH:ii:ss
 */
function get_datetime() {
	date_default_timezone_set('PRC');
	return date('Y-m-d H:i:s');
}

/**
 * 获取客户端的真实IP
 */
function get_client_ip() {
	$unknown = 'unknown';  
	if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) 
		&& $_SERVER['HTTP_X_FORWARDED_FOR'] 
		&& strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown) ) 
	{  
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];  
	}
	elseif ( isset($_SERVER['REMOTE_ADDR']) 
		&& $_SERVER['REMOTE_ADDR'] 
		&& strcasecmp($_SERVER['REMOTE_ADDR'], $unknown) )
	{  
		$ip = $_SERVER['REMOTE_ADDR'];  
	}  
	/*
	处理多层代理的情况  
	或者使用正则方式：$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;  
	*/  
	if (false !== strpos($ip, ','))  
		$ip = reset(explode(',', $ip));  
	
	return $ip;
}

function get_client_browser_type() {
	$re = "";
	if ( strstr($_SERVER["HTTP_USER_AGENT"], "MSIE") ) {
		$re .= "ie ";
		if( strstr($_SERVER["HTTP_USER_AGENT"], "MSIE 9") ) {
			$re .= "ie9 ";
		}
		if( strstr($_SERVER["HTTP_USER_AGENT"], "MSIE 8") ) {
			$re .= "ie8 ievil ";
		}
		if( strstr($_SERVER["HTTP_USER_AGENT"], "MSIE 7") ) {
			$re .= "ie7 ievil ";
		}
		if( strstr($_SERVER["HTTP_USER_AGENT"], "MSIE 6") ) {
			$re .= "ie6 ievil ";
		}
	}
	else {
		if ( strstr($_SERVER["HTTP_USER_AGENT"], "Safari") ) {
			$re .= "safari ";
		}
		if ( strstr($_SERVER["HTTP_USER_AGENT"], "Firefox") ) {
			$re .= "firefox ";
		}
		if ( strstr($_SERVER["HTTP_USER_AGENT"], "Chrome") ) {
			$re .= "chrome ";
		}
		if ( strstr($_SERVER["HTTP_USER_AGENT"], "Opera") ) {
			$re .= "opera ";
		}
		$re .= "non-ie ";
	}
	
	if ( strstr($_SERVER["HTTP_USER_AGENT"], "Windows") ) {
		$re .= "windows";
	}
	else {
		$re .= "non-windows";
	}
	
	return $re;
}

/*
 * 生成 UUID
 */
function uuid($prefix = '') {
	$chars = md5(uniqid(mt_rand(), true));
	$uuid  = substr($chars,0,8) . '-';
	$uuid .= substr($chars,8,4) . '-';
	$uuid .= substr($chars,12,4) . '-';
	$uuid .= substr($chars,16,4) . '-';
	$uuid .= substr($chars,20,12);
	return $prefix . $uuid;
}
/**
 * 根据餐品的Id 来查询他的图片
 *
 */
function getDishImgByDishId($dId){
	global $dbhost;
	global $dbuser;
	global $dbpass;
	global $dbname;
	$mysql=mysql_connect($dbhost,$dbuser,$dbpass) or die('网络不畅通');
	mysql_select_db($dbname);
	mysql_query("set names 'utf8'");
	$sql="select img.imgPath,img.width,img.height from dishimg as img inner join dish as dish where dish.id=img.dishid and dish.id=".$dId;
	$result = mysql_query($sql) or die("Query failed : " . mysql_error());
	$path=mysql_fetch_assoc($result);
	return $path;
}
// mysqli 数据访问对象
function dao() {
	global $dbhost;
	global $dbuser;
	global $dbpass;
	global $dbname;
	$db = new mysqli ( $dbhost, $dbuser, $dbpass, $dbname );
	$db->query ( "set names 'utf8';" );
	$db->query ( "SET CHARACTER_SET_CLIENT=UTF8;" );
	$db->query ( "SET CHARACTER_SET_RESULTS=UTF8;" );
	$db->query ( "SET time_zone = '+8:00';" );
	return $db;
}

/**
 * 根据城市ID得到该城市的餐馆
 * @param $cid
 */
function getRestaurantByCityId($cid){
	$sql="select * from restaurant where Hide=0 and CityId=".$cid;
	$db=dao();
	$result=$db->query($sql);
	$rs=array();
	while($row=$result->fetch_assoc()){
		$rs[]=$row;
	}
	$db->close();
	return $rs;
}
/***
 * 根据餐馆的ID判断菜餐馆是不是营业中
 */
function isBusiness($rid){
	$sql="select BusinessHour from restaurant where ID=".$rid;
	$db=dao();
	$result=$db->query($sql);
	if($row=$result->fetch_assoc()){
		$businessHour= $row['BusinessHour'];
		$temp_arr=explode('-',$businessHour);
		date_default_timezone_set ( 'PRC' );
		$min=strtotime($temp_arr[0].':00');//开始营业时间
		$max=strtotime($temp_arr[1].':00');//关门时间
		$theNow=strtotime(date( 'H:i:s' ));//当前时间戳
		if($min<=$theNow && $theNow<=$max){
		 	return true;
		}else{
			return false;
		}
	}
	$db->close();
}
/**
 * 得到时间段
 * Enter description here ...
 * @param $rid
 */
function getBusinessHour($rid){
	$sql="select BusinessHour from restaurant where ID=".$rid;
	$db=dao();
	$businessHour='';
	$result=$db->query($sql);
	if($row=$result->fetch_assoc()){
		$businessHour= $row['BusinessHour'];
	}
	return $businessHour;
	$db->close();
}

/**
 * 查询出所有的城市
 */
function getCityInfo(){
	global $dbhost;
	global $dbuser;
	global $dbpass;
	global $dbname;
	$rs=array();
	//$sql="select c.Name,c.Latitude,c.longitude,c.ZoomLevel,C.Hide,r.Name as rName,r.Latitude as rLatitude,r.Longitude as rLongitude,r.ZoomLevel as rz
	//from city as c left join region as r on c.ID=r.CityID where c.Hide=0 and r.Hide=0";
	$sql="select * from city where hide=0";
	mysql_connect($dbhost,$dbuser,$dbpass);
	mysql_select_db($dbname);
	mysql_query("set names 'utf8'");
	$result=mysql_query($sql);

	while($n=mysql_fetch_assoc($result)){
		$rs[]=$n;
	}
	//echo "<pre>";
	//	print_r($rs);
	//echo "</pre>";
	return $rs;
}
/**
 * 根据城市的Id来获得城市
 * Enter description here ...
 * @param $cityId
 */
function getCityInfoById($cityId){
	$db=dao();
	$rs=null;
	//$sql="select c.Name,c.Latitude,c.longitude,c.ZoomLevel,C.Hide,r.Name as rName,r.Latitude as rLatitude,r.Longitude as rLongitude,r.ZoomLevel as rz
	//from city as c left join region as r on c.ID=r.CityID where c.Hide=0 and r.Hide=0";
	$sql="select * from city where hide=0 and ID=".$cityId;

	$result=$db->query($sql);

	while($n=$result->fetch_assoc()){
		$rs=$n;
	}
	$db->close();
	return $rs;
}

function getRegionByCityId($cid) {
	$rs = array ();
	$db = dao ();
	if (! empty ( $cid )) {
		$result = $db->query ( "select * from region where Hide=0 and CityID=" . $cid );
		while ( $row = $result->fetch_assoc () ) {
			$rs [] = $row;
		}
	}
	$db->close ();
	return $rs;
}
/**
 * 得到 餐馆 热门的 餐饮
 */
function getTop3DishesByRestaurentId($rid) {
	$rs = array ();
	$db = dao ();
	$sql = "select * from dish where restaurantID =" . $rid . " limit 3";
	$result = $db->query ( $sql );
	while ( $n = $result->fetch_assoc () ) {
		$rs [] = $n;
	}
	$db->close();
	return $rs;
}

/**
 * 根据餐馆的ID 判断该餐馆是不是被该用户收藏过
 *
 * @param unknown_type $rid        	
 * @return boolean
 */
function isExistInFav($rid) {
	$rs = false;
	$db = dao ();
	$sql = "select ID from favrestaurant where (CustomID=" . (empty ( $_SESSION [loginUser] [ID] ) ? - 1 : $_SESSION [loginUser] [ID]) . " or GuestID='" . $_COOKIE [guestid] . "') and RestaurantID=" . $rid;
	$restult = $db->query ( $sql );
	if ($row = $restult->fetch_assoc ()) {
		$rs = true;
	}
	$db->close ();
	return $rs;
}
// 查询 restaurant 所有餐馆信息的到餐馆列表
function getRestarauntAllInfoById($rid = 0) {
	$db = dao ();
	if (empty ( $rid )) {
		return null;
	}
	$restautant = null;
	$sql = $db->escape_string ( "select * from `restaurant` where `restaurant`.`ID`=" . $rid );
	$result = $db->query ( $sql );
	if ($n = $result->fetch_assoc ()) {
		//$n ['rsimg'] = getImgInfoByRid ( $n [ID] );
		$restautant = $n;
	}
	$db->close ();
	return $restautant;
}

/**
 * 根据餐馆的id查询所有该餐馆的餐品
 *
 * @param $rid 餐馆的ID        	
 */
function getDishInfoListByRid($rid) {
	$dishes = array ();
	$db = dao (); // 创建数据访问层对象
	$sql = $db->escape_string ( "select d.*,i.imgPath,i.width,i.height from dish as d left join dishimg as i on d.ID=i.dishId  where d.RestaurantID=" . $rid );
	$result = $db->query ( $sql );
	echo $db->error;
	while ( $row = $result->fetch_assoc () ) {
		$dishes [] = $row;
	}
	$db->close ();
	return $dishes;
}
/**
 * 查询 restaurant 所有餐馆信息的到餐馆列表
 *
 * @param unknown_type $regionId
 *        	区域Id
 * @param unknown_type $cityId
 *        	城市ID
 */
function getRestarauntByRegionIDOrCityId($regionId, $cityId) {
	$db = dao ();
	$list = array ();
	$sql = $db->escape_string ( "select DISTINCT * from restaurant where Hide=0 and (regionID={$regionId} or cityId={$cityId})" );
	$result = $db->query ( $sql );
	while ( $row = $result->fetch_assoc () ) {
		$list [] = $row;
	}
	$db->close ();
	return $list;
}
/**
 * 根据经纬度，也是 根据东北角西南角或的 该地图上的所有的餐馆的详细信息
 * Enter description here ...
 * @param unknown_type $maxLng
 * @param unknown_type $maxLat
 * @param unknown_type $minLng
 * @param unknown_type $minLat
 */
function getRestaurantByBounds($maxLng,$maxLat,$minLng,$minLat){
	$db=dao();
	$list=array();
	$sql=$db->escape_string("select * from restaurant where Hide=0 and Latitude >= {$minLat} and Latitude <= {$maxLat} and Longitude>= {$minLng} and Longitude<= {$maxLng}") ;
	$result=$db->query($sql);
	while($row=$result->fetch_assoc()){
		$list[]=$row;
	}
	$db->close();
	return $list;
}

/**
 * 截取中文首字母
 * Enter description here ...
 * @param $str
 * @param $from
 * @param $len
 */
function utf8Substr($str, $from, $len)
{
	return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
                       '$1',$str);
}
/**
 * 得到中文首字母
 * Enter description here ...
 * @param $s0
 */
function getfirstchar($s0){
	$fchar = ord($s0{0});
	if($fchar >= ord("A") and $fchar <= ord("z") )return strtoupper($s0{0});
	$s1 = iconv("UTF-8","gb2312", $s0);
	$s2 = iconv("gb2312","UTF-8", $s1);
	if($s2 == $s0){$s = $s1;}else{$s = $s0;}
	$asc = ord($s{0}) * 256 + ord($s{1}) - 65536;

	if($asc >= -20319 and $asc <= -20284) return "A";
	if($asc >= -20283 and $asc <= -19776) return "B";
	if($asc >= -19775 and $asc <= -19219) return "C";
	if($asc >= -19218 and $asc <= -18711) return "D";
	if($asc >= -18710 and $asc <= -18527) return "E";
	if($asc >= -18526 and $asc <= -18240) return "F";
	if($asc >= -18239 and $asc <= -17923) return "G";
	if($asc >= -17922 and $asc <= -17418) return "H";
	if($asc >= -17417 and $asc <= -16475) return "J";
	if($asc >= -16474 and $asc <= -16213) return "K";
	if($asc >= -16212 and $asc <= -15641) return "L";
	if($asc >= -15640 and $asc <= -15166) return "M";
	if($asc >= -15165 and $asc <= -14923) return "N";
	if($asc >= -14922 and $asc <= -14915) return "O";
	if($asc >= -14914 and $asc <= -14631) return "P";
	if($asc >= -14630 and $asc <= -14150) return "Q";
	if($asc >= -14149 and $asc <= -14091) return "R";
	if($asc >= -14090 and $asc <= -13319) return "S";
	if($asc >= -13318 and $asc <= -12839) return "T";
	if($asc >= -12838 and $asc <= -12557) return "W";
	if($asc >= -12556 and $asc <= -11848) return "X";
	if($asc >= -11847 and $asc <= -11056) return "Y";
	if($asc >= -11055 and $asc <= -10247) return "Z";
	return null;
}

/**
 * 根据Id得到餐馆
 * Enter description here ...
 * @param $rid
 */
function getRestarauntById($rid){
	$rs=null;
	$sql="select * from restaurant where ID =".$rid;
	$db=dao();
	$result=$db->query($sql);
	if($row=$result->fetch_assoc()){
		$rs=$row;
	}
	return $rs;
}

/**
 * 根据地区名获得街道信息
 * Enter description here ...
 * @param $regionId
 */
function getStreetByRegionId($regionId){
	$first=array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
	$sql="select * from street where regionId=".$regionId." order by sequence";//
//	$sql="select * from street  order by sequence";//where regionId=".$regionId."
	$db=dao();
	$result=$db->query($sql);
	$arr=array();
	while($row=$result->fetch_assoc()){
		if($row['sequence']=='A'){
			$arr['A'][]=$row;
		}else if($row['sequence']=='B'){
			$arr['B'][]=$row;
		}else if($row['sequence']=='C'){
			$arr['C'][]=$row;
		}else if($row['sequence']=='D'){
			$arr['D'][]=$row;
		}else if($row['sequence']=='E'){
			$arr['E'][]=$row;
		}else if($row['sequence']=='F'){
			$arr['F'][]=$row;
		}else if($row['sequence']=='G'){
			$arr['G'][]=$row;
		}else if($row['sequence']=='H'){
			$arr['H'][]=$row;
		}else if($row['sequence']=='I'){
			$arr['I'][]=$row;
		}else if($row['sequence']=='J'){
			$arr['J'][]=$row;
		}else if($row['sequence']=='K'){
			$arr['K'][]=$row;
		}else if($row['sequence']=='L'){
			$arr['L'][]=$row;
		}else if($row['sequence']=='M'){
			$arr['M'][]=$row;
		}else if($row['sequence']=='N'){
			$arr['N'][]=$row;
		}else if($row['sequence']=='O'){
			$arr['O'][]=$row;
		}else if($row['sequence']=='P'){
			$arr['P'][]=$row;
		}else if($row['sequence']=='Q'){
			$arr['Q'][]=$row;
		}else if($row['sequence']=='R'){
			$arr['R'][]=$row;
		}else if($row['sequence']=='S'){
			$arr['S'][]=$row;
		}else if($row['sequence']=='T'){
			$arr['T'][]=$row;
		}else if($row['sequence']=='U'){
			$arr['U'][]=$row;
		}else if($row['sequence']=='V'){
			$arr['V'][]=$row;
		}else if($row['sequence']=='W'){
			$arr['W'][]=$row;
		}else if($row['sequence']=='X'){
			$arr['X'][]=$row;
		}else if($row['sequence']=='Y'){
			$arr['Y'][]=$row;
		}else if($row['sequence']=='Z'){
			$arr['Z'][]=$row;
		}
	}
	$db->close();
	return $arr;
}




function lipinList($start = 0, $limit = 10) {
	$db = dao ();
	$re = array ();
	$sql = "select * from lipin where lipinCount>0  limit {$start},{$limit}";
	$result = $db->query ( $sql );
	while ( $row = $result->fetch_assoc () ) {
		$re [] = $row;
	}
	return $re;
}

function getLipinCount() {
	$db = dao ();
	$re = 0;
	$sql = "select count(*) as c from lipin";
	$result = $db->query ( $sql );
	if ($row = $result->fetch_assoc ()) {
		$re = $row ['c'];
	}
	return $re;
}

function getMyScore() {
	$db = dao ();
	$re = null;
	$sql = "select * from customscore where  customId=" . $_SESSION ['session_customid'];
	$result = $db->query ( $sql );
	if ($row = $result->fetch_assoc ()) {
		$re = $row;
	}
	return $re;
}

function getLipinTip(){
	$sql="select tip1,tip2 from scorereg ";
	$db=dao();
	$result=null;
	$rs=$db->query($sql);
	if($row=$rs->fetch_assoc()){
		$result=$row;
	}
	$db->close();
	return $result;
}


function getPrintText($oid,$type){
	$db=dao();
	$text='';
	$flag=true;
	$rid=0;
	$sql="SELECT `Order`.`CreateTime` AS OrderTime, `Order`.`Takeout` as takeout,`Restaurant`.`Discount` as dis,`Restaurant`.`DiscountIn` as disIn, `Restaurant`.`Name`,`Restaurant`.`SaleAd` as isPrint, " .
			"`Order`.`Mobile` AS CustomMobile, `Order`.`RestaurantID`, " .
			"`Order`.`Address`, `Order`.`Notes`, `Order`.`CustomID` ,`Custom`.`Username`,`order`.`VeriCode` " .
			"FROM `Restaurant`, `Order`, `Custom` " .
			"WHERE `Order`.`ID`='{$oid}' " .
			"AND `Order`.`RestaurantID`=`Restaurant`.`ID` " .
			"AND `Order`.`CustomID`= `Custom`.`ID` ";
	$rs = $db->query($sql);
	if($row = $rs->fetch_assoc() ) {
		$orderTime = $row['OrderTime'];				//订餐时间
		$Restaurant = $row['Name'];					 //餐馆名称
		$RestaurantID = $row['RestaurantID'];			//餐馆Id
		$rid=$RestaurantID;
		$CustomMobile = $row['CustomMobile'];			//客户电话
		$Address = $row['Address'];						//收货地址
		$Notes = $row['Notes'];							//特殊要求
		$CustomID = $row['CustomID'];					//客户Id
		$CustomName = $row['Username'];					//客户用户名
		$isPrint=$row['isPrint'];						//是否打印
		$vericode=$row['VeriCode'];						//到店消费，有用,验证码
		$takeout=$row['takeout'];				//是否送
		$Discount=$row['dis'];
		$DiscountIn=$row['disIn'];
		if($isPrint==0){
			return true;//停止打印
		}
		//组装
		$text.=$Restaurant.'
(来自淘吃啦的订单)
		
条目         单价（元）    数量
------------------------------
';
		$sql = "SELECT `Name`, `Price`, `Count` " .//查询 该订单的餐品
				"FROM `OrderItem` WHERE `OrderID`='{$oid}';";
		$item_rs = $db->query($sql);
		$total = 0;
		while($item = $item_rs->fetch_assoc() ){
			//array_push($items, $item['Name'] . "，" . ($item['Price']+0) . "元x" . $item['Count']);
			//组装
			$text.=$item['Name'].'
             '.$item['Price'].'        '.$item['Count'].'
';
			$total += ($item['Price']+0) * ($item['Count']+0);
		}
		if($total==0){
			$flag=false;
		}
		
		$totalCount=0;
		if($takeout=='0'){//到店消费
			$totalCount=$total*$DiscountIn/10;
		}else{//送餐上门
			$totalCount=$total*$Discount/10;
		}
		//组装
		$text.='备注：'.$Notes.'
------------------------------
合计：'.$totalCount.'元
			
客户地址：'.$Address.'
联系电话：'.$CustomMobile.'
订购时间：'.$orderTime.'
------------------------------
'.$type.($type=='到店消费'?'
验证码: '.$vericode:'');	
	}
	if($rid!=0){//改餐馆存在
		include_once 'feyinApi/printFunctions.php';
		$sql="select MEMBER_CODE,FEYIN_KEY,DEVICE_NO from restaurant where ID=".$rid;
		$resInfo=$db->query($sql);
		if($row=$resInfo->fetch_assoc()){
			print_msg($text,$row['MEMBER_CODE'],$row['FEYIN_KEY'],$row['DEVICE_NO']);
			//sendFreeMessage($text,$row['MEMBER_CODE'],$row['FEYIN_KEY'],$row['DEVICE_NO']);
		}else{
			$flag=false;
		}
	}else{
		$flag=false;
	}
	return $flag;
}






/**
 * 根据参观的Id 得到 他 的UUID
 * Enter description here ...
 * @param $rid
 */
function getRestaurantUUIDByID($rid){
	$db=dao();
	$result= $db->query("select UUID from restaurant where ID=".$rid);
	$uuid='';
	if($row=$result->fetch_assoc()){
		$uuid=$row['UUID'];
	}
	$db->close();
	return $uuid;
}



function dump($arr){
	echo "<pre>";
	print_r($arr);
	echo "</pre>";
}
/**
 * 以下为公共执行内容
 */
//注意：所有函数、cookie都没有了反斜杠
if (get_magic_quotes_gpc ()) {
 	function stripslashes_deep ($value){
		$value = (is_array ($value) ? array_map ('stripslashes_deep', $value) : stripslashes ($value));
		return $value;
	}
	$_POST = array_map ('stripslashes_deep', $_POST);
	$_GET = array_map ('stripslashes_deep', $_GET);
	$_COOKIE = array_map ('stripslashes_deep', $_COOKIE);
	$_REQUEST = array_map ('stripslashes_deep', $_REQUEST);
}
if (get_magic_quotes_runtime ()) {
	set_magic_quotes_runtime (0);
}
session_start ();
read_setting();
read_page_setting();
welcome_guest();
?>