<?php

//扩展函数库

/**
 * @abstract 获得制作的所有信息
 * @param string $ids
 * @return array
 */
function get_made_info($ids,$id = ""){
	$array = array();
	foreach ( M("made")->where("id in ({$ids})")->select() as $k => $v){
		$v["meterial"] = M("Meterial")->where("id = {$v['metid']}")->find();
		if($id == $v["id"]) 
			$v["current"] = 1;
		else
			$v["current"] = 0;
		$array[$k] = $v;
	}
	return $array;
}


function formatBytes($size) {
	$units = array(' B', ' KB', ' MB', ' GB', ' TB');
	for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
	return round($size, 2).$units[$i];
}

/**
 * @abstract 返回区域地址
 * @param string $str
 * @return string
 */
function get_area($str){
	$temp = "";
	foreach (explode(",",$str) as $id){
		if($id)
			$temp .= M("district")->where("id = {$id}")->getField("name");
	}
	return $temp;
}
/**
 * @abstract 返回订单状态
 * @param 状态值
 * @return string0:下单
 *  0:已下单
	1:未付款
	2:已付款
	3:已发货
	4:已完成
	-1:关闭订单
*/

function get_orderstatus($status){
	switch ($status){
		case 0:
			return  "已下单";
		case 1:
			return  "未付款";
		case 2:
			return  "已付款";
		case 3:
			return  "已发货";
		case 4:
			return  "已完成";
		case -1:
			return  "关闭订单";
		default:
			return  false;
			
	}
}

/**
 * @abstract 获得文档状态
 * @param unknown $status
 * 
	-1:删除
	0:禁用
	1:正常
	2:待审核
	3:草稿
 */
function get_docstatus($status){
	switch ($status){
		case 0:
			return  "禁用";
		case 1:
			return  "正常";
		case 2:
			return  "待审核";
		case 3:
			return  "草稿";
		case -1:
			return  "删除";
		default:
			return  false;
	}
}

/**
 * @abstract 获得分类信息
 * @param int $cateid
 * @param string $field
 */
function get_cateinfo($cateid,$field = "title"){
	$cate = D("category")->info($cateid);
	if(empty($field))
		return $cate;
	else 
		return $cate[$field];
}
/**
 * @abstract增加文件下载次数
 * @param int $id
 */
function adddowns($id){
	$model = M("document_model")->where("stl={$id}")->find();
	M("document_model")->where("stl={$id}")->setInc("downs");
	M("document")->where("id={$model['id']}")->setInc("extend");
}


/**
 * @abstract 获得商品订单数量
 * @param unknown $pid
 */
function getOrderNums($pid){
	return M("order")->where("status = 4 and productid={$pid}")->count();
}


/**
 * @abstract 获得模型订单数量
 * @param unknown $mid
 */
function getModelOrderNums($mid){
	return M("modelorder")->where("status = 4 and modelid={$mid}")->count();
}

/**
 * @abstract 判断用户与模型的所属关系  1：上传  2：购买
 * @param int $uid
 * @param int $modelid
 * @return number
 */
function hasmodel($uid,$modelid){
	//该用户上传的模型
	if(M("document")->where("id={$modelid} and uid = {$uid}")->count()) return 1;
	//用户购买的模型 
	if(M("modelorder")->where("id={$modelid} and uid = {$uid} and status >= 2")->count()) return 2;
	return 0;
}

/**
 * 系统邮件发送函数
 * @param string $to    接收邮件者邮箱
 * @param string $name  接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body    邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 */
function send_mail($to, $name, $subject = '', $body = '', $attachment = null){
	$map=array('name' => array('in', array( 1 => 'MAIL_SMTP_HOST', 2 => 'MAIL_SMTP_PORT', 3 => 'MAIL_SMTP_USER', 4 => 'MAIL_SMTP_PASS', 5 => 'MAIL_SMTP_CE', 6 => 'FROM_EMAIL')));
	$db=M('config');
	$conf=$db->where($map)->field('value,name')->select();
	$config='';
	foreach ($conf as $k=>$v){
		$config[$v['name']]=$v['value'];
	}
	vendor('PHPMailer.PHPMailerAutoload'); //从PHPMailer目录导class.phpmailer.php类文件
	$mail             = new \PHPMailer(); //PHPMailer对象
	$mail->CharSet    = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
	$mail->IsSMTP();  // 设定使用SMTP服务
	$mail->SMTPDebug  = 0;                     // 关闭SMTP调试功能
	// 1 = errors and messages
	// 2 = messages only
	$mail->SMTPAuth   = true;                  // 启用 SMTP 验证功能
	$mail->SMTPSecure = 'ssl';                 // 使用安全协议
	$mail->Host       = $config['MAIL_SMTP_HOST'];  // SMTP 服务器
	$mail->Port       = $config['MAIL_SMTP_PORT'];  // SMTP服务器的端口号
	$mail->Username   = $config['MAIL_SMTP_USER'];  // SMTP服务器用户名
	$mail->Password   = $config['MAIL_SMTP_PASS'];  // SMTP服务器密码
	$from=$config['FROM_EMAIL']?$config['FROM_EMAIL']:C('WEB_SITE_TITLE');
	$mail->SetFrom($config['MAIL_SMTP_USER'],$from );
	$replyEmail       = $config['REPLY_EMAIL']?$config['REPLY_EMAIL']:$config['FROM_EMAIL'];
	$replyName        = $config['REPLY_NAME']?$config['REPLY_NAME']:$config['FROM_NAME'];
	$mail->AddReplyTo($replyEmail, $replyName);
	$mail->Subject    = $subject;
	$mail->MsgHTML($body);
	$mail->AddAddress($to, $name);
	if(is_array($attachment)){ // 添加附件
		foreach ($attachment as $file){
			is_file($file) && $mail->AddAttachment($file);
		}
	}
	return $mail->Send() ? true : $mail->ErrorInfo;
}

/*执行外部命令*/
function my_exec($cmd, $input=''){
	$proc=proc_open($cmd, array(0=>array('pipe', 'r'), 1=>array('pipe', 'w'), 2=>array('pipe', 'w')), $pipes);
	fwrite($pipes[0], $input);
	fclose($pipes[0]);
	$stdout=stream_get_contents($pipes[1]);
	fclose($pipes[1]);
	$stderr=stream_get_contents($pipes[2]);
	fclose($pipes[2]);
	$rtn=proc_close($proc);
	return array('stdout'=>$stdout,
			'stderr'=>$stderr,
			'return'=>$rtn
	);
}

/**
 * @abstract 中文字符截取
 * @param unknown $string
 * @param number $length
 * @param string $ellipsis
 * @param number $start
 * @return string|Ambigous <string, unknown>
 */
function truncate_cn($string,$length=0,$ellipsis='…',$start=0)
{
	$string=strip_tags($string);
	$string=preg_replace('/\n/is','',$string);
	$string=preg_replace('/ /is','',$string);
	preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/",$string,$string);
	if(is_array($string)&&!empty($string[0])){
		$string=implode('',$string[0]);
		if(strlen($string)<$start+1){
			return '';
		}
		preg_match_all("/./su",$string,$ar);
		$string2='';
		$tstr='';
		for($i=0;isset($ar[0][$i]);$i++){
			if(strlen($tstr)<$start){
				$tstr.=$ar[0][$i];
		}
		else{
				if(strlen($string2)<$length+strlen($ar[0][$i])){
					$string2.=$ar[0][$i];
				}
				else{
					break;
				}
			}
		}
		return $string==$string2?$string2:$string2.$ellipsis;
	}
	else{
			$string='';
	}
	return $string;
}
