<repo_name>liting68/planbook<file_sep>/weixin.php
<?php
require_once 'weixin/lib/config.php';
require_once 'weixin/wechat.php';

//define your token
$wechat = WeChat::getInstance();
//$wechatObj->valid();
//$wechatObj->setToken();
//$wechatObj->sendCustomMsg("hello","o9ZPks_8ZpcQXBndQqjuUpt-E9tg");
//$wechat->responseMsg();
?><file_sep>/App/Model/Qe.php
<?php
FLEA::loadClass('FLEA_Db_TableDataGateway');
class Model_Qe extends FLEA_Db_TableDataGateway
{
	var $tableName = 'qe';
	var $primaryKey = 'id';

	function addTimes($qeid){
		$times=$this->find(array('id'=>$qeid),'','times');
		$this->updateField(array('id'=>$qeid), 'times', $times['times']*1+1);
	}
}

?><file_sep>/App/Service/pdf/font/unifont/msyh.mtx.php
<?php
$name='MicrosoftYaHei';
$type='TTF';
$desc=array (
  'Ascent' => 1058,
  'Descent' => -262,
  'CapHeight' => 756,
  'Flags' => 4,
  'FontBBox' => '[-158 -255 1270 1036]',
  'ItalicAngle' => 0,
  'StemV' => 87,
  'MissingWidth' => 697,
);
$up=-87;
$ut=58;
$ttffile='/Library/WebServer/Documents/qa/App/Service/pdf/font/unifont/msyh.ttf';
$originalsize=15043584;
$fontkey='microsoftyahei';
?><file_sep>/App/Model/QsAnswerDetail.php
<?php
FLEA::loadClass('FLEA_Db_TableDataGateway');
class Model_QsAnswerDetail extends FLEA_Db_TableDataGateway
{
	var $tableName = 'qs_answer_detail';
	var $primaryKey = 'id';

}

?><file_sep>/App/Model/QeCon.php
<?php
FLEA::loadClass('FLEA_Db_TableDataGateway');
class Model_QeCon extends FLEA_Db_TableDataGateway
{
	var $tableName = 'qecon';
	var $primaryKey = 'id';

}

?><file_sep>/App/Class/Common.php
<?php
if (! function_exists ( 'mb_substr' )) {
	function mb_substr($str, $start, $len = '', $encoding = "UTF-8") {
		$limit = strlen ( $str );
		
		for($s = 0; $start > 0; -- $start) { // found the real start
			if ($s >= $limit)
				break;
			
			if ($str [$s] <= "\x7F")
				++ $s;
			else {
				++ $s; // skip length
				

				while ( $str [$s] >= "\x80" && $str [$s] <= "\xBF" )
					++ $s;
			}
		}
		
		if ($len == '')
			return substr ( $str, $s );
		else
			for($e = $s; $len > 0; -- $len) { //found the real end
				if ($e >= $limit)
					break;
				
				if ($str [$e] <= "\x7F")
					++ $e;
				else {
					++ $e; //skip length
					

					while ( $str [$e] >= "\x80" && $str [$e] <= "\xBF" && $e < $limit )
						++ $e;
				}
			}
		
		return substr ( $str, $s, $e - $s );
	}
}
/**

 * Project: 公共函数

 * Author: libin

 * Date: 2008年10月13日

 * File: common.php

 * Version: 1.0

 */

class Class_Common extends FLEA_Controller_Action {
	var $_admin;
	
	/**

	 * Enter description here...

	 *

	 */
	
	function __construct() {
		$this->_admin = & get_singleton ( "Model_Admin" );
	}
	
	/**

	 * Open, parse, and return the file content.

	 * @author libin 2008-09-13

	 * @param string string the php file name

	 *

	 * @return string

	 */
	
	function include_fetch($file, $var = array()) {
		extract ( $var ); // Extract the vars to local namespace
		

		ob_start (); // Start output buffering
		

		include ($file); // Include the file
		

		$contents = ob_get_contents (); // Get the contents of the buffer
		

		ob_end_clean (); // End buffering and discard
		

		return $contents; // Return the contents
	

	}
	
	/**

	 *调用包含函数

	 * @author libin 2008-09-13

	 * @param unknown_type $function

	 * @param unknown_type $params

	 * @return unknown

	 */
	
	function include_fetch_function($function, $params = array()) {
		
		ob_start ();
		
		call_user_func_array ( $function, $params );
		
		$contents = ob_get_contents ();
		
		ob_end_clean ();
		
		return $contents;
	
	}
	
	/**

	 * 显示模板页面

	 * @author libin 2008-09-13

	 * @param unknown_type $parm

	 */
	
	function show($parm = array()) {
		$smarty = & $this->_getView ();
		foreach ( $parm as $key => $value ) {
			$smarty->assign ( $key, $value );
		}
		if (@$parm ['title'] == "") {
			$parm ['title'] = DEFAUT_TITLE;
		
		}
		
		$smarty->register_modifier ( "substr", array ("Class_Common", "m_substr" ) );
		$smarty->register_modifier ( "formatdate", array ("Class_Common", "formatdate" ) );
		$smarty->register_modifier ( "formatmoney", array ("Class_Common", "formatmoney" ) );
		
		if (isset ( $_SESSION ['loginuserid'] ) && $_SESSION ['loginuserid'] != "") {
			$loginuserinfo = $this->_admin->findByField ( "id", $_SESSION ['loginuserid'] );
			$smarty->assign ( 'loginuserinfo', @$loginuserinfo );
			$smarty->assign ( 'loginuserid', @$_SESSION ['loginuserid'] );
		} else {
			$loginuserinfo = array ();
		}
		$smarty->display ( 'main.tpl' );
	}
	
	function article($parm = array()){
		$smarty = & $this->_getView ();
		foreach ( $parm as $key => $value ) {
			$smarty->assign ( $key, $value );
		}
		$smarty->display ( 'article.tpl' );
	}
	
	/**

	 * 后台管理

	 *

	 * @param unknown_type $parm

	 * @param unknown_type $admin_flag

	 */
	
	function manage($parm = array(), $admin_flag = "") {
		$smarty = & $this->_getView ();
		foreach ( $parm as $key => $value ) {
			$smarty->assign ( $key, $value );
		}
		if (@$parm ['title'] == "") {
			$parm ['title'] = DEFAUT_TITLE;
		
		}
		
		$smarty->register_modifier ( "substr", array ("Class_Common", "m_substr" ) );
		$smarty->register_modifier ( "formatdate", array ("Class_Common", "formatdate" ) );
		$smarty->register_modifier ( "formatmoney", array ("Class_Common", "formatmoney" ) );
		
		if (isset ( $_SESSION ['loginuserid'] ) && $_SESSION ['loginuserid'] != "") {
			$loginuserinfo = $this->_user->findByField ( "id", $_SESSION ['loginuserid'] );
		} else {
			$loginuserinfo = array ();
		}
		
		$smarty->assign ( 'loginuserinfo', @$loginuserinfo );
		$smarty->assign ( 'loginuserid', @$_SESSION ['loginuserid'] );
		$smarty->display ( 'admin/main.tpl' );
	}
	
	/**

	 * 不带模板的页面显示

	 * @author libin 2008-09-13

	 * @param unknown_type $page

	 * @param unknown_type $parm

	 */
	
	function display($page, $parm = array()) {
		$smarty = & $this->_getView ();
		foreach ( $parm as $key => $value ) {
			$smarty->assign ( $key, $value );
		}
		$smarty->register_modifier ( "substr", array ("Com_Common", "m_substr" ) );
		
		$smarty->display ( $page );
	}
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $date
	 */
	function formatdate($date) {
		$date = str_replace ( "-", "/", $date );
		return $date;
	}
	/**
	 * 
	 * 格式化金额
	 * @param unknown_type $date
	 */
	function formatmoney($date) {
		$date = number_format ( $date );
		return $date;
	}
	
	/**

	 * word cut

	 * @author libin 2008-09-13

	 * @param unknown_type $word

	 * @param unknown_type $num

	 * @return unknown

	 */
	
	function word_explode($word, $num) {
		
		$str = wordwrap ( $word, $num, "|", 1 );
		
		$str = explode ( "|", $str );
		
		$str = $str [0];
		
		return $str;
	
	}
	
	/**

	 *字截取

	 *

	 * @param unknown_type $word

	 * @param unknown_type $startw

	 * @param unknown_type $length

	 * @return unknown

	 */
	
	function m_substr($word, $start, $length, $more = "") {
		$word = htmlspecialchars_decode ( $word );
		$word = str_replace ( "&acute;", "'", $word );
		$str = mb_substr ( $word, $start, $length, "UTF-8" );
		
		if (strlen ( $word ) > strlen ( $str )) {
			$str = $str . $more;
		}
		
		return $str;
	
	}
	
	/**
	 * 
	 * 检查用户角色信息
	 * @param unknown_type $userid
	 * @param unknown_type $role
	 */
	function checkUser($userid, $role = "") {
		$userinfo = $this->_user->findByField ( "id", $userid );
		if (! is_array ( $role )) {
			$role = explode ( ",", $role );
		}
		$flag = false;
		if (count ( $userinfo ) > 0 && is_array ( $userinfo )) {
			foreach ( $role as $v ) {
				if ($v == $userinfo ['role']) {
					$flag = true;
				}
			}
		}
		if ($flag) {
			return true;
		} else {
			$url = url ( "Default", "Login" );
			redirect ( $url );
		}
	}
	
	/**
	 * 
	 * 过滤参数
	 * @return undefine
	 * @author libin
	 * @property created at 2012-10-29
	 * @property updated at 2012-10-29
	 * @example  
	 */
	function filter($value) {
		if(is_array($value)){
			foreach ($value as $k=>$v){
				if(is_array($v)){
					foreach ($v as $kk=>$vv){
						$v[$kk]=htmlspecialchars ( $vv);
					}
					$value[$k]=$v;
				}else{
					$value[$k]=htmlspecialchars ( $v);
				}
			}
		}else{
			$value = htmlspecialchars ( $value);
		}
		return $value;
	}
	
	/**
	 * 由长连接生成短链接操作
	*
	* 算法描述：使用6个字符来表示短链接，我们使用ASCII字符中的'a'-'z','0'-'9','A'-'Z'，共计62个字符做为集合。
	* 		     每个字符有62种状态，六个字符就可以表示62^6（56800235584），那么如何得到这六个字符，
	*           具体描述如下：
	*		  1. 对传入的长URL+设置key值 进行Md5，得到一个32位的字符串(32 字符十六进制数)，即16的32次方；
	*        2. 将这32位分成四份，每一份8个字符，将其视作16进制串与0x3fffffff(30位1)与操作, 即超过30位的忽略处理；
	*		  3. 这30位分成6段, 每5个一组，算出其整数值，然后映射到我们准备的62个字符中, 依次进行获得一个6位的短链接地址。
	*
	* @author flyer0126
	* @since 2012/07/13
	*/
	function shortUrl( $long_url ){
		$key = 'tongji2014';
		$base32 = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	
		// 利用md5算法方式生成hash值
		$hex = hash('md5', $long_url.$key);
		$hexLen = strlen($hex);
		$subHexLen = $hexLen / 8;
	
		$output = array();
		for( $i = 0; $i < $subHexLen; $i++ )
		{
			// 将这32位分成四份，每一份8个字符，将其视作16进制串与0x3fffffff(30位1)与操作
			$subHex = substr($hex, $i*8, 8);
			$idx = 0x3FFFFFFF & (1 * ('0x' . $subHex));
			 
			// 这30位分成6段, 每5个一组，算出其整数值，然后映射到我们准备的62个字符
			$out = '';
			for( $j = 0; $j < 6; $j++ )
			{
				$val = 0x0000003D & $idx;
				$out .= $base32[$val];
				$idx = $idx >> 5;
			}
			$output[$i] = $out;
		}
	
		return $output[0];
	}
	
	function generateQRfromGoogle($chl,$Height ='150',$widht='150',$EC_level='L',$margin='0'){
		$chl = urlencode($chl);
		return '<img src="http://1192.168.127.12/chart?chs='.$widht.'x'.$Height.'&cht=qr&chld='.$EC_level.'|'.$margin.'&chl='.$chl.'" alt="QR code" height="'.$Height.'" widht="'.$widht.'"/>';
	}
	
	function downloadQRpngfromGoogle($chl,$Height ='150',$widht='150',$EC_level='L',$margin='0'){
		$chl = urlencode($chl);
		return 'http://172.16.31.10/chart?chs='.$widht.'x'.$Height.'&cht=qr&chld='.$EC_level.'|'.$margin.'&chl='.$chl;
	}
	
	/**
	 * 时间差计算
	 *time2Units(time()-strtotime($date))
	 * @param Timestamp $time 时间差
	 * @return String Time Elapsed
	 * @author <NAME>
	 * @copyright http://phparch.cn (Professional PHP Architecture)
	 */
	function time2Units ($time)
	{
		$year   = floor($time / 60 / 60 / 24 / 365);
		$time  -= $year * 60 * 60 * 24 * 365;
		$month  = floor($time / 60 / 60 / 24 / 30);
		$time  -= $month * 60 * 60 * 24 * 30;
		$week   = floor($time / 60 / 60 / 24 / 7);
		$time  -= $week * 60 * 60 * 24 * 7;
		$day    = floor($time / 60 / 60 / 24);
		$time  -= $day * 60 * 60 * 24;
		$hour   = floor($time / 60 / 60);
		$time  -= $hour * 60 * 60;
		$minute = floor($time / 60);
		$time  -= $minute * 60;
		$second = $time;
		$elapse = '刚刚';
	
		$unitArr = array('年前'  =>'year', '个月前'=>'month',  '周前'=>'week', '天前'=>'day',
				'小时前'=>'hour', '分钟前'=>'minute', '秒前'=>'second'
		);
	
		foreach ( $unitArr as $cn => $u )
		{
			if ( $year > 0 ) {//大于一年显示年月日
				$elapse = date('Y/m/d',time()-$time);
				break;
			}
			else if ( $$u > 0 )
			{
				$elapse = $$u . $cn;
				break;
			}
		}
	
		return $elapse;
	}
	
	
}

?><file_sep>/resource/js/analysis.js
$(function () {
	$('div[id^=container]').each(function(i){
		var title='';//$('#quetitle'+i).val();
		var anscount=$('#anscount'+i).val();
		var subtitle='答卷人数:'+anscount;
		if($('#quetype'+i).val()==1){
			var option=createOption(i,title,subtitle,anscount,'pie');
		}else if($('#quetype'+i).val()==2){
			var option=createOption(i,title,subtitle,anscount,'bar');
		}else if($('#quetype'+i).val()==3){
			var option=createOption(i,title,subtitle,anscount,'bar');
		}
		$(this).highcharts(option);
	});
});

//构造option i第几个,标题,副标题,图形类型
function createOption(i,title,subtitle,anscount,type){
	var option = (type=='pie') ? getPieOption() : getBarOption();
	option.title.text=title;
	option.subtitle.text=subtitle;
	option.chart.type=type;
	var optdata=new Array();
	$('.options'+i).each(function(opi){
		var opttitle=$(this).text().toString();
		var optcount=$('.counts'+i).eq(opi).text().toString()*1;
		if(type=='pie'){
			optcount = optcount/anscount*100;
			optdata[opi]=[opttitle, optcount];
		}else if(type=='bar'){
			option.xAxis.categories[opi]=opttitle;
			optdata[opi]=optcount;
		}
	});
	option.series[0]={
        name: '选中人数',
        data: optdata
    };
	return option;
}
//饼形图
function getPieOption(){
	var option={
	        chart: {
	            plotBackgroundColor: null,
	            plotBorderWidth: null,//null,
	            plotShadow: false
	        },
	        colors:['#22b5c3', '#a3be57', '#ff9c9c', '#48cfef', '#25bf6e', '#ea5f35', '#7e85e0', '#f2bd7c', '#bbbbba', '#7257a2'],
	        title: {
	            text: '选项标题',
	            style:{
	                fontFamily:'Microsoft YaHei'
	            }
	        },
	        subtitle: {
	            text: '副标题',
	            style:{
	                fontFamily:'Microsoft YaHei'
	            }
	        },
	        tooltip: {
	            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
	        },
	        plotOptions: {
	            pie: {
	                allowPointSelect: true,
	                cursor: 'pointer',
	                dataLabels: {
	                    enabled: true,
	                    format: '{point.name}: {point.percentage:.1f} %',
	                    style: {
	                    	fontFamily:'Microsoft YaHei',
	                    	fontSize:'8px'
	                    }
	                }
	            }
	        },
	        series: [{}]
	    };
	return option;
}

//条形图
function getBarOption(){
	var option={
	        chart: {
	            type: 'bar'
	        },
	        title: {
	            text: '选项标题'
	        },
	        subtitle: {
	            text: '副标题'
	        },
	        xAxis: {
	            categories: [],
	            title: {
	                text: null
	            }
	        },
	        yAxis: {
	            min: 0,
	            title: {
	            	text: '',
	                style:{fontFamily:'Microsoft YaHei'}
	            }
	        },
	        tooltip: {
	        	style:{
	                color:'#888888',
	                fontFamily:'Microsoft YaHei'
	              },
		          formatter: function() {
		            return this.y.toFixed(2)+'%';
		          }
	        },
	        plotOptions: {
	            bar: {
	                dataLabels: {
	                    enabled: true
	                }
	            }
	        },
	        legend: {
	            layout: 'vertical',
	            align: 'right',
	            verticalAlign: 'top',
	            x: -40,
	            y: 100,
	            floating: true,
	            borderWidth: 1,
	            backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
	            shadow: true
	        },
	        credits: {
	            enabled: false
	        },
	        series: [{}]
	    };
	return option;
}<file_sep>/resource/js/list.js
$(function(){
	$('a.delBtn').click(function(){
		if(confirm('确定删除吗?')){
			window.location=$(this).attr('href');
		}
		return false;
	});
	$('a.pubBtn').click(function(){
		if(confirm('确定发布吗?')){
			window.location=$(this).attr('href');
		}
		return false;
	});
	$('a.overBtn').click(function(){
		if(confirm('确定结束这个问卷吗?')){
			window.location=$(this).attr('href');
		}
		return false;
	});
	
	$('a.recover').click(function(){
		if(confirm('确定恢复这个问卷吗?')){
			window.location=$(this).attr('href');
		}
		return false;
	});
});<file_sep>/App/Model/Questionnaire.php
<?php
FLEA::loadClass('FLEA_Db_TableDataGateway');
class Model_Questionnaire extends FLEA_Db_TableDataGateway
{
	var $tableName = 'questionnaire';
	var $primaryKey = 'id';
	
}

?><file_sep>/App/Model/QsAbstract.php
<?php
FLEA::loadClass('FLEA_Db_TableDataGateway');
class Model_QsAbstract extends FLEA_Db_TableDataGateway
{
	var $tableName = 'qs_abstract';
	var $primaryKey = 'id';

}

?><file_sep>/App/Model/QsAnswer.php
<?php
FLEA::loadClass('FLEA_Db_TableDataGateway');
class Model_QsAnswer extends FLEA_Db_TableDataGateway
{
	var $tableName = 'qs_answer';
	var $primaryKey = 'id';

	function getMaxNumGoupByQid($qnnaid){
		$ans=$this->find(array('qs_id'=>$qnnaid),'id desc');
		return !isset($ans['id'])?1:($ans['num']*1+1);
	}
}

?><file_sep>/App/Controller/As.php
<?php
class Controller_As extends FLEA_Controller_Action {
	/**
	 *
	 * Enter description here ...
	 * @var Class_Common
	 */
	var $_common;
	var $_admin;
	var $_adminid;
	var $_qs;
	var $_qe;
	var $_op;
	var $_qs_answer;
	var $_qs_answer_detail;
	var $_qs_abstract;
	var $_qepath;
	var $_qecon;

	function __construct() {
		$this->_common = get_singleton ( "Class_Common" );
		$this->_admin = get_singleton ( "Model_Admin" );
		$this->_qs = get_singleton ( "Model_Qs" );
		$this->_qe = get_singleton ( "Model_Qe" );
		$this->_op = get_singleton ( "Model_Op" );
		$this->_qs_answer = get_singleton ( "Model_QsAnswer" );
		$this->_qs_answer_detail = get_singleton ( "Model_QsAnswerDetail" );
		$this->_qs_abstract = get_singleton ( "Model_QsAbstract" );
		$this->_qepath=get_singleton ( "Model_QePath" );
		$this->_qecon=get_singleton ( "Model_QeCon" );
	}

	//短链接跳转
	function actionQrcode() {
		$short = isset ( $_GET ['short'] ) ? $this->_common->filter($_GET ['short']) : '';
		$questionnaire=$this->_qs->find(array('short'=>$short),'id desc');
		if(@$questionnaire['status']=='1'){
			$url=url('As','Index',array('qid'=>$questionnaire['id']));
			redirect($url);
			return ;
		}
		if($questionnaire['status']=='0'){
			echo '<h1>调查问卷还没发布</h1>';
		}elseif($questionnaire['status']=='2'){
			echo '<h1>调查问卷已经结束</h1>';
		}else{
			echo '<h1>找不到相关问卷,请联系管理员</h1>';
		}
		
	}
	
	//回答问卷
	function actionIndex(){
		$qsid = isset ( $_GET ['qid'] ) ? $this->_common->filter($_GET ['qid']) : '';
		$questionnaire=$this->_qs->findByField('id',$qsid);
		$abstract=$this->_qs_abstract->findAll(array('qs_id'=>$qsid),'id asc');
		$qepath=$this->_qepath->findAll(array('qs_id'=>$qsid,'step'=>0));//第一组随机问题
		$tmparr=array();
		foreach ($qepath as $qk=>$p){
			$tmparr[$qk]=$p['probability'];
		}
		$pk=$this->get_rand($tmparr);
		$question=$this->_qe->findByField('id',$qepath[$pk]['qe_id']);
		$question['option']=$this->_op->findAll(array('qe_id'=>$question['id']),'id asc');
		//获取答题路径及条件,供js判断
		$path=$this->_qepath->findAll(array('qs_id'=>$qsid,' step > 0 and qe_id <> '.$question['id']),'step asc,id asc');
		$qesall=$qes=$qe=array();
		$step='';
		foreach ($path as $p){
			if($step!=$p['step']&&($p['flag_over']==2||$p['step']==$questionnaire['step_num']) ){//默认随机问题排除触发结束
				if(count($qe)>0){$qes[]=$qe;}
				$qe=array();
			}
			$ques=$this->_qe->findByField('id',$p['qe_id']);
			$ques['option']=$this->_op->findAll(array('qe_id'=>$ques['id']),"id");
			$p['question']=$ques;
			$qe[]=$p;//结构化路径
			$step=$p['step'];
			$qesall[]=$p;//所有问题
		}
		if(count($qe)>0){$qes[]=$qe;}//结构化路径
		$qecon=$this->_qecon->findAll(array('qs_id'=>$qsid));
		$qes=$this->restructure($qes);//重构内容按概率出题
		//print_r($qes);//exit();
		$signinfo=$this->_admin->findByField('adm_name','admin');
		$this->_common->display('as/answer.tpl',array ('questionnaire'=>$questionnaire,'abstract'=>$abstract,'question'=>$question,'qesall'=>$qesall,'qes'=>$qes,'qecon'=>$qecon,'signinfo'=>$signinfo) );
	}
	
	//问题结果重构
	function restructure($list){
		$newlist=array();
		foreach ($list as $k => $d){
			$arr=array();
			foreach ($d as $qk=>$q){
				$arr[$qk]=$q['probability'];
			}
			$tk=$this->get_rand($arr);
			$repeatFlag=0;
			foreach ($newlist as $n){
				if($n['qe_id']==$d[$tk]['qe_id']){
					$repeatFlag=1;
				}
			}
			$newlist[$k]=$d[$tk];
		}
		if($repeatFlag){
			return $this->restructure($list);
		}else{
			return $newlist;
		}
	}
	
	//根据概率获取结果
	function get_rand($proArr) {
		$result = '';
		//概率数组的总概率精度
		$proSum = array_sum($proArr);
		//概率数组循环
		foreach ($proArr as $key => $proCur) {
			$randNum = mt_rand(1, $proSum);
			if ($randNum <= $proCur) {
				$result = $key;
				break;
			} else {
				$proSum -= $proCur;
			}
		}
		unset ($proArr);
	
		return $result;
	}
	
	//提交问卷
	function actionSubmit(){
		$data = $this->_common->filter($_POST);
		$act = isset ( $data ['act'] ) ? $data ['act'] : '';
		$qnnaid = isset ( $data ['questionnaire_unit'] ) ? $data ['questionnaire_unit'] : '';
		if($act=='submit'&&!empty($qnnaid)){
			$questionnaire=$this->_qs->findByField('id',$qnnaid);
			if($questionnaire['status']=='0'){
				$ref=$_SERVER['HTTP_REFERER'];
				echo '<h1>调查问卷还没发布,您不能答题<br><a href="'.$ref.'" >返回</a><';
				return ;
			}
			if($questionnaire['status']=='2'){
				$ref=$_SERVER['HTTP_REFERER'];
				echo '<h1>调查问卷已结束,您不能答题<br><a href="'.$ref.'" >返回</a>';
				return ;
			}
			$passtime='';
			$time=$data['time'];
			//$d = intval($time/86400);
			$h = round(($time%86400)/3600);
			$m = round(($time%3600)/60);
			$s = round(($time%60));
			$passtime.=$h>0?$h.'时':'';
			$passtime.=$m>0?$m.'分':'';
			$passtime.=$s.'秒';
			//回答信息
			$answer=array('qs_id'=>$qnnaid,'pass_time'=>$passtime,'num'=>$this->_qs_answer->getMaxNumGoupByQid($qnnaid),'ip'=>$_SERVER['REMOTE_ADDR']);
			$ansid=$this->_qs_answer->create($answer);
			$quesnum=$data['quesnum'];
			for($i=0;$i<$quesnum;$i++){
				$asoption=$data['check'.$i];
				if(is_array($asoption)){//多选
					foreach ($asoption as $aopt){
						$asdetial=array('qs_answer_id'=>$ansid,'qs_id'=>$qnnaid,'qe_id'=>$data['questionid'.$i],'op_id'=>$aopt,'qs_answer_content'=>$data['anscontent'.$aopt]);
						$this->_qs_answer_detail->create($asdetial);
					}
				}else{
					$asdetial=array('qs_answer_id'=>$ansid,'qs_id'=>$qnnaid,'qe_id'=>$data['questionid'.$i],'op_id'=>$asoption,'qs_answer_content'=>$data['anscontent'.$asoption]);
					$this->_qs_answer_detail->create($asdetial);
				}
				$this->_qe->addTimes($data['questionid'.$i]);//添加答题次数
			}
			$url=url('As','Complete');
			redirect($url);
		}
	}
	
	//完成问卷
	function actionComplete(){
		$signinfo=$this->_admin->findByField('adm_name','admin');
		$this->_common->display('as/complete.tpl',array('msg'=>'感谢您的提交!','signinfo'=>$signinfo));
	}
	
	function actionPreview(){
		$config = FLEA::getAppInf ( 'dbDSN' );
		$prefix = $config ['prefix'];
		$aid = isset ( $_GET ['qid'] ) ? $this->_common->filter($_GET['qid']) : '';
		$answer=$this->_qs_answer->findByField('id',$aid);
		if(empty($answer['id'])){
			echo '答题内容不存在,可能已被删除';
			return;
		}
		$questionnaire=$this->_qs->findByField('id',$answer['qs_id']);
		$abstract=$this->_qs_abstract->findAll(array('qs_id'=>$aid));
		$detailsql="select qe.* from ".$prefix."qe qe left join ".$prefix."qs_answer_detail ad on qe.id=ad.qe_id 
				where ad.qs_answer_id=".$aid." group by qe.id";
		$question=$this->_qe->findBySql($detailsql);
		foreach ($question as $k=>$q){
			//查找答题选项
			$sql="select opt.content,ad.qs_answer_content as answer_content from ".$prefix."qs_answer_detail ad left join ".$prefix."op opt on ad.op_id=opt.id 
					where ad.qs_answer_id=$aid and ad.qe_id=".$q['id'];
			$o=$this->_qs_answer_detail->findBySql($sql);
			$contentstr=array();
			$answerstr=array();
			foreach ($o as $oo){
				$contentstr[]=$oo['content'];
				$answerstr[]=$oo['answer_content'];
			}
			$contentstr=implode(',', $contentstr);
			$answerstr=implode(',', $answerstr);
			$answer_content='';
			if($q['type']=='1'||$q['type']=='2'){
				$answer_content=$contentstr;
			}else{
				$contentstr=explode("@text", $contentstr);
				$answerstr=explode(",", $answerstr);
				foreach ($contentstr as $ck=>$c){
					$answer_content.=$c.$answerstr[$ck];
				}
			}
			$question[$k]['answer']=$answer_content;
		}

		$this->_common->display('as/preview.tpl',array('answer'=>$answer,'questionnaire'=>$questionnaire,'question'=>$question,'abstract'=>$abstract));
	}
	
	function actionAnalysis(){
		$config = FLEA::getAppInf ( 'dbDSN' );
		$prefix = $config ['prefix'];
		$qnnaid = isset ( $_GET ['qnnaid'] ) ?$this->_common->filter($_GET ['qnnaid'])  : '';
		$questionnaire=$this->_qs->findByField('id',$qnnaid);
		$question=$this->_qe->findBySql("select qe.*,path.qs_id from ".$prefix."qe qe left join ".$prefix."qepath path on path.qe_id = qe.id where path.qs_id=$qnnaid");
		foreach ($question as $k=>$q){
			$options=$this->_op->findAll(array('qe_id'=>$q['id']));
			foreach ($options as $opk=>$op){
				$options[$opk]['count']=$this->_qs_answer_detail->findCount(array('qs_id'=>$qnnaid,'qe_id'=>$q['id'],'op_id'=>$op['id']));
			}
			$question[$k]['option']=$options;
		}
		$questionnaire['anscount']=$this->_qs_answer->findCount(array('qs_id'=>$qnnaid));
		
		//查看答卷详情
		$pageparm = array ('qnnaid'=>$qnnaid);//9删除
		$page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1;
		$page_size = 50;
		$title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : '';
		
		$conditions=array('qs_id'=>$qnnaid);
		if(!empty($title)){
			$conditions[]="title like '%$title%'";
			$pageparm['title']=$title;
		}
		
		$total=$this->_qs_answer->findCount($conditions);
		
		$pages = & get_singleton ( "Service_Page" );
		$pages->_page_no = $page_no;
		$pages->_page_num = $page_size;
		$pages->_total = $total;
		$pages->_url = url ( "As", "Analysis");
		$pages->_parm = $pageparm;
		$page = $pages->analysisPage ();
		$start = ($page_no - 1) * $page_size;
		
		$answerlist=$this->_qs_answer->findAll($conditions,"id desc limit $start,$page_size");
		foreach ($answerlist as $k=>$v){
			$anses=array();
			foreach ($question as $qk=>$q){
				$sql="select op.content,ad.qs_answer_content as answer_content from ".$prefix."qs_answer_detail ad 
					left join ".$prefix."op op on op.id=ad.op_id 
					where ad.qe_id=".$q['id']." and ad.qs_answer_id=".$v['id'];
				$o=$this->_qs_answer_detail->findBySql($sql);
				$content=array();
				$answer=array();
				foreach ($o as $oo){
					$content[]=$oo['content'];
					$answer[]=$oo['answer_content'];
				}
				$content=implode(',', $content);
				$answer=implode(',', $answer);
				$answer_content='';
				if($q['type']=='1'||$q['type']=='2'){
					$answer_content=$content;
				}else{
					$content=explode("@text", $content);
					$answer=explode(",", $answer);
					foreach ($content as $ck=>$c){
						$c.=@$answer[$ck];
						$answer_content.=$c;
					}
				}
				$anses[]=array('content'=>$answer_content,'qetype'=>$q['type']);
			}
			$answerlist[$k]['answer']=$anses;
			
		}
		
		$this->_common->display('as/analysis.tpl', array ('questionnaire'=>$questionnaire,'question'=>$question,'answerlist'=>$answerlist,'page'=>$page,'pageparm'=>$pageparm) );
	}
	
}



<file_sep>/result.php
<?php
require_once 'const.php';

header("Location:".SITEHOST.'/index.php?controller=Answer&action=Analysis&qnnaid='.$_GET['qnnaid']);<file_sep>/resource/js/qsadd.js
$(function(){
	//添加图文摘要
	$('#addAbstract').click(function(){
		var num=$('#abstractnum').val();
		++num;
		$('#addAbsTr').before('<tr><td style="text-align:center;"><input name="abstract'+num+'[title]" type="text" value="摘要'+num+'" style="width:50px;" /></td><td><textarea name="abstract'+num+'[content]" style="width:700px;height:150px;"></textarea></td></tr>'+
            '<tr><td style="text-align:center;">图片'+num+'</td><td><input name="abstractimg'+num+'" type="file" style="width:700px;"></td></tr>'+
            '<tr><td style="text-align:center;">图片信息'+num+'</td><td><textarea name="abstract'+num+'[imginfo]" value="" style="width:700px;height:50px;"></textarea></td></tr>');
		$('#abstractnum').val(num);
	});
	//选中路径
	$('.tk_lm').live('click',function(){
		//当前第几步路径
		$('.selectedstep').val($('.tk_lm').index($(this)));
		$('.tk_lm').removeClass('tk_lmon');
		$(this).addClass('tk_lmon');
	});
	//添加问题到路径中
	$('.tk_rm1 li').click(function(){
		var step=$('.selectedstep').val();
		var no=$(this).find('.no').val();
		var qeid=$(this).find('.qeid').val();
		var qetitle=$(this).find('.qetitle').val();
		//添加路径隐藏属性
		$('.tk_lmon ul').append($(this).clone().addClass('tooltip').attr('title',qetitle).html('<span>R</span><p>'+no+'</p><input type="hidden" name="step[]" class="step" value="'+step+'" /><input type="hidden" name="qeid[]" class="qeid" value="'+qeid+'" /><input type="hidden" name="probability[]" class="probability" value="1" /><input type="hidden" value="2" class="hascon" name="hascon[]" /><input type="hidden" value="1" class="aslimit" name="aslimit[]" /><input type="hidden" value="2" class="flag_over" name="flag_over[]" /><input type="hidden" class="qetitle" value="'+qetitle+'" />'));
		$('.tooltip').tooltipster();
	});
	//移除问题
	$('#removeQe').click(function(){
		if(confirm('是否移除?')){
			$('.tk_lm ul li.selected').remove();
			$('.tck_box').hide();
		}
	});
	//查看详细
	$('.tk_lm ul li').live('click',function(){
		$('.tk_lm ul li').removeClass('selected');
		$(this).addClass('selected');
		var url=$('#getOpsByQeUrl').val();
		var qeid=$(this).find('.qeid').val();
		var step=$(this).find('.step').val();
		var probability=$(this).find('.probability').val();
		var aslimit=$(this).find('.aslimit').val();
		var flag_over=$(this).find('.flag_over').val();
		var beftk=step;
		var beftklmqe=$('.tk_lm:lt('+beftk+')').find('li');
		$.ajax({
			type:'post',
			url:url,
			data:{'qeid':qeid},
			dataType:'json',
			success:function(res){
				//问题详情
				$('#tc_qeTitle').text('').html('<font color="red">'+res.no+'</font>&nbsp;'+res.title);
				$('#tc_ulops').html('');
				for(i in res.op){
					$('#tc_ulops').append('<li>'+res.op[i].content+'</li>');
				}
				$('.qeBeforeCon').html('');
				$('.qeProbability').val(probability);
				$('.qeAslimit').val(aslimit);
				if(flag_over==1){
					$('.qeFlagOver').eq(0).removeAttr('checked');
					$('.qeFlagOver').eq(1).attr('checked','checked');
				}else{
					$('.qeFlagOver').eq(0).attr('checked','checked');
					$('.qeFlagOver').eq(1).removeAttr('checked');
				}
				
				//前置条件
				if(step==0){
					$('.qeBeforeCon').text('无');
					$('#addCondition').attr('disabled','disabled');
				}else{
					$('#addCondition').removeAttr('disabled');
					var strda='';
					$('.tk_lmon li.selected input[name^=consprevqe]').each(function(i){
						strda+='qe[]='+$(this).val()+'&op[]='+$('.tk_lmon li.selected input[name^=consprevop]').eq(i).val()+'&';
					});
					if(strda!=''){//原先有条件的情况
						var getconurl=$('#getBeforeConUrl').val();
						//填充条件
						$.ajax({
							type:'post',
							url:getconurl,
							data:strda,
							dataType:'json',
							success:function(res){
								var str='';
								for(i in res){
									str+='<select class="questionCondition">';
									str+='<option value="">请选择</option>';
									beftklmqe.each(function(tkli){
										var sected=(res[i].qeid==$(this).find('.qeid').val())?'selected':'';
										str+='<option '+sected+' value="'+$(this).find('.qeid').val()+'">'+$(this).find('p').text()+'('+$(this).find('.qetitle').val()+')</option>'
									})
									var opstr='';
									var inputattr='type="checkbox" ';
									if(res[i].qetype=='2'){
										inputattr='type="checkbox" ';
									}
									for(opk in res[i].ops){
										sected='';
										for(s in res[i].opids){
											if(res[i].opids[s]==res[i].ops[opk].id){
												sected='checked';
											}
										}
										opstr+='<li><label><input class="selectop" '+sected+' '+inputattr+' name="radiocon'+i+'" value="'+res[i].ops[opk].id+'">'+res[i].ops[opk].content+'</label></li>';
									}
									
									str+='</select><br><div class="dxt"><ul class="optionCondition">'+opstr+'</ul></div><br>'+'<div class="cls"></div>';
								}
								$('.qeBeforeCon').html(str);
							}
						});
					}else{//默认无值的情况
						var str='<select class="questionCondition">';
						str+='<option value="">请选择</option>';
						beftklmqe.each(function(tkli){
							str+='<option value="'+$(this).find('.qeid').val()+'">'+$(this).find('p').text()+'('+$(this).find('.qetitle').val()+')</option>'
						})
						str+='</select><br><div class="dxt"><ul class="optionCondition"></ul></div><br>';
						$('.qeBeforeCon').html(str+'<div class="cls"></div>');
					}
					
				}
				$('.tck_box').show();
			}
		})
	});
	//条件
	$('.questionCondition').live('change',function(){
		var url=$('#getOpsByQeUrl').val();
		var index=$('.questionCondition').index($(this));
		var options=$('.optionCondition').eq(index);
		var qeid=$(this).val();
		$.ajax({
			type:'post',
			url:url,
			data:{'qeid':qeid},
			dataType:'json',
			success:function(res){
				options.html('');
				var inputattr='type="checkbox" name="radiocon'+index+'"';
				if(res.type=='2'){
					inputattr='type="checkbox" name="radiocon'+index+'"';
				}
				for(i in res.op){
					options.append('<li><label><input class="selectop" '+inputattr+' value="'+res.op[i].id+'">'+res.op[i].content+'</label></li>');
				}
			}
		})
	});
	//添加条件
	$('#addCondition').click(function(){
		var ops=$('.questionCondition').last().clone().html();//前一个问题选项
		var str='<select class="questionCondition">';
		str+=ops;
		str+='</select><br><div class="dxt"><ul class="optionCondition"></ul></div><br>';
		$('.qeBeforeCon').append(str+'<div class="cls"></div>');
	});
	//确认条件
	$('#subCondition').click(function(){
		//问题出现概率
		$('.tk_lmon li.selected input.probability').val($('.qeProbability').val());
		$('.tk_lmon li.selected input.aslimit').val($('.qeAslimit').val());
		$('.tk_lmon li.selected input.flag_over').val($('.qeFlagOver:checked').val());
		
		$('.tk_lmon li.selected input[name^=consprevqe]').remove();
		$('.tk_lmon li.selected input[name^=consprevop]').remove();
		$('.tk_lmon li.selected input[name^=consqeid]').remove();
		$('.tk_lmon li.selected input[name^=constep]').remove();
		$('.questionCondition').each(function(i){
			var qeid=$(this).val();
			$('.optionCondition').eq(i).find('input:checked').each(function(oi){
				$('.tk_lmon li.selected').append('<input type="hidden" name="consprevqe[]" value="'+qeid+'" /><input type="hidden" name="consprevop[]" value="'+$(this).val()+'" /><input type="hidden" name="consqeid[]" value="'+$('.tk_lmon li.selected input.qeid').val()+'" /><input type="hidden" name="constep[]" value="'+$('.tk_lmon li.selected input.step').val()+'" />');
			});
		});
		if($('.optionCondition li').length>0){//有前置条件
			$('.tk_lmon li.selected input.hascon').val(1);
			$('.tk_lmon li.selected span').text('C');
		}else{//无前置条件
			$('.tk_lmon li.selected input.hascon').val(2);
			$('.tk_lmon li.selected span').text('R');
		}
		$('.tck_box').hide();
	});
	//鼠标滚动
	$(window).scroll(function(){
//		if($(window).scrollTop() > $('.tk_l').offset().top){
//			$('.tk_l').css('margin-top',($(window).scrollTop()-$('.tk_l').offset().top)+'px');
//		}
	});
	//弹出框
	$('body').append($('.tck_box'));
	$('#tck_close').click(function(){
		$('.tck_box').hide();
		$('.tk_lm ul li').removeClass('selected');
	});
	//鼠标hover效果
//	$('li[class^=icon]').hover(function(){
//		//alert($(this).find('.qetitle').val())
//	},function(){
//		
//	});
	$('.tooltip').tooltipster();
	//添加路径框
	$('#addpath').click(function(){
		$(this).prev().removeClass('wx');
		$(this).before('<div class="tk_lm wx"><ul></ul><div class="cls"></div></div>');
	});
	//查找题库
	$('.searchCategory').change(function(){
		var cid=$(this).val();
		if(cid==''){
			$(this).parent().next().find('li').show();
			return;
		}
		$(this).parent().next().find('li').each(function(){
			if($(this).find('.qecate').val()==cid){
				$(this).show();
			}else{
				$(this).hide();
			}
		});
	});
	$('.searchQeBtn').click(function(){
		var key=$(this).prev().val();
		if(key==''){
			$(this).parent().next().find('li').show();
			return;
		}
		$(this).parent().next().find('li').each(function(){
			var str=$(this).find('.qetitle').val();
			if(str.indexOf(key)!=-1){
				$(this).show();
			}else{
				$(this).hide();
			}
		});
	});
	$('.searchAll').click(function(){
		$(this).parent().next().find('li').show();
		//$(this).parent().find('.searchTitle').val('');
	});
});


function checkFrom(){
	var flag=true;
	var title=$('#qs_title').val();
	var status=$('#questionnaire_status').val();
	var msg='';
	if($.trim(title)==''){
		msg+='请填写问卷标题\n';
		flag=false;
	}
	if($.trim(status)=='1'){
		msg+='问卷已发布不可编辑\n';
		flag=false;
	}
	if($.trim(status)=='2'){
		msg+='问卷已结束不可编辑\n';
		flag=false;
	}
	if(!flag){
		alert(msg);
	}
	return flag;
}<file_sep>/App/Controller/Questionnaire.php
<?php
require_once SERVERROOT. DS . 'App' . DS . 'Class' .DS.'phpqrcode.php';
require_once SERVERROOT. DS . 'weixin' . DS . 'wechat.php';
class Controller_Questionnaire extends FLEA_Controller_Action {
	/**
	 *
	 * Enter description here ...
	 * @var Class_Common
	 */
	var $_common;
	var $_admin;
	var $_adminid;
	var $_questionnaire;
	var $_question;
	var $_option;
	var $_answer;
	var $_abstract;

	function __construct() {
		$this->_common = get_singleton ( "Class_Common" );

		$this->_admin = get_singleton ( "Model_Admin" );
		$this->_questionnaire = get_singleton ( "Model_Questionnaire" );
		$this->_question = get_singleton ( "Model_Question" );
		$this->_option = get_singleton ( "Model_Option" );
		$this->_answer = get_singleton ( "Model_Answer" );
		$this->_abstract = get_singleton ( "Model_Abstract" );
		$this->_adminid = isset ( $_SESSION ['loginuserid'] ) ? $_SESSION ['loginuserid'] : "";
		if(empty($_SESSION ['loginuserid'])){
			$url=url("Default","Login");
			redirect($url);
		}
	}

	//问卷列表
	function actionIndex() {
		$pageparm = array ('status != 9 and status != 2');//9删除
		$page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1;
		$page_size = 20;
		$title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : '';

		$conditions=array('status != 9 and status != 2');
		if(!empty($title)){
			$conditions[]="title like '%$title%'";
			$pageparm['title']=$title;
		}

		$total=$this->_questionnaire->findCount($conditions);

		$pages = & get_singleton ( "Service_Page" );
		$pages->_page_no = $page_no;
		$pages->_page_num = $page_size;
		$pages->_total = $total;
		$pages->_url = url ( "Questionnaire", "Index" );
		$pages->_parm = $pageparm;
		$page = $pages->page ();
		$start = ($page_no - 1) * $page_size;

		$list=$this->_questionnaire->findAll($conditions,"id desc limit $start,$page_size");
		foreach ($list as $k=>$d){
			$list[$k]['num']=$this->_answer->findCount(array('questionnaire_id'=>$d['id']));
			$list[$k]['updated']=$this->_common->time2Units(time()-strtotime($d['updated']));
		}
		$this->_common->show ( array ('main' => 'questionnaire/list.tpl','list'=>$list,'page'=>$page,'pageparm'=>$pageparm) );
	}
	
	//完成的问卷列表
	function actionFinshed(){
		$pageparm = array ('status = 2');//9删除
		$page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1;
		$page_size = 20;
		$title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : '';

		$conditions=array('status = 2');
		if(!empty($title)){
			$conditions[]="title like '%$title%'";
			$pageparm['title']=$title;
		}

		$total=$this->_questionnaire->findCount($conditions);

		$pages = & get_singleton ( "Service_Page" );
		$pages->_page_no = $page_no;
		$pages->_page_num = $page_size;
		$pages->_total = $total;
		$pages->_url = url ( "Questionnaire", "Finshed" );
		$pages->_parm = $pageparm;
		$page = $pages->page ();
		$start = ($page_no - 1) * $page_size;

		$list=$this->_questionnaire->findAll($conditions,"id desc limit $start,$page_size");
		foreach ($list as $k=>$d){
			$list[$k]['num']=$this->_answer->findCount(array('questionnaire_id'=>$d['id']));
		}
		$this->_common->show ( array ('main' => 'questionnaire/list.tpl','list'=>$list,'page'=>$page,'pageparm'=>$pageparm) );
	}
	
	
	//问卷新增
	function actionAdd(){
		$act=isset ( $_POST ['act'] ) ? $_POST ['act'] : '';
		if($act=='add'){
			$data=$this->_common->filter($_POST['data']);
			$data['author']=htmlspecialchars_decode($data['author']);
			//问卷设置
			$data['over_num']=intval($data['over_num']);
			if(empty($data['over_num'])){
				unset($data['over_num']);
			}
			if(empty($data['over_date'])){
				unset($data['over_date']);
			}
			
			//短连接及二维码
			$shoturl=url('Answer','Index',array('time'=>time()));
			$shoturl=$this->_common->shortUrl($shoturl);
			$data['short']=$shoturl;
			$data['qrcode']=$this->createQr($shoturl);
			$data['created']=date("Y-m-d H:i:s");
			//创建问卷
			$questionnaire_id=$this->_questionnaire->create($data);
			//创建摘要
			$Upload= & get_singleton ( "Service_UpLoad" );
			$folder="resource/upload/abstract/";
			if (! file_exists ( $folder )) {
				mkdir ( $folder, 0777 );
			}
			$Upload->setDir($folder.date("Ymd")."/");
			$absnum=$_POST['abstractnum'];
			for ($i=0;$i<$absnum;$i++){
				$abstract=array();
				$numi=($i+1);
				$Upload->setPrefixName($i);
				$img=$Upload->upload('abstractimg'.$numi);
				if($img['status']==1){
					$file_path=$img['file_path'];
				}
				$abstract['questionnaire_id']=$questionnaire_id;
				$abstract['title']=$_POST['abstract'.$numi]['title'];
				$abstract['content']=$_POST['abstract'.$numi]['content'];
				$abstract['imginfo']=$_POST['abstract'.$numi]['imginfo'];
				$abstract['img']=$file_path;
				$this->_abstract->create($abstract);
			}
			//创建答题选项
			$questionnum=$this->_common->filter($_POST['questionnum']);
			for($i=0;$i<$questionnum;$i++){
				//创建问题
				if(isset($_POST['question'.$i])){
					$question=$this->_common->filter($_POST['question'.$i]);
					$question['questionnaire_id']=$questionnaire_id;
					$question['num']=($i+1);
					$question_id=$this->_question->create($question);
					foreach($question['content'] as $c){
						//创建选项
						if(!empty($c)){
							$option=array('content'=>$c,'questionnaire_id'=>$questionnaire_id,'question_id'=>$question_id);
							$this->_option->create($option);
						}
					}
				}
			}
			$url=url('Questionnaire','Index');
			redirect($url);
		}
		$this->_common->show ( array ('main' => 'questionnaire/add.tpl') );
	}
	
	//问卷编辑
	function actionEdit(){
		$qnnaid=isset ( $_GET ['qnnaid'] ) ? $_GET ['qnnaid'] : '';
		$act=isset ( $_POST ['act'] ) ? $_POST ['act'] : '';
		$msg='';
		if($act=='edit'){
			$data=$this->_common->filter($_POST['data']);
			$data['author']=htmlspecialchars_decode($data['author']);
			//问卷设置
			$data['over_num']=intval($data['over_num']);
			if(empty($data['over_num'])){
				unset($data['over_num']);
			}
			if(empty($data['over_date'])){
				unset($data['over_date']);
			}
			//清除旧二维码
			if(file_exists ( $data['qrcode'] )){
				unlink($data['qrcode']);
			}
			//短连接及二维码
			$shoturl=url('Answer','Index',array('time'=>time()));
			$shoturl=$this->_common->shortUrl($shoturl);
			$data['short']=$shoturl;
			$data['qrcode']=$this->createQr($shoturl);
			//创建问卷
			$questionnaire_id=$data['id'];
			$this->_questionnaire->update($data);
			//清除摘要和选项
			$this->_abstract->removeByConditions(array('questionnaire_id'=>$questionnaire_id));
			$this->_question->removeByConditions(array('questionnaire_id'=>$questionnaire_id));
			$this->_option->removeByConditions(array('questionnaire_id'=>$questionnaire_id));
			//创建摘要
			$Upload= & get_singleton ( "Service_UpLoad" );
			$folder="resource/upload/abstract/";
			if (! file_exists ( $folder )) {
				mkdir ( $folder, 0777 );
			}
			$Upload->setDir($folder.date("Ymd")."/");
			$absnum=$_POST['abstractnum'];
			for ($i=0;$i<$absnum;$i++){
				$abstract=array();
				$numi=($i+1);
				$Upload->setPrefixName($i);
				$img=$Upload->upload('abstractimg'.$numi);
				$oldimg=$_POST['abstract'.$numi]['img'];
				if($img['status']==1){//如果有上传图片则更新
					$file_path=$img['file_path'];
					if(file_exists($oldimg)){
						unlink($oldimg);
					}
				}else{
					$file_path=$oldimg;
				}
				$abstract['questionnaire_id']=$questionnaire_id;
				$abstract['title']=$_POST['abstract'.$numi]['title'];
				$abstract['content']=$_POST['abstract'.$numi]['content'];
				$abstract['imginfo']=$_POST['abstract'.$numi]['imginfo'];
				$abstract['img']=$file_path;
				$this->_abstract->create($abstract);
			}
			//创建答题选项
			$questionnum=$this->_common->filter($_POST['questionnum']);
			for($i=0;$i<$questionnum;$i++){
				//创建问题
				if(isset($_POST['question'.$i])){
					$question=$this->_common->filter($_POST['question'.$i]);
					$question['questionnaire_id']=$questionnaire_id;
					$question['num']=($i+1);
					$question_id=$this->_question->create($question);
					foreach($question['content'] as $c){
						//创建选项
						if(!empty($c)){
							$option=array('content'=>$c,'questionnaire_id'=>$questionnaire_id,'question_id'=>$question_id);
							$this->_option->create($option);
						}
					}
				}
			}
			$msg='问卷更新成功!';
		}
		
		$questionnaire=$this->_questionnaire->findByField('id',$qnnaid);
		$abstract=$this->_abstract->findAll(array('questionnaire_id'=>$qnnaid),'id asc');
		$question=$this->_question->findAll(array('questionnaire_id'=>$qnnaid),'num,id desc');
		foreach ($question as $k=>$q){
			$question[$k]['option']=$this->_option->findAll(array('question_id'=>$q['id']),'id asc');
		}
		$this->_common->show ( array ('main' => 'questionnaire/edit.tpl','questionnaire'=>$questionnaire,'abstract'=>$abstract,'question'=>$question,'msg'=>$msg) );
	}
	
	//被删除的问卷列表
	function actionDeList() {
		$pageparm = array ('status = 9');//9删除
		$page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1;
		$page_size = 20;
		$title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : '';
	
		$conditions=array('status = 9');
		if(!empty($title)){
			$conditions[]="title like '%$title%'";
			$pageparm['title']=$title;
		}
	
		$total=$this->_questionnaire->findCount($conditions);
	
		$pages = & get_singleton ( "Service_Page" );
		$pages->_page_no = $page_no;
		$pages->_page_num = $page_size;
		$pages->_total = $total;
		$pages->_url = url ( "Questionnaire", "DeList" );
		$pages->_parm = $pageparm;
		$page = $pages->page ();
		$start = ($page_no - 1) * $page_size;
	
		$list=$this->_questionnaire->findAll($conditions,"id desc limit $start,$page_size");
		foreach ($list as $k=>$d){
			$list[$k]['num']=$this->_answer->findCount(array('questionnaire_id'=>$d['id']));
			$list[$k]['updated']=$this->_common->time2Units(time()-strtotime($d['updated']));
		}
		$this->_common->show ( array ('main' => 'questionnaire/delist.tpl','list'=>$list,'page'=>$page,'pageparm'=>$pageparm) );
	}
	
	
	
	//再次发布
	function actionRePublic(){
		$qnnaid=isset ( $_GET ['qnnaid'] ) ? $_GET ['qnnaid'] : '';
		$questionnaire=$this->_questionnaire->findByField('id',$qnnaid);
		if(is_array($questionnaire)){
			$abstract=$this->_abstract->findAll(array('questionnaire_id'=>$qnnaid),'id asc');
			$question=$this->_question->findAll(array('questionnaire_id'=>$qnnaid),'num,id desc');
			
			unset($questionnaire['id']);
			//短连接及二维码
			$shoturl=url('Answer','Index',array('time'=>time()));
			$shoturl=$this->_common->shortUrl($shoturl);
			$questionnaire['short']=$shoturl;
			$questionnaire['qrcode']=$this->createQr($shoturl);
			$questionnaire['status']=0;
			$questionnaire['created']=date("Y-m-d H:i:s");
			$newqnnaid=$this->_questionnaire->create($questionnaire);
			foreach ($abstract as $ab){
				unset($ab['id']);
				$ab['questionnaire_id']=$newqnnaid;
				$this->_abstract->create($ab);
			}
			foreach ($question as $q){
				$options=$this->_option->findAll(array('question_id'=>$q['id']),'id asc');
				unset($q['id']);
				$q['questionnaire_id']=$newqnnaid;
				$newqid=$this->_question->create($q);
				foreach ($options as $op){
					unset($op['id']);
					$op['question_id']=$newqid;
					$op['questionnaire_id']=$newqnnaid;
					$this->_option->create($op);
				}
			}
		}
		
		$url=url('Questionnaire','Index');
		redirect($url);
	}


	function actionDel(){//删除status9
		$id=$this->_common->filter($_GET['id']);
		$eve=array('id'=>$id,'status'=>9);
		$this->_questionnaire->update($eve);
		redirect($_SERVER['HTTP_REFERER']);
	}
	function actionPublic(){ //发布status1
		$id=$this->_common->filter($_GET['id']);
		$eve=array('id'=>$id,'status'=>1);
		$this->_questionnaire->update($eve);
		redirect($_SERVER['HTTP_REFERER']);
	}
	function actionEnd(){//结束status2
		$id=$this->_common->filter($_GET['id']);
		$eve=array('id'=>$id,'status'=>2);
		$this->_questionnaire->update($eve);
		$msg=SITEHOST.'/result.php?qnnaid='.$id;
		$wechatObj = WeChat::getInstance();
		$wechatObj->sendCustomMsg('分析结果是 '.$msg,"o9ZPks_8ZpcQXBndQqjuUpt-E9tg");
		redirect($_SERVER['HTTP_REFERER']);
	}
	
	function actionRecover(){//恢复被删除的问卷
		$id=$this->_common->filter($_GET['id']);
		$eve=array('id'=>$id,'status'=>0);
		$this->_questionnaire->update($eve);
		redirect($_SERVER['HTTP_REFERER']);
	}
	
	function createQr($shoturl){
		$qrfile='resource/upload/'.$shoturl.'.png';
		$qrurl=SITEHOST.url('Answer','Qrcode',array('short'=>$shoturl));
		QRcode::png($qrurl,$qrfile,0,7,1);//生成二维码
		//file_put_contents($qrfile , file_get_contents($this->_common->downloadQRpngfromGoogle($qrurl,300,300)));//生成本地图片
		return $qrfile;
	}
}
<file_sep>/resource/js/add.js
$(function(){
	//添加图文摘要
	$('#addAbstract').click(function(){
		var num=$('#abstractnum').val();
		++num;
		$('#addAbsTr').before('<tr><td style="text-align:center;"><input name="abstract'+num+'[title]" type="text" value="摘要'+num+'" style="width:50px;padding:0;" /></td><td><textarea name="abstract'+num+'[content]" style="width:700px;height:150px;"></textarea></td></tr>'+
            '<tr><td style="text-align:center;">图片'+num+'</td><td><input name="abstractimg'+num+'" type="file" style="width:700px;"></td></tr>'+
            '<tr><td style="text-align:center;">图片信息'+num+'</td><td><textarea name="abstract'+num+'[imginfo]" value="" style="width:700px;height:50px;"></textarea></td></tr>');
		$('#abstractnum').val(num);
	});
	//添加选项
	$('#addSingle').click(function(){
		var num=$('#questionnum').val();
		$('#addtr').before('<tr class="qtr"><td class="qn" style="text-align:center;"></td><td>'+
            '<input type="text" name="question'+num+'[title]" value="" style="width:300px;" /><a style="float:right;" href="#" class="delQuestion">删除</a></td></tr>'+
            '<tr class="atr"><td style="text-align:center;">单选题<input type="hidden" name="question'+num+'[type]" value="1" /><br>'+
            '<input type="button" class="mvDown" value="下移" /><input type="button" class="mvUp" value="上移" /></td>'+
            '<td><input type="radio" name="question'+num+'">&nbsp;<input type="text" name="question'+num+'[content][]" value="" style="width:240px;" />'+
            '<br/><input type="radio" name="question'+num+'">&nbsp;<input type="text" name="question'+num+'[content][]" value="" style="width:240px;" />'+
		'<a href="#" class="addOption">添加选项+</a></td></tr>');
		$('#questionnum').val((num*1+1));
		resetQ();
	});
	$('#addMultiple').click(function(){
		var num=$('#questionnum').val();
		$('#addtr').before('<tr class="qtr"><td class="qn" style="text-align:center;"></td><td>'+
             '<input type="text" name="question'+num+'[title]" value="" style="width:300px;" /><a style="float:right;" href="#" class="delQuestion">删除</a></td></tr>'+
             '<tr class="atr"><td style="text-align:center;">多选题<input type="hidden" name="question'+num+'[type]" value="2" /><br>'+
             '<input type="button" class="mvDown" value="下移" /><input type="button" class="mvUp" value="上移" /></td>'+
             '<td><input type="checkbox">&nbsp;<input type="text" name="question'+num+'[content][]" value="" style="width:240px;" />'+
             '<br/><input type="checkbox">&nbsp;<input type="text" name="question'+num+'[content][]" value="" style="width:240px;" />'+
             '<a href="#" class="addOption">添加选项+</a></td></tr>');
		$('#questionnum').val((num*1+1));
		resetQ();
	});
	$('#addOpenness').click(function(){
		var num=$('#questionnum').val();
		$('#addtr').before('<tr class="qtr"><td class="qn" style="text-align:center;"></td><td>'+
            '<input type="text" name="question'+num+'[title]" value="" style="width:300px;" /><a style="float:right;" href="#" class="delQuestion">删除</a></td></tr>'+
            '<tr class="atr"><td style="text-align:center;">开放性问题<input type="hidden" name="question'+num+'[type]" value="3" /><br>'+
            '<input type="button" class="mvDown" value="下移" /><input type="button" class="mvUp" value="上移" /></td>'+
            '<td>(需要答题者填写文字的部分请用特殊符号"@text"代替,如:我认为@text)<br/>'+
            '<input type="radio" name="question'+num+'">&nbsp;<input type="text" name="question'+num+'[content][]" value="" style="width:240px;" />'+
            '<br/><input type="radio" name="question'+num+'">&nbsp;<input type="text" name="question'+num+'[content][]" value="" style="width:240px;" />'+
			'<a href="#" class="addOption">添加选项+</a></td></tr>');
		$('#questionnum').val((num*1+1));
		resetQ();
	});
	$('#addFill').click(function(){
		var num=$('#questionnum').val();
		$('#addtr').before('<tr class="qtr"><td class="qn" style="text-align:center;"></td><td>'+
            '<input type="text" name="question'+num+'[title]" value="" style="width:300px;" /><a style="float:right;" href="#" class="delQuestion">删除</a></td></tr>'+
            '<tr class="atr"><td style="text-align:center;">填空题<input type="hidden" name="question'+num+'[type]" value="4" /><br>'+
            '<input type="button" class="mvDown" value="下移" /><input type="button" class="mvUp" value="上移" /></td>'+
            '<td>(需要答题者填写文字的部分请用特殊符号"@text"代替,如:姓名是@text)<br/>'+
            '<input type="text" name="question'+num+'[content][]" value="" style="width:240px;" /></td></tr>');
		$('#questionnum').val((num*1+1));
		resetQ();
	});
	$('.delQuestion').live('click',function(){
		if(confirm('是否删除问题')){
			$(this).parent().parent().next().remove();
			$(this).parent().parent().remove();
			resetQ();
		}
		
		return false;
	});
	$('.addOption').live('click',function(){
		var optcheck=$(this).prev().prev().clone().removeAttr('checked');
		var opt=$(this).prev().clone().val('');
		$(this).before('<br/>');
		$(this).before(optcheck);
		$(this).before('&nbsp;');
		$(this).before(opt);
		return false;
	});
	//下移
	$('input.mvDown').live('click',function(){
		var thisaobj=$(this).parent().parent();
		var thisqobj=thisaobj.prev();
		var index=$('tr.atr').index(thisaobj);
		if((index+1)<=$('tr.atr').length){
			$('tr.atr').eq(index+1).after(thisqobj);
			thisqobj.after(thisaobj);
			resetQ();
		}
	});
	//上移
	$('input.mvUp').live('click',function(){
		var thisaobj=$(this).parent().parent();
		var thisqobj=thisaobj.prev();
		var index=$('tr.atr').index(thisaobj);
		if((index-1)>=0){
			$('tr.qtr').eq(index-1).before(thisaobj);
			thisaobj.before(thisqobj);
			resetQ();
		}
	});
	
});

//重新初始化问题序号
function initQuestionNum(){
	$('tr.qtr').each(function(i){
		$(this).find('input').each(function(){
			if($(this).attr('name')){
				var strname=$(this).attr('name')+'';
				strname = strname.replace(/question\d+/g,'question'+i);
				$(this).attr('name',strname+'');
			}
		});
		$(this).next().find('input').each(function(){
			if($(this).attr('name')){
				var strname=$(this).attr('name')+'';
				strname = strname.replace(/question\d+/g,'question'+i);
				$(this).attr('name',strname+'');
			}
		});
	});
}

//重置Q序号
function resetQ(){
	$('.qn').each(function(i){
		$(this).html('Q'+(i+1));
	});
	initQuestionNum();
}

function checkFrom(){
	var flag=true;
	var title=$('#questionnaire_title').val();
	var status=$('#questionnaire_status').val();
	var msg='';
	if($.trim(title)==''){
		msg+='请填写问卷标题\n';
		flag=false;
	}
	if($.trim(status)=='1'){
		msg+='问卷已发布不可编辑\n';
		flag=false;
	}
	if($.trim(status)=='2'){
		msg+='问卷已结束不可编辑\n';
		flag=false;
	}
	if(!flag){
		alert(msg);
	}
	return flag;
}<file_sep>/App/Model/Category.php
<?php
FLEA::loadClass('FLEA_Db_TableDataGateway');
class Model_Category extends FLEA_Db_TableDataGateway
{
	var $tableName = 'category';
	var $primaryKey = 'id';

}

?><file_sep>/resource/js/as.js
$(function(){
	setInterval(function(){$('#time').val($('#time').val()*1+1)},1000);
	$('#submit').click(function(){
		if($('#questionnaire_status').val()!=1){
			if($('#questionnaire_status').val()==2){
				alert('调查问卷已结束,您不能答题');
			}else{
				alert('调查问卷还没发布,您不能答题');
			}
			return false;
		}else{
			return true;
		}
	});
	$('.anstext').live('blur',function(){
		var qeobj=$(this).parent().parent();
		var type=qeobj.find('.qetype').val();
		if(type==3){
			var i=qeobj.find('.anstext').index($(this));
			qeobj.find('input[name^=anscontent]').eq(i).val($(this).val());
		}
		if(type==4){
			var str='';
			qeobj.find('.anstext').each(function(i){
				str+=$(this).val()+',';
			});
			qeobj.find('input[name^=anscontent]').val(str.slice(0,-1));
		}
	});
	
	$('#copyQurl').click(function(){
		//window.clipboardData.setData("Text等等", '需要复制的信息');
		//alert('复制成功');
		return false;
	});
	
	//判断概率出下一题
	$('.ansqe label').live('click',function(){
		//选中高亮切换
		if(!$(this).find('input:eq(0)').attr('checked')){
			//最多选择几项
			var numlimit=$(this).parent().find('.aslimit').val();
			if($(this).find('input:eq(0)').attr('type')=='checkbox'&&$(this).parent().find('input:checked').length>=numlimit){
				alert('本题最多选择'+numlimit+'项答案');
				return false;
			}
			//勾选
			if($(this).find('input:eq(0)').attr('type')=='radio'){
				$(this).parent().find('label').css('background-color','#fff');
			}
			$(this).find('input:eq(0)').attr('checked','checked');//勾选
			$(this).css('background-color','#d5eaff');
		}else{
			//取消
			$(this).find('input:eq(0)').removeAttr('checked','checked');//勾选
			$(this).css('background-color','#fff');
		}
		//如果是触发结束题则不出新的题
		if($(this).parent().find('.flag_over').val()==1){
			return false;
		}
		//移除后面答题内容
		var index=$('.question_list').index($(this).parent().parent());
		$('.question_list:gt('+index+')').remove();
		
		var questionid=$(this).parent().prev().find('input[name^=questionid]').val();
		var optionlist=$(this).parent().find('input:checked');//var optionid=$(this).find('input').val();
		var selectqeid='';
		var selectqeidarr=new Array();
		//找符合前置条件的问题
		var i=0;
		$('.qecon li').each(function(){
			var qecon_prevqe_id=$(this).find('.qecon_prevqe_id').val();
			var qecon_prevop_id=$(this).find('.qecon_prevop_id').val();
			var qecon_qe_id=$(this).find('.qecon_qe_id').val();
			optionlist.each(function(){
				if(qecon_prevqe_id==questionid && qecon_prevop_id==$(this).val()){
					selectqeidarr[i]=qecon_qe_id;
					i++;
				}
			});
		});
		var ind=Math.floor(Math.random()*selectqeidarr.length);
		selectqeid=selectqeidarr[ind]?selectqeidarr[ind]:'';
		//如果没有符合前置条件的问题则随机下一轮,按概率出
		if(selectqeid==''){
			var step=$('.ansqe').length;
			var qeli=$('#qepath .step').eq(step-1).find('li');//某个路径的li
			var maxnum=0;
			qeli.each(function(){
					maxnum+=$(this).find('.probability').val()*1;
			});
			var tnum=Math.floor(Math.random()*maxnum+1);
			qeli.each(function(){
				var probability=$(this).find('.probability').val()*1;
				if(tnum<=probability){
					selectqeid=$(this).find('.qeid').val();
					return false;
				}else{
					maxnum-=probability;
					tnum=Math.floor(Math.random()*maxnum+1);
				}
			});
		}
		if(selectqeid!=''){
			var leng=$('.question_list').length;
			var selectqe=$('li#qestion_id'+selectqeid).length>0?$('li#qestion_id'+selectqeid):$('li#questall_id'+selectqeid).eq(0);//先通过前置条件找,如果没有则在所有路径问题中找到问题
			var qetitle=selectqe.find('.qetitle').val();
			var qetype=selectqe.find('.qetype').val();
			var aslimit=selectqe.find('.aslimit').val();//答题限制
			var flag_over=selectqe.find('.flag_over').val();//1触发结束,2无
			var qefile=(selectqe.find('.qefile').val()!='')?'<br><img src="'+selectqe.find('.qefile').val()+'">':'';
			
			var str='<div class="wj_m question_list">'+
			    	'<p>Q'+(leng+1)+'. '+qetitle+qefile+
					'<input type="hidden" name="questionid'+leng+'" value="'+selectqeid+'"  />'+
				'</p> <div class="wj_mm ansqe">'+
			    '<input class="qetype" type="hidden" value="'+qetype+'" /><input class="aslimit" type="hidden" value="'+aslimit+'" /><input class="flag_over" type="hidden" value="'+flag_over+'" />';
		    selectqe.find('.opid').each(function(i){
		    	var opid=$(this).val();
		    	var opcontent=selectqe.find('.opcontent').eq(i).val();
		    	str+='<label>';
		    	if(qetype == 1){
		    		str+='<input type="radio" name="check'+leng+'" value="'+opid+'">';
		    	}else if(qetype == 2){
		    		str+='<input type="checkbox" name="check'+leng+'[]" value="'+opid+'">';
		    	}else if(qetype == 3){
		    		str+='<input type="radio" name="check'+leng+'" value="'+opid+'">';
		    	}else if(qetype == 4){
		    		str+='<input type="hidden" name="check'+leng+'" value="'+opid+'">';
		    	}
		    	opcontent=opcontent.replace(/@text/g,'<br><input type="text" class="anstext" value="" style="font-size:16px;width:80%;height:30px;" /><br>')
		    	str+=opcontent+'<input type="hidden" name="anscontent'+opid+'" value="" /></label>';
		    });
			 str+='</div></div>';
			 $(this).parent().parent().after(str);//新加题目
			 if(flag_over==1){
				 $('#quesnum').val($('.question_list').length);
				 $('#submit').val('答题结束并提交');
			 }else{
				 $('#submit').val('中止答题并提交');
			 }
		}else{
			$('#quesnum').val($('.question_list').length);
			$('#submit').val('答题结束并提交');
		}
		return false;
	});
	
});
<file_sep>/App/Controller/ResultAnalysis_bak_20150316.php
<?php
FLEA::loadFile ('App/Service/pdf/tfpdf.php');
FLEA::loadFile ( "Service/PHPExcel/IOFactory.php" );
class Controller_ResultAnalysis extends FLEA_Controller_Action {
	/**
	 *
	 * Enter description here ...
	 * @var Class_Common
	 */
	var $_common;
	var $_admin;
	var $_adminid;
	var $_questionnaire;
	var $_question;
	var $_option;
	var $_answer;
	var $_answer_detail;

	function __construct() {
		$this->_common = get_singleton ( "Class_Common" );

		$this->_admin = get_singleton ( "Model_Admin" );
		$this->_questionnaire = get_singleton ( "Model_Questionnaire" );
		$this->_question = get_singleton ( "Model_Question" );
		$this->_option = get_singleton ( "Model_Option" );
		$this->_answer = get_singleton ( "Model_Answer" );
		$this->_answer_detail = get_singleton ( "Model_AnswerDetail" );
		$this->_adminid = isset ( $_SESSION ['loginuserid'] ) ? $_SESSION ['loginuserid'] : "";
		if(empty($_SESSION ['loginuserid'])){
			$url=url("Default","Login");
			redirect($url);
		}
	}

	
	//分析统计图
	function actionAnalysis(){
		$qnnaid = isset ( $_GET ['qnnaid'] ) ?$this->_common->filter($_GET ['qnnaid'])  : '';
		if(empty($qnnaid)){
			$url=url('Questionnaire','Index');
			redirect($url);
			return;
		}
		$questionnaire=$this->_questionnaire->findByField('id',$qnnaid);
		$question=$this->_question->findAll(array('questionnaire_id'=>$qnnaid),'num asc,id desc');
		foreach ($question as $k=>$q){
			$options=$this->_option->findAll(array('question_id'=>$q['id']));
			foreach ($options as $opk=>$op){
				$options[$opk]['count']=$this->_answer_detail->findCount(array('questionnaire_id'=>$qnnaid,'question_id'=>$q['id'],'option_id'=>$op['id']));
			}
			$question[$k]['option']=$options;
		}
		$questionnaire['anscount']=$this->_answer->findCount(array('questionnaire_id'=>$qnnaid));
		$this->_common->show ( array ('main' => 'analysis/analysis.tpl','questionnaire'=>$questionnaire,'question'=>$question) );
		
	}
	
	//答题列表
	function actionList() {
		$qnnaid=isset ( $_GET ['qnnaid'] ) ? $this->_common->filter($_GET ['qnnaid']) : '';
		if(empty($qnnaid)){
			$url=url('Questionnaire','Index');
			redirect($url);
			return;
		}
		$pageparm = array ('qnnaid'=>$qnnaid);//9删除
		$page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1;
		$page_size = 20;
		$title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : '';

		$conditions=array('questionnaire_id'=>$qnnaid);
		if(!empty($title)){
			$conditions[]="title like '%$title%'";
			$pageparm['title']=$title;
		}

		$total=$this->_answer->findCount($conditions);

		$pages = & get_singleton ( "Service_Page" );
		$pages->_page_no = $page_no;
		$pages->_page_num = $page_size;
		$pages->_total = $total;
		$pages->_url = url ( "ResultAnalysis", "List");
		$pages->_parm = $pageparm;
		$page = $pages->page ();
		$start = ($page_no - 1) * $page_size;

		$list=$this->_answer->findAll($conditions,"id desc limit $start,$page_size");
		$questionnaire=$this->_questionnaire->findByField('id',$qnnaid);
		$this->_common->show ( array ('main' => 'analysis/answer_list.tpl','list'=>$list,'page'=>$page,'pageparm'=>$pageparm,'questionnaire'=>$questionnaire) );
	}
	
	function actionDelAnswer(){
		$id=isset ( $_GET ['id'] ) ? $this->_common->filter($_GET ['id']) : '';
		if(empty($id)){
			$url=url('Questionnaire','Index');
			redirect($url);
			return;
		}
		$this->_answer->removeByConditions(array('id'=>$id));
		$this->_answer_detail->removeByConditions(array('answer_id'=>$id));
		redirect($_SERVER['HTTP_REFERER']);
	}
	
	//pdf打印
	function actionQuestionarePdf(){
		$config = FLEA::getAppInf ( 'dbDSN' );
		$prefix = $config ['prefix'];
		$qnnaid = isset ( $_GET ['qnnaid'] ) ?$this->_common->filter($_GET ['qnnaid'])  : '';
		$questionnaire=$this->_questionnaire->findByField('id',$qnnaid);
		$question=$this->_question->findAll(array('questionnaire_id'=>$qnnaid),'num asc,id asc');
		//查看答卷详情
		$conditions=array('questionnaire_id'=>$qnnaid);
		$answerlist=$this->_answer->findAll($conditions,"id desc");
		if(!is_array($answerlist)||count($answerlist)<=0){
			echo '暂无答题数据';
			return false;
		}
		
		$pdf = new tFPDF ();
		$pdf->isfooter = false;
		$pdf->bMargin = 0;
		$pdf->AutoPageBreak = false;
		$pdf->AddFont ( 'MicrosoftYaHei', '', 'msyh.ttf', true );
		$pdf->Open ();
		foreach ($answerlist as $k=>$v){
			$pdf->AddPage ();
			$pdf->SetTextColor ( 0, 0, 0 );
			$x=$y=0;
			$y += 10;
			$pdf->SetXY ( $x, $y );
			$pdf->SetFont ( 'MicrosoftYaHei', '', 12 );
			$pdf->SetFontSize(15);
			$sw=$pdf->GetStringWidth($questionnaire['title']);
			$pdf->MultiCell(210, 8, $questionnaire['title'],0,'C');
			//$pdf->Cell ( 210,12, $questionnaire['title'], 0, 0, 'C', 0);
			$y += (ceil($sw/210))*8+5;
			$pdf->SetXY ( $x, $y );
			$pdf->SetFontSize(10);
			$pdf->Cell ( 210,12, '答题序号：'.$v['num'].'	用 户 IP：'.$v['ip'].'	答题时长：'.$v['pass_time'].'	答题时间：'.$v['created'], 0, 0, 'C', 0);
			$y += 12;
			$pdf->SetXY ( $x+5, $y );
			$pdf->SetFillColor(60,156,207);
			$pdf->Cell ( 200,0.5, '', 0, 0, 'C', 1);//蓝线
			foreach ($question as $qk=>$q){
				//查下问题答案详情
				$sql="select op.content,ad.answer_content from ".$prefix."answer_detail ad
					left join ".$prefix."option op on op.id=ad.option_id
					where ad.question_id=".$q['id']." and ad.answer_id=".$v['id'];
				$o=$this->_answer_detail->findBySql($sql);
				$content=array();
				$answer=array();
				foreach ($o as $oo){
					$content[]=$oo['content'];
					$answer[]=$oo['answer_content'];
				}
				$content=implode(',', $content);
				$answer=implode(',', $answer);
				$answer_content='';
				if($q['type']=='1'||$q['type']=='2'){
					$answer_content=$content;
				}else{
					$content=explode("@text", $content);
					$answer=explode(",", $answer);
					foreach ($content as $ck=>$c){
						$answer_content.=$c.$answer[$ck];
					}
				}

				$y+=5;
				$pdf->SetXY($x+5,$y);
				$pdf->Cell(8,10,'Q'.($qk+1).'.', 0, 0, 'L', 0);
				$pdf->SetX($x+12);
				$pdf->MultiCell(192, 10, $q['title']);
				$sw=$pdf->GetStringWidth($q['title']);
				
				$y+=ceil($sw/192)>0?ceil($sw/192)*10:10;
				$pdf->SetX($x+5,$y);
				$pdf->Cell(10,10,'回答:', 0, 0, 'L', 0);
				$pdf->SetX($x+15);
				$pdf->MultiCell(190, 10, $answer_content);
				$sw=$pdf->GetStringWidth($answer_content);
				$y+=ceil($sw/190)>0?ceil($sw/190)*10:10;
			}
			$pdf->SetXY ( $x+5, 260 );
			$pdf->Cell ( 200,0.5, '', 0, 0, 'C', 1);
			$pdf->SetXY ( $x+10, 260 );
			$pdf->Cell ( 210,12, '关注"Planbook"微信账号,了解更多内容', 0, 0, 'L', 0);
			$path = "resource/images/planbook.jpg";
			$pdf->Image ( $path, 160, 262, 30, 30 );
		}
			
		$pdf->Output ();
	}
	
	//导出Excel
	function actionQuestionareExc(){
		$config = FLEA::getAppInf ( 'dbDSN' );
		$prefix = $config ['prefix'];
		$qnnaid = isset ( $_GET ['qnnaid'] ) ?$this->_common->filter($_GET ['qnnaid'])  : '';
		$questionnaire=$this->_questionnaire->findByField('id',$qnnaid);
		$question=$this->_question->findAll(array('questionnaire_id'=>$qnnaid),'num asc,id asc');
		$conditions=array('questionnaire_id'=>$qnnaid);
		$answerlist=$this->_answer->findAll($conditions,"id desc ");
		
		// 设置基本属性
		$objPHPExcel = new PHPExcel();
		// 创建多个工作薄
		$sheet1 = $objPHPExcel->createSheet();
		// 设置第一个工作簿为活动工作簿
		$objPHPExcel->setActiveSheetIndex(0);
		// 设置活动工作簿名称
		$objPHPExcel->getActiveSheet()->setTitle('统计数据');
		// 设置默认字体和大小
		$objPHPExcel->getDefaultStyle()->getFont()->setName('宋体');
		$objPHPExcel->getDefaultStyle()->getFont()->setSize(10);
		// 给特定单元格中写入内容
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0,1, '答题序号');
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1,1, '答题时间');
		$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2,1, '答题时长');
		$i=3;
		foreach ($question as $q){
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($i,1, $q['title']);
			++$i;
		}
		$r=2;
		foreach ($answerlist as $v){
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0,$r, $v['num']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1,$r, $v['created']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2,$r, $v['pass_time']);
			$i=3;
			foreach ($question as $q){
				//查找答题选项
				$sql="select op.content,ad.answer_content from ".$prefix."answer_detail ad
						left join ".$prefix."option op on op.id=ad.option_id
						where ad.question_id=".$q['id']." and ad.answer_id=".$v['id'];
				$o=$this->_answer_detail->findBySql($sql);
				$contentstr=array();
				$answerstr=array();
				foreach ($o as $oo){
					$contentstr[]=$oo['content'];
					$answerstr[]=$oo['answer_content'];
				}
				$contentstr=implode(',', $contentstr);
				$answerstr=implode(',', $answerstr);
				$answer_content='';
				if($q['type']=='1'||$q['type']=='2'){
					$answer_content=$contentstr;
				}else{
					$contentstr=explode("@text", $contentstr);
					$answerstr=explode(",", $answerstr);
					foreach ($contentstr as $ck=>$c){
						$answer_content.=$c.@$answerstr[$ck];
					}
				}
				//用户答案
				$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($i,$r, $answer_content);
				++$i;
			}
			++$r;
		}
		$FileName = '答题统计表'.date('YmdHis').".xls"; // 输出EXCEL文件名
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
		header("Content-Type:application/force-download");
		header("Content-Type: application/vnd.ms-excel;");
		header("Content-Type:application/octet-stream");
		header("Content-Type:application/download");
 		header("Content-Disposition:attachment;filename=".$FileName);
		header("Content-Transfer-Encoding:binary");
		$objWriter->save("php://output"); 
		
	}
	
}


<file_sep>/App/Controller/Answer.php
<?php
class Controller_Answer extends FLEA_Controller_Action {
	/**
	 *
	 * Enter description here ...
	 * @var Class_Common
	 */
	var $_common;
	var $_admin;
	var $_adminid;
	var $_questionnaire;
	var $_question;
	var $_option;
	var $_answer;
	var $_answer_detail;
	var $_abstract;

	function __construct() {
		$this->_common = get_singleton ( "Class_Common" );

		$this->_admin = get_singleton ( "Model_Admin" );
		$this->_questionnaire = get_singleton ( "Model_Questionnaire" );
		$this->_question = get_singleton ( "Model_Question" );
		$this->_option = get_singleton ( "Model_Option" );
		$this->_answer = get_singleton ( "Model_Answer" );
		$this->_answer_detail = get_singleton ( "Model_AnswerDetail" );
		$this->_abstract = get_singleton ( "Model_Abstract" );
	}

	//短链接跳转
	function actionQrcode() {
		$short = isset ( $_GET ['short'] ) ? $this->_common->filter($_GET ['short']) : '';
		$questionnaire=$this->_questionnaire->find(array('short'=>$short),'id desc');
		if(@$questionnaire['status']=='1'){
			$url=url('Answer','Index',array('qid'=>$questionnaire['id']));
			redirect($url);
			return ;
		}
		if($questionnaire['status']=='0'){
			echo '<h1>调查问卷还没发布</h1>';
		}elseif($questionnaire['status']=='2'){
			echo '<h1>调查问卷已经结束</h1>';
		}else{
			echo '<h1>找不到相关问卷,请联系管理员</h1>';
		}
		
	}
	
	//回答问卷
	function actionIndex(){
		$qid = isset ( $_GET ['qid'] ) ? $this->_common->filter($_GET ['qid']) : '';
		$questionnaire=$this->_questionnaire->findByField('id',$qid);
		$abstract=$this->_abstract->findAll(array('questionnaire_id'=>$qid),'id asc');
		$question=$this->_question->findAll(array('questionnaire_id'=>$qid),'num,id asc');
		foreach ($question as $k=>$q){
			$question[$k]['option']=$this->_option->findAll(array('question_id'=>$q['id']),'id asc');
		}
		$signinfo=$this->_admin->findByField('adm_name','admin');
		$this->_common->display('qa/qa.tpl',array ('questionnaire'=>$questionnaire,'question'=>$question,'abstract'=>$abstract,'signinfo'=>$signinfo) );
	}
	
	//提交问卷
	function actionSubmit(){
		$data = $this->_common->filter($_POST);
		$act = isset ( $data ['act'] ) ? $data ['act'] : '';
		$qnnaid = isset ( $data ['questionnaire_unit'] ) ? $data ['questionnaire_unit'] : '';
		if($act=='submit'&&!empty($qnnaid)){
			$questionnaire=$this->_questionnaire->findByField('id',$qnnaid);
			if($questionnaire['status']=='0'){
				$ref=$_SERVER['HTTP_REFERER'];
				echo '<h1>调查问卷还没发布,您不能答题<br><a href="'.$ref.'" >返回</a><';
				return ;
			}
			if($questionnaire['status']=='2'){
				$ref=$_SERVER['HTTP_REFERER'];
				echo '<h1>调查问卷已结束,您不能答题<br><a href="'.$ref.'" >返回</a>';
				return ;
			}
			$passtime='';
			$time=$data['time'];
			//$d = intval($time/86400);
			$h = round(($time%86400)/3600);
			$m = round(($time%3600)/60);
			$s = round(($time%60));
			$passtime.=$h>0?$h.'时':'';
			$passtime.=$m>0?$m.'分':'';
			$passtime.=$s.'秒';
			//回答信息
			$answer=array('questionnaire_id'=>$qnnaid,'pass_time'=>$passtime,'num'=>$this->_answer->getMaxNumGoupByQid($qnnaid),'ip'=>$_SERVER['REMOTE_ADDR']);
			$ansid=$this->_answer->create($answer);
			$quesnum=$this->_question->findCount(array('questionnaire_id'=>$qnnaid));
			for($i=0;$i<$quesnum;$i++){
				$asoption=$data['check'.$i];
				if(is_array($asoption)){
					foreach ($asoption as $aopt){
						$asdetial=array('answer_id'=>$ansid,'questionnaire_id'=>$qnnaid,'question_id'=>$data['questionid'.$i],'option_id'=>$aopt,'answer_content'=>$data['anscontent'.$aopt]);
						$this->_answer_detail->create($asdetial);
					}
				}else{
					$asdetial=array('answer_id'=>$ansid,'questionnaire_id'=>$qnnaid,'question_id'=>$data['questionid'.$i],'option_id'=>$asoption,'answer_content'=>$data['anscontent'.$asoption]);
					$this->_answer_detail->create($asdetial);
				}
			}
			$url=url('Answer','Complete');
			redirect($url);
		}
	}
	
	//完成问卷
	function actionComplete(){
		$signinfo=$this->_admin->findByField('adm_name','admin');
		$this->_common->display('qa/complete.tpl',array('msg'=>'感谢您的提交!','signinfo'=>$signinfo));
	}
	
	function actionPreview(){
		$config = FLEA::getAppInf ( 'dbDSN' );
		$prefix = $config ['prefix'];
		$qid = isset ( $_GET ['qid'] ) ? $this->_common->filter($_GET['qid']) : '';
		$answer=$this->_answer->findByField('id',$qid);
		if(empty($answer['id'])){
			echo '答题内容不存在,可能已被删除';
			return;
		}
		$questionnaire=$this->_questionnaire->findByField('id',$answer['questionnaire_id']);
		$abstract=$this->_abstract->findAll(array('questionnaire_id'=>$qid));
		$question=$this->_question->findAll(array('questionnaire_id'=>$answer['questionnaire_id']),'num asc,id desc');
		foreach ($question as $k=>$q){
			//查找答题选项
			$sql="select op.content,ad.answer_content from ".$prefix."answer_detail ad 
					left join ".$prefix."option op on op.id=ad.option_id 
					where ad.question_id=".$q['id']." and ad.answer_id=".$qid;
			$o=$this->_answer_detail->findBySql($sql);
			$contentstr=array();
			$answerstr=array();
			foreach ($o as $oo){
				$contentstr[]=$oo['content'];
				$answerstr[]=$oo['answer_content'];
			}
			$contentstr=implode(',', $contentstr);
			$answerstr=implode(',', $answerstr);
			$answer_content='';
			if($q['type']=='1'||$q['type']=='2'){
				$answer_content=$contentstr;
			}else{
				$contentstr=explode("@text", $contentstr);
				$answerstr=explode(",", $answerstr);
				foreach ($contentstr as $ck=>$c){
					$answer_content.=$c.$answerstr[$ck];
				}
			}
			$question[$k]['answer']=$answer_content;
		}

		$this->_common->display('qa/preview.tpl',array('answer'=>$answer,'questionnaire'=>$questionnaire,'question'=>$question,'abstract'=>$abstract));
	}
	
	function actionAnalysis(){
		$config = FLEA::getAppInf ( 'dbDSN' );
		$prefix = $config ['prefix'];
		$qnnaid = isset ( $_GET ['qnnaid'] ) ?$this->_common->filter($_GET ['qnnaid'])  : '';
		$questionnaire=$this->_questionnaire->findByField('id',$qnnaid);
		$question=$this->_question->findAll(array('questionnaire_id'=>$qnnaid),'num asc,id asc');
		foreach ($question as $k=>$q){
			$options=$this->_option->findAll(array('question_id'=>$q['id']));
			foreach ($options as $opk=>$op){
				$options[$opk]['count']=$this->_answer_detail->findCount(array('questionnaire_id'=>$qnnaid,'question_id'=>$q['id'],'option_id'=>$op['id']));
			}
			$question[$k]['option']=$options;
		}
		$questionnaire['anscount']=$this->_answer->findCount(array('questionnaire_id'=>$qnnaid));
		
		//查看答卷详情
		$pageparm = array ('qnnaid'=>$qnnaid);//9删除
		$page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1;
		$page_size = 50;
		$title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : '';
		
		$conditions=array('questionnaire_id'=>$qnnaid);
		if(!empty($title)){
			$conditions[]="title like '%$title%'";
			$pageparm['title']=$title;
		}
		
		$total=$this->_answer->findCount($conditions);
		
		$pages = & get_singleton ( "Service_Page" );
		$pages->_page_no = $page_no;
		$pages->_page_num = $page_size;
		$pages->_total = $total;
		$pages->_url = url ( "Answer", "Analysis");
		$pages->_parm = $pageparm;
		$page = $pages->analysisPage ();
		$start = ($page_no - 1) * $page_size;
		
		$answerlist=$this->_answer->findAll($conditions,"id desc limit $start,$page_size");
		
		foreach ($answerlist as $k=>$v){
			$anses=array();
			foreach ($question as $qk=>$q){
				$sql="select op.content,ad.answer_content from ".$prefix."answer_detail ad 
					left join ".$prefix."option op on op.id=ad.option_id 
					where ad.question_id=".$q['id']." and ad.answer_id=".$v['id'];
				$o=$this->_answer_detail->findBySql($sql);
				$content=array();
				$answer=array();
				foreach ($o as $oo){
					$content[]=$oo['content'];
					$answer[]=$oo['answer_content'];
				}
				$content=implode(',', $content);
				$answer=implode(',', $answer);
				$answer_content='';
				if($q['type']=='1'||$q['type']=='2'){
					$answer_content=$content;
				}else{
					$content=explode("@text", $content);
					$answer=explode(",", $answer);
					foreach ($content as $ck=>$c){
						$c.=@$answer[$ck];
						$answer_content.=$c;
					}
				}
				$anses[]=array('content'=>$answer_content,'qetype'=>$q['type']);
			}
			$answerlist[$k]['answer']=$anses;
			
		}
		
		$this->_common->display('qa/analysis.tpl', array ('questionnaire'=>$questionnaire,'question'=>$question,'answerlist'=>$answerlist,'page'=>$page,'pageparm'=>$pageparm) );
	}
	
}



<file_sep>/App/Controller/Qe.php
<?php
class Controller_Qe extends FLEA_Controller_Action {
	/**
	 *
	 * Enter description here ...
	 * @var Class_Common
	 */
	var $_common;
	var $_admin;
	var $_adminid;
	var $_qs;
	var $_qe;
	var $_op;
	var $_group;
	var $_category;

	function __construct() {
		$this->_common = get_singleton ( "Class_Common" );

		$this->_admin = get_singleton ( "Model_Admin" );
		$this->_group = get_singleton ( "Model_Group" );
		$this->_category = get_singleton ( "Model_Category" );
		$this->_qs = get_singleton ( "Model_Qs" );
		$this->_qe = get_singleton ( "Model_Qe" );
		$this->_op = get_singleton ( "Model_Op" );
		$this->_adminid = isset ( $_SESSION ['loginuserid'] ) ? $_SESSION ['loginuserid'] : "";
		if(empty($_SESSION ['loginuserid'])){
			$url=url("Default","Login");
			redirect($url);
		}
	}

//题库分组
	function actionGroup(){
		$act=isset($_POST['act'])?$this->_common->filter($_POST['act']):'';
		$msg='';
		if(!empty($act)){
			$ids=$_POST['ids'];
			$name=$_POST['name'];
			foreach ($name as $k=>$n){
				if(!empty($n)){
					if(!empty($ids[$k])){
						$g=array('id'=>$ids[$k],'name'=>$n);
						$this->_group->update($g);
					}else{
						$g=array('name'=>$n);
						$this->_group->create($g);
					}
				}
			}
			$msg='分组更新成功';
		}
		$groups=$this->_group->findAll();
		$this->_common->show ( array ('main' => 'qe/group.tpl','groups'=>$groups,'msg'=>$msg) );
	}
	
	//删除分组
	function actionDelGroup(){
		$id=$this->_common->filter($_GET['id']);
		$count=$this->_qe->findCount(array('group_id'=>$id));
		if($count>0){
			echo '<script>alert("此分组中有题库,不可删除");window.location="'.$_SERVER['HTTP_REFERER'].'"</script>';
		}else{
			$this->_group->removeByPkv($id);
			redirect($_SERVER['HTTP_REFERER']);
		}
	}
	
	//题库分类
	function actionCategory(){
		$act=isset($_POST['act'])?$this->_common->filter($_POST['act']):'';
		$msg='';
		if(!empty($act)){
			$ids=$_POST['ids'];
			$name=$_POST['name'];
			foreach ($name as $k=>$n){
				if(!empty($n)){
					if(!empty($ids[$k])){
						$g=array('id'=>$ids[$k],'name'=>$n);
						$this->_category->update($g);
					}else{
						$g=array('name'=>$n);
						$this->_category->create($g);
					}
				}
			}
			$msg='分类更新成功';
		}
		$category=$this->_category->findAll();
		$this->_common->show ( array ('main' => 'qe/category.tpl','category'=>$category,'msg'=>$msg) );
	}
	
	//删除分类
	function actionDelCategory(){
		$id=$this->_common->filter($_GET['id']);
		$count=$this->_qe->findCount(array('category_id'=>$id));
		if($count>0){
			echo '<script>alert("此类型中有题库,不可删除");window.location="'.$_SERVER['HTTP_REFERER'].'"</script>';
		}else{
			$this->_category->removeByPkv($id);
			redirect($_SERVER['HTTP_REFERER']);
		}
	}
	
	//题库新增
	function actionQeAdd(){
		$act=isset ( $_POST ['act'] ) ? $_POST ['act'] : '';
		if($act=='add'){
			//创建题库
			$qe=$this->_common->filter($_POST['qe']);
			//判断类型为空
			if(empty($qe['category_id'])){unset($qe['category_id']);}
			$Upload= & get_singleton ( "Service_UpLoad" );
			$folder="resource/upload/qeimg/";
			if (! file_exists ( $folder )) {
				mkdir ( $folder, 0777 );
			}
			$Upload->setDir($folder.date("Ymd")."/");
			$img=$Upload->upload('file');
			if($img['status']==1){
				$file_path=$img['file_path'];
				$qe['file']=$file_path;
			}
			$qe_id=$this->_qe->create($qe);
			//创建答题选项
			$i=$qe['type'];
			if(isset($_POST['op'.$i])){
				$op=$this->_common->filter($_POST['op'.$i]);
				foreach($op['content'] as $c){
					//创建选项
					if(!empty($c)){
						$option=array('content'=>$c,'qe_id'=>$qe_id);
						$this->_op->create($option);
					}
				}
			}
			$url=url('Qe','QeList');
			redirect($url);
		}
		$group=$this->_group->findAll(array(),"id");
		$category=$this->_category->findAll(array(),"id");
		$this->_common->show ( array ('main' => 'qe/qeadd.tpl','category'=>$category,'group'=>$group) );
	}
	
	//题库编辑
	function actionQeEdit(){
		$act=isset ( $_POST ['act'] ) ? $_POST ['act'] : '';
		$id=isset ( $_GET ['qeid'] ) ? $this->_common->filter($_GET ['qeid']) : '';
		$msg='';
		if($act=='edit'){
			//创建题库
			$qe=$this->_common->filter($_POST['qe']);
			//判断类型为空
			if(empty($qe['category_id'])){unset($qe['category_id']);}
			$qe_id=$qe['id'];
			$Upload= & get_singleton ( "Service_UpLoad" );
			$folder="resource/upload/qeimg/";
			if (! file_exists ( $folder )) {
				mkdir ( $folder, 0777 );
			}
			$Upload->setDir($folder.date("Ymd")."/");
			$img=$Upload->upload('file');
			if($img['status']==1){
				$file_path=$img['file_path'];
				$qe['file']=$file_path;
			}
			$this->_qe->update($qe);
			//创建答题选项
			$i=$qe['type'];
			if(isset($_POST['op'.$i])){
				$this->_op->removeByConditions(array('qe_id'=>$qe_id));
				$op=$this->_common->filter($_POST['op'.$i]);
				foreach($op['content'] as $c){
					//创建选项
					if(!empty($c)){
						$option=array('content'=>$c,'qe_id'=>$qe_id);
						$this->_op->create($option);
					}
				}
			}
			$msg='修改成功!';
		}
		$qe=$this->_qe->findByField('id',$id);
		$ops=$this->_op->findAll(array('qe_id'=>$id),"id asc");
		$group=$this->_group->findAll(array(),"id asc");
		$category=$this->_category->findAll(array(),"id");
		$this->_common->show ( array ('main' => 'qe/qeedit.tpl','category'=>$category,'group'=>$group,'qe'=>$qe,'ops'=>$ops,'msg'=>$msg) );
	}
	
	//题库列表
	function actionQeList(){
		$config = FLEA::getAppInf ( 'dbDSN' );
		$prefix = $config ['prefix'];
		$keyword = isset ( $_GET ['keyword'] ) ? $this->_common->filter($_GET ['keyword']) : '';
		$group_id = isset ( $_GET ['group'] ) ? $this->_common->filter($_GET ['group']) : '';
		$category_id = isset ( $_GET ['category'] ) ? $this->_common->filter($_GET ['category']) : '';
		$conditions='';
		$pageparm=array();
		if(!empty($keyword)){
			$conditions=" and title like '%".addslashes($keyword)."%'";
			$pageparm['keyword']=$keyword;
		}
		if(!empty($group_id)){
			$conditions.=" and group_id =".addslashes($group_id);
			$pageparm['group']=$group_id;
		}
		if(!empty($category_id)){
			$conditions.=" and category_id =".addslashes($category_id);
			$pageparm['category']=$category_id;
		}
		$sql="select qe.*,gp.name group_name from ".$prefix."qe qe left join ".$prefix."group gp on qe.group_id=gp.id where 1=1 ";
		$sql.=$conditions;
		$total=$this->_qe->findBySql("select count(*) as num from ($sql) s ");
		$total=$total[0]['num'];
		$page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1;
		$page_size = 20;
		$pages = & get_singleton ( "Service_Page" );
		$pages->_page_no = $page_no;
		$pages->_page_num = $page_size;
		$pages->_total = $total;
		$pages->_url = url ( "Qe", "QeList");
		$pages->_parm = $pageparm;
		$page = $pages->page ();
		$start = ($page_no - 1) * $page_size;

		
		$list=$this->_qe->findBySql($sql." order by qe.id desc limit $start,$page_size");
		foreach ($list as $k=>$v){
			$ops=$this->_op->findAll(array('qe_id'=>$v['id']),'id asc');
			$list[$k]['ops']=$ops;
		}
		$group=$this->_group->findAll(array(),"id");
		$category=$this->_category->findAll(array(),"id");
		$this->_common->show ( array ('main' => 'qe/qelist.tpl','list'=>$list,'pageparm'=>$pageparm,'group'=>$group,'category'=>$category,'page'=>$page) );
	}
	
	//题库附件
	function actionQeFile(){
		$config = FLEA::getAppInf ( 'dbDSN' );
		$prefix = $config ['prefix'];
		$keyword = isset ( $_GET ['keyword'] ) ? $this->_common->filter($_GET ['keyword']) : '';
		$conditions='';
		if(!empty($keyword)){
			$conditions="and title like '%".addslashes($keyword)."%'";
			$pageparm['keyword']=$keyword;
		}
		$sql="select qe.*,gp.name group_name from ".$prefix."qe qe left join ".$prefix."group gp on qe.group_id=gp.id where qe.file is not null and qe.file<>'' ";
		$sql.=$conditions;
		$total=$this->_qe->findBySql("select count(*) as num from ($sql) s ");
		$total=$total[0]['num'];
		$page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1;
		$page_size = 20;
		$pages = & get_singleton ( "Service_Page" );
		$pages->_page_no = $page_no;
		$pages->_page_num = $page_size;
		$pages->_total = $total;
		$pages->_url = url ( "Qe", "QeList");
		$pages->_parm = $pageparm;
		$page = $pages->page ();
		$start = ($page_no - 1) * $page_size;
		
		$list=$this->_qe->findBySql($sql."order by qe.id desc limit $start,$page_size");
		foreach ($list as $k=>$v){
			$ops=$this->_op->findAll(array('qe_id'=>$v['id']),'id asc');
			$list[$k]['ops']=$ops;
			$total=$this->_qe->findBySql("select count(a.id) as num from ".$prefix."qs_answer a left join ".$prefix."qs qs on a.qs_id=qs.id left join ".$prefix."qepath path on path.qs_id=qs.id where path.qe_id=".$v['id']);
			$total=@$total[0]['num']*1;
			$list[$k]['rate']=round($v['times']/$total*100,2);
		}
		$this->_common->show ( array ('main' => 'qe/qefiles.tpl','list'=>$list,'pageparm'=>$pageparm,'page'=>$page) );
	}
	
	
	//删除题库
	function actionQeDel(){
		$id=$this->_common->filter($_GET['id']);
		$this->_op->removeByConditions(array('qe_id'=>$id));
		$this->_qe->removeByPkv($id);
		redirect($_SERVER['HTTP_REFERER']);
	}
	
	//删除题库附件
	function actionQeDelFile(){
		$id=$this->_common->filter($_GET['qeid']);
		$qe=$this->_qe->findByField('id',$id);
		if(!empty($qe['file'])){
			unlink($qe['file']);
		}
		$qe['file']='';
		$this->_qe->update($qe);
		redirect($_SERVER['HTTP_REFERER']);
	}
	
	
}
<file_sep>/App/Controller/Qs.php
<?php
require_once SERVERROOT. DS . 'App' . DS . 'Class' .DS.'phpqrcode.php';
require_once SERVERROOT. DS . 'weixin' . DS . 'wechat.php';
class Controller_Qs extends FLEA_Controller_Action {
	/**
	 *
	 * Enter description here ...
	 * @var Class_Common
	 */
	var $_common;
	var $_admin;
	var $_adminid;
	var $_qs;
	var $_qe;
	var $_op;
	var $_qs_answer;
	var $_qs_abstract;
	var $_group;
	var $_category;
	var $_qepath;
	var $_qecon;

	function __construct() {
		$this->_common = get_singleton ( "Class_Common" );

		$this->_admin = get_singleton ( "Model_Admin" );
		$this->_group = get_singleton ( "Model_Group" );
		$this->_category = get_singleton ( "Model_Category" );
		$this->_qs = get_singleton ( "Model_Qs" );
		$this->_qe = get_singleton ( "Model_Qe" );
		$this->_op = get_singleton ( "Model_Op" );
		$this->_qs_answer = get_singleton ( "Model_QsAnswer" );
		$this->_qs_abstract = get_singleton ( "Model_QsAbstract" );
		$this->_qepath=get_singleton ( "Model_QePath" );
		$this->_qecon=get_singleton ( "Model_QeCon" );
		$this->_adminid = isset ( $_SESSION ['loginuserid'] ) ? $_SESSION ['loginuserid'] : "";
		if(empty($_SESSION ['loginuserid'])){
			$url=url("Default","Login");
			redirect($url);
		}
	}
	
	
	//问卷添加
	function actionAdd(){
		$act=isset ( $_POST ['act'] ) ? $_POST ['act'] : '';
		if($act=='add'){
			//问卷设置
			$data=$this->_common->filter($_POST['data']);
			$data['over_num']=intval($data['over_num']);
			if(empty($data['over_num'])){
				unset($data['over_num']);
			}
			if(empty($data['over_date'])){
				unset($data['over_date']);
			}
			
			//短连接及二维码
			$shoturl=url('As','Index',array('time'=>time()));
			$shoturl=$this->_common->shortUrl($shoturl);
			$data['short']=$shoturl;
			$data['qrcode']=$this->createQr($shoturl);
			$data['created']=date("Y-m-d H:i:s");
			//创建问卷
			$qs_id=$this->_qs->create($data);
			//创建摘要
			$Upload= & get_singleton ( "Service_UpLoad" );
			$folder="resource/upload/abstract/";
			if (! file_exists ( $folder )) {
				mkdir ( $folder, 0777 );
			}
			$Upload->setDir($folder.date("Ymd")."/");
			$absnum=$_POST['abstractnum'];
			for ($i=0;$i<$absnum;$i++){
				$abstract=array();
				$numi=($i+1);
				$Upload->setPrefixName($i);
				$img=$Upload->upload('abstractimg'.$numi);
				if($img['status']==1){
					$file_path=$img['file_path'];
				}
				$abstract['qs_id']=$qs_id;
				$abstract['title']=$_POST['abstract'.$numi]['title'];
				$abstract['content']=$_POST['abstract'.$numi]['content'];
				$abstract['imginfo']=$_POST['abstract'.$numi]['imginfo'];
				$abstract['img']=$file_path;
				$this->_qs_abstract->create($abstract);
			}
			//创建答题选项
			$step=$this->_common->filter($_POST['step']);
			$qeids=$this->_common->filter($_POST['qeid']);
			$probability=$this->_common->filter($_POST['probability']);
			$hascon=$this->_common->filter($_POST['hascon']);
			$aslimit=$this->_common->filter($_POST['aslimit']);
			$flag_over=$this->_common->filter($_POST['flag_over']);
			$num=1;
			$csp=$step[0];
			foreach ($step as $sk=>$sp){
				$prov=($probability[$sk]=='')?1:$probability[$sk];
				$qepath=array('qs_id'=>$qs_id,'step'=>$sp,'qe_id'=>$qeids[$sk],'num'=>$num,'probability'=>$prov,'hascon'=>$hascon[$sk],'aslimit'=>$aslimit[$sk],'flag_over'=>$flag_over[$sk]);
				if($csp!=$sp){
					$num=1;
				}else{
					++$num;
				}
				$csp=$sp;
				$this->_qepath->create($qepath);
				
			}
			$stepnumupdate=array('id'=>$qs_id,'step_num'=>$csp);
			$this->_qs->update($stepnumupdate);//更新最大步骤数
			
			$prevqe=$this->_common->filter($_POST['consprevqe']);
			$prevop=$this->_common->filter($_POST['consprevop']);
			$consqeid=$this->_common->filter($_POST['consqeid']);
			$constep=$this->_common->filter($_POST['constep']);
			foreach ($prevqe as $pk=>$qid){
				$qecon=array('qs_id'=>$qs_id,'prevqe_id'=>$qid,'prevop_id'=>empty($prevop[$pk])?null:$prevop[$pk],'qe_id'=>$consqeid[$pk],'step'=>$constep[$pk]);
				$this->_qecon->create($qecon);
			}
			$url=url('Qs','List');
			redirect($url);
		}
		$gps=$groups=$this->_group->findAll(array(),"id asc",null,array("id","name"));
		foreach ($groups as $kg=>$g){
			$groups[$kg]['qes']=$this->_qe->findAll(array('group_id'=>$g['id']));
		}
		$category=$this->_category->findAll(array(),"id");
		$this->_common->show ( array ('main' => 'qs/qsadd.tpl','groups'=>$groups,'category'=>$category,'gps'=>$gps) );
	}
	
	//专业问卷调查列表
	function actionList() {
		$pageparm = array ('status != 9 and status != 2');//9删除
		$page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1;
		$page_size = 20;
		$title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : '';

		$conditions=array('status != 9 and status != 2');
		if(!empty($title)){
			$conditions[]="title like '%$title%'";
			$pageparm['title']=$title;
		}

		$total=$this->_qs->findCount($conditions);

		$pages = & get_singleton ( "Service_Page" );
		$pages->_page_no = $page_no;
		$pages->_page_num = $page_size;
		$pages->_total = $total;
		$pages->_url = url ( "Qs", "List" );
		$pages->_parm = $pageparm;
		$page = $pages->page ();
		$start = ($page_no - 1) * $page_size;

		$list=$this->_qs->findAll($conditions,"id desc limit $start,$page_size");
		foreach ($list as $k=>$d){
			$list[$k]['num']=$this->_qs_answer->findCount(array('qs_id'=>$d['id']));
		}
		$this->_common->show ( array ('main' => 'qs/qslist.tpl','list'=>$list,'page'=>$page,'pageparm'=>$pageparm) );
	}
	//被删除的问卷列表
	function actionDeList() {
	$pageparm = array ('status = 9');//9删除
		$page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1;
		$page_size = 20;
		$title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : '';

		$conditions=array('status = 9');
		if(!empty($title)){
			$conditions[]="title like '%$title%'";
			$pageparm['title']=$title;
		}

		$total=$this->_qs->findCount($conditions);

		$pages = & get_singleton ( "Service_Page" );
		$pages->_page_no = $page_no;
		$pages->_page_num = $page_size;
		$pages->_total = $total;
		$pages->_url = url ( "Qs", "DeList" );
		$pages->_parm = $pageparm;
		$page = $pages->page ();
		$start = ($page_no - 1) * $page_size;

		$list=$this->_qs->findAll($conditions,"id desc limit $start,$page_size");
		foreach ($list as $k=>$d){
			$list[$k]['num']=$this->_qs_answer->findCount(array('qs_id'=>$d['id']));
		}
		$this->_common->show ( array ('main' => 'qs/deqslist.tpl','list'=>$list,'page'=>$page,'pageparm'=>$pageparm) );
	}
	
	//完成的问卷列表
	function actionFinshed(){
		$pageparm = array ('status = 2');//9删除
		$page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1;
		$page_size = 20;
		$title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : '';

		$conditions=array('status = 2');
		if(!empty($title)){
			$conditions[]="title like '%$title%'";
			$pageparm['title']=$title;
		}

		$total=$this->_qs->findCount($conditions);

		$pages = & get_singleton ( "Service_Page" );
		$pages->_page_no = $page_no;
		$pages->_page_num = $page_size;
		$pages->_total = $total;
		$pages->_url = url ( "Qs", "Finshed" );
		$pages->_parm = $pageparm;
		$page = $pages->page ();
		$start = ($page_no - 1) * $page_size;

		$list=$this->_qs->findAll($conditions,"id desc limit $start,$page_size");
		foreach ($list as $k=>$d){
			$list[$k]['num']=$this->_qs_answer->findCount(array('qs_id'=>$d['id']));
			$list[$k]['updated']=$this->_common->time2Units(time()-strtotime($d['updated']));
		}
		$this->_common->show ( array ('main' => 'qs/qslist.tpl','list'=>$list,'page'=>$page,'pageparm'=>$pageparm) );
	}
	
	//专业问卷编辑
	function actionEdit(){
		$qnnaid=isset ( $_GET ['qnnaid'] ) ? $_GET ['qnnaid'] : '';
		$act=isset ( $_POST ['act'] ) ? $_POST ['act'] : '';
		$msg='';
		if($act=='edit'){
			$data=$this->_common->filter($_POST['data']);
			$data['author']=htmlspecialchars_decode($data['author']);
			//问卷设置
			if(empty($data['over_num'])){
				unset($data['over_num']);
			}
			if(empty($data['over_date'])){
				unset($data['over_date']);
			}
			//清除旧二维码
			if(file_exists ( $data['qrcode'] )){
				unlink($data['qrcode']);
			}
			//短连接及二维码
			$shoturl=url('As','Index',array('time'=>time()));
			$shoturl=$this->_common->shortUrl($shoturl);
			$data['short']=$shoturl;
			$data['qrcode']=$this->createQr($shoturl);
			//创建问卷
			$qs_id=$data['id'];
			$this->_qs->update($data);
			//清除摘要和选项
			$this->_qs_abstract->removeByConditions(array('qs_id'=>$qs_id));
			//创建摘要
			$Upload= & get_singleton ( "Service_UpLoad" );
			$folder="resource/upload/abstract/";
			if (! file_exists ( $folder )) {
				mkdir ( $folder, 0777 );
			}
			$Upload->setDir($folder.date("Ymd")."/");
			$absnum=$_POST['abstractnum'];
			for ($i=0;$i<$absnum;$i++){
				$abstract=array();
				$numi=($i+1);
				$Upload->setPrefixName($i);
				$img=$Upload->upload('abstractimg'.$numi);
				$oldimg=$_POST['abstract'.$numi]['img'];
				if($img['status']==1){//如果有上传图片则更新
					$file_path=$img['file_path'];
					if(file_exists($oldimg)){
						unlink($oldimg);
					}
				}else{
					$file_path=$oldimg;
				}
				$abstract['qs_id']=$qs_id;
				$abstract['title']=$_POST['abstract'.$numi]['title'];
				$abstract['content']=$_POST['abstract'.$numi]['content'];
				$abstract['imginfo']=$_POST['abstract'.$numi]['imginfo'];
				$abstract['img']=$file_path;
				$this->_qs_abstract->create($abstract);
			}

			$this->_qepath->removeByConditions(array('qs_id'=>$qs_id));
			$this->_qecon->removeByConditions(array('qs_id'=>$qs_id));
			//创建答题选项
			$step=$this->_common->filter($_POST['step']);
			$qeids=$this->_common->filter($_POST['qeid']);
			$probability=$this->_common->filter($_POST['probability']);
			$hascon=$this->_common->filter($_POST['hascon']);
			$aslimit=$this->_common->filter($_POST['aslimit']);
			$flag_over=$this->_common->filter($_POST['flag_over']);
			$num=1;
			$csp=$step[0];
			foreach ($step as $sk=>$sp){
				$prov=($probability[$sk]=='')?1:$probability[$sk];
				$qepath=array('qs_id'=>$qs_id,'step'=>$sp,'qe_id'=>$qeids[$sk],'num'=>$num,'probability'=>$prov,'hascon'=>$hascon[$sk],'aslimit'=>$aslimit[$sk],'flag_over'=>$flag_over[$sk]);
				if($csp!=$sp){
					$num=1;
				}else{
					++$num;
				}
				$csp=$sp;
				$this->_qepath->create($qepath);
			
			}
			
			$stepnumupdate=array('id'=>$qs_id,'step_num'=>$csp);
			$this->_qs->update($stepnumupdate);//更新最大步骤数
			
			$prevqe=$this->_common->filter($_POST['consprevqe']);
			$prevop=$this->_common->filter($_POST['consprevop']);
			$consqeid=$this->_common->filter($_POST['consqeid']);
			$constep=$this->_common->filter($_POST['constep']);
			foreach ($prevqe as $pk=>$qid){
				$qecon=array('qs_id'=>$qs_id,'prevqe_id'=>$qid,'prevop_id'=>empty($prevop[$pk])?null:$prevop[$pk],'qe_id'=>$consqeid[$pk],'step'=>$constep[$pk]);
				$this->_qecon->create($qecon);
			}
			$msg="更新成功!";
		}
		$gps=$groups=$this->_group->findAll(array(),"id asc",null,array("id","name"));
		foreach ($groups as $kg=>$g){
			$groups[$kg]['qes']=$this->_qe->findAll(array('group_id'=>$g['id']));
		}
		$questionnaire=$this->_qs->findByField('id',$qnnaid);
		$abstract=$this->_qs_abstract->findAll(array('qs_id'=>$qnnaid),'id asc');
		$path=$this->_qepath->findAll(array('qs_id'=>$qnnaid),'step asc,id asc');
		$qes=$qe=array();
		$step='';
		foreach ($path as $p){
			if($step!=$p['step']){
				if(count($qe)>0){$qes[]=$qe;}
				$qe=array();
			}
			$question=$this->_qe->findByField('id',$p['qe_id']);
			$p['question']=$question;
			$p['qecon']=$this->_qecon->findAll(array('step'=>$p['step'],'qs_id'=>$qnnaid,'qe_id'=>$p['qe_id']));
			$qe[]=$p;
			$step=$p['step'];
		}
		if(count($qe)>0){$qes[]=$qe;}
		$category=$this->_category->findAll(array(),"id");
		$this->_common->show ( array ('main' => 'qs/qsedit.tpl','questionnaire'=>$questionnaire,'abstract'=>$abstract,'msg'=>$msg,'groups'=>$groups,'category'=>$category,'gps'=>$gps,'path'=>$path,'qes'=>$qes) );
	}
	
	//再次发布
	function actionRePublic(){
		$qnnaid=isset ( $_GET ['qnnaid'] ) ? $_GET ['qnnaid'] : '';
		$questionnaire=$this->_qs->findByField('id',$qnnaid);
		if(is_array($questionnaire)){
			$abstract=$this->_qs_abstract->findAll(array('qs_id'=>$qnnaid),'id asc');
			$qepath=$this->_qepath->findAll(array('qs_id'=>$qnnaid),'id');
			$qecon=$this->_qecon->findAll(array('qs_id'=>$qnnaid),'id');
				
			unset($questionnaire['id']);
			//短连接及二维码
			$shoturl=url('As','Index',array('time'=>time()));
			$shoturl=$this->_common->shortUrl($shoturl);
			$questionnaire['short']=$shoturl;
			$questionnaire['qrcode']=$this->createQr($shoturl);
			$questionnaire['status']=0;
			$questionnaire['created']=date("Y-m-d H:i:s");
			$newqnnaid=$this->_qs->create($questionnaire);
			foreach ($abstract as $ab){
				unset($ab['id']);
				$ab['qs_id']=$newqnnaid;
				$this->_qs_abstract->create($ab);
			}
			foreach ($qepath as $q){
				unset($q['id']);
				$q['qs_id']=$newqnnaid;
				$this->_qepath->create($q);
			}
			foreach ($qecon as $q){
				unset($q['id']);
				$q['qs_id']=$newqnnaid;
				$this->_qecon->create($q);
			}
		}
	
		$url=url('Qs','List');
		redirect($url);
	}
	
	//删除status9
	function actionDel(){
		$id=$this->_common->filter($_GET['id']);
		$eve=array('id'=>$id,'status'=>9);
		$this->_qs->update($eve);
		redirect($_SERVER['HTTP_REFERER']);
	}
	//发布status1
	function actionPublic(){ 
		$id=$this->_common->filter($_GET['id']);
		$eve=array('id'=>$id,'status'=>1);
		$this->_qs->update($eve);
		redirect($_SERVER['HTTP_REFERER']);
	}
	//结束status2
	function actionEnd(){
		$id=$this->_common->filter($_GET['id']);
		$eve=array('id'=>$id,'status'=>2);
		$this->_qs->update($eve);
		$msg=SITEHOST.'/result.php?qnnaid='.$id;
		$wechatObj = WeChat::getInstance();
		$wechatObj->sendCustomMsg('分析结果是 '.$msg,"o9ZPks_8ZpcQXBndQqjuUpt-E9tg");
		redirect($_SERVER['HTTP_REFERER']);
	}

	//ajax获取问题选项
	function actionGetOpsByQe(){
		$qeid=$this->_common->filter($_POST['qeid']);
		$qe=$this->_qe->findByField('id',$qeid);
		$op=$this->_op->findAll(array('qe_id'=>$qeid),'id asc');
		$qe['op']=$op;
		echo json_encode($qe);
	}
	//ajax根据分组获取问题
	function actionGetQeByGroup(){
		$gid=$this->_common->filter($_POST['gid']);
		$qes=$this->_qe->findAll(array('group_id'=>$gid));
		echo json_encode($qes);
	}
	//ajax获取前置条件
	function actionGetBeforeCon(){
		$qe=$this->_common->filter($_POST['qe']);
		$op=$this->_common->filter($_POST['op']);
		$curqeid='';
		$data=array();
		$qandop=array();
		foreach ($qe as $k=>$q){
			$qes=$this->_qe->findByField('id',$q);
			if($q!=$curqeid&&!empty($qandop)){
				$qandop['ops']=$this->_op->findAll(array('qe_id'=>$qandop['qeid']),'id asc');
				$data[]=$qandop;
				$qandop=array();
			}
			$qandop['qeid']=$q;
			$qandop['qetype']=$qes['type'];
			$qandop['opids'][]=$op[$k];
			$curqeid=$q;
		}
		if(!empty($qandop)){
			$qandop['ops']=$this->_op->findAll(array('qe_id'=>$qandop['qeid']),'id asc');
			$data[]=$qandop;
		}
		echo json_encode($data);
	}
	
	function createQr($shoturl){
		$qrfile='resource/upload/'.$shoturl.'.png';
		$qrurl=SITEHOST.url('As','Qrcode',array('short'=>$shoturl));
		QRcode::png($qrurl,$qrfile,0,10,1);//生成二维码
		//file_put_contents($qrfile , file_get_contents($this->_common->downloadQRpngfromGoogle($qrurl,300,300)));//生成本地图片
		return $qrfile;
	}
}
<file_sep>/const.php
<?php
define ('DEFAUT_TITLE',"调查问卷管理后台");
define('SERVERROOT',dirname(__FILE__) );
$httpsflag=isset($_SERVER['HTTPS'])?$_SERVER['HTTPS']:"";
if(empty($httpsflag)){
	$urlprefix="http://";
}else{
	$urlprefix="http://";
}
define('SITE',$urlprefix.$_SERVER['HTTP_HOST'].substr($_SERVER['PHP_SELF'],0,strrpos ($_SERVER['PHP_SELF'],'/')+1));
//define('SITEHOST','http://www.planinbook.com:8021');
define('SITEHOST','http://192.168.11.100');

?><file_sep>/App/Controller/Admin.php
<?php
class Controller_Admin extends FLEA_Controller_Action {
	/**
	 *
	 * Enter description here ...
	 * @var Class_Common
	 */
	var $_common;
	var $_admin;
	var $_adminid;
	var $_questionnaire;
	var $_question;
	var $_option;
	var $_answer;

	function __construct() {
		$this->_common = get_singleton ( "Class_Common" );

		$this->_admin = get_singleton ( "Model_Admin" );
		$this->_questionnaire = get_singleton ( "Model_Questionnaire" );
		$this->_question = get_singleton ( "Model_Question" );
		$this->_option = get_singleton ( "Model_Option" );
		$this->_answer = get_singleton ( "Model_Answer" );
		$this->_adminid = isset ( $_SESSION ['loginuserid'] ) ? $_SESSION ['loginuserid'] : "";
		if(empty($_SESSION ['loginuserid'])){
			$url=url("Default","Login");
			redirect($url);
		}
	}

	//问卷列表
	function actionChangePass() {
		$msg='';
		$act=isset($_POST['act'])?$this->_common->filter($_POST['act']):'';
		if($act=='update'){
			$data=$this->_common->filter($_POST);
			$old_pass=$data['old_pass'];
			$new_pass=$data['new_pass'];
			$confirm_pass=$data['confirm_pass'];
			if(empty($old_pass)||empty($new_pass)||empty($confirm_pass)){
				$msg='请输入正确内容';
			}elseif($new_pass!=$confirm_pass){
				$msg='新密码确认内容不一致';
			}else{
				$adm=$this->_admin->findByField('id',$this->_adminid);
				if(md5($old_pass)!=$adm['adm_password']){
					$msg='原始密码不正确';
				}else{
					$adm['adm_password']=md5($new_pass);
					$this->_admin->update($adm);
					$msg='密码更新成功';
				}
			}
		}
		$this->_common->show ( array ('main' => 'admin/change_pass.tpl','msg'=>$msg) );
	}
	
	//管理问卷公共信息
	function actionCommonInfo(){
		$msg='';
		$act=isset($_POST['act'])?$this->_common->filter($_POST['act']):'';
		if($act=='update'){
			$admin = $this->_admin->findByField('id',$this->_adminid);
			$data=$this->_common->filter($_POST);
			$info['id']=$this->_adminid;
			$info['complete_msg']=$data['complete_msg'];
			$info['sign_text']=$data['sign_text'];
			//签名图片
			$Upload= & get_singleton ( "Service_UpLoad" );
			$folder="resource/upload/signimg/";
			if (! file_exists ( $folder )) {
				mkdir ( $folder, 0777 );
			}
			$Upload->setDir($folder.$admin['adm_name']."/");
			$oldimg=$admin['sign_img'];
			$img=$Upload->upload('file');
			if($img['status']==1){//如果有上传图片则更新
				$info['sign_img']=$img['file_path'];
				if(file_exists($oldimg)){
					unlink($oldimg);
				}
			}else{
				$info['sign_img']=$oldimg;
			}

			$this->_admin->update($info);
			$msg='更新成功';
		}
		$info=$this->_admin->findByField('id',$this->_adminid);
		$this->_common->show ( array ('main' => 'admin/common_info.tpl','msg'=>$msg,'admin'=>$info) );
	}
	
}<file_sep>/resource/js/qa.js
$(function(){
	setInterval(function(){$('#time').val($('#time').val()*1+1)},1000);
	$('#submit').click(function(){
		if($('#questionnaire_status').val()!=1){
			if($('#questionnaire_status').val()==2){
				alert('调查问卷已结束,您不能答题');
			}else{
				alert('调查问卷还没发布,您不能答题');
			}
			return false;
		}else{
			return true;
		}
	});
	$('.anstext').blur(function(){
		var qeobj=$(this).parent().parent();
		var type=qeobj.find('.qetype').val();
		if(type==3){
			var i=qeobj.find('.anstext').index($(this));
			qeobj.find('input[name^=anscontent]').eq(i).val($(this).val());
		}
		if(type==4){
			var str='';
			qeobj.find('.anstext').each(function(i){
				str+=$(this).val()+',';
			});
			qeobj.find('input[name^=anscontent]').val(str.slice(0,-1));
		}
	});
	//选中高亮切换
	$('input[type=radio],input[type=checkbox]').change(function(){
		$('input[type=radio],input[type=checkbox]').each(function(i){
			if($(this).attr('checked')){
				$(this).parent().css('background-color','#d5eaff');
			}else{
				$(this).parent().css('background-color','#fff');
			}
		});
	});
	$('#copyQurl').click(function(){
		//window.clipboardData.setData("Text等等", '需要复制的信息');
		//alert('复制成功');
		return false;
	});
});
