Ver Fonte

Merge branch 'yhz_paper_paser_v1' into testing

yanghz há 5 meses atrás
pai
commit
867ca45f74

+ 246 - 173
protected/commands/WordPushCommand.php

@@ -1,181 +1,234 @@
 <?php
-class WordPushCommand extends CConsoleCommand {
- 	public function init() {
-    	parent::init();
-    	
-    	@ini_set('memory_limit', '1024M');
-		set_time_limit(0);
+
+class WordPushCommand extends CConsoleCommand
+{
+	public $examType = array(1=>'周考', 2=>'单元考', 3=>'月考', 4=>'联考', 5=>'期中',6=>'期末', 7=>'高考模拟', 8=>'冲刺', 9=>'测试');
+	public $topicTypeName = array(
+		3 => array(1=>'选择题',2=>'多选题',5=>'填空题',6=>'填空题',7=>'解答题',11=>'不定项'),
+		8 => array(1=>'单项填空',2=>'完形填空',3=>'阅读理解',4=>'任务型阅读',5=>'七选五',6=>'语法填空',7=>'短文改错',13=>'书面表达',15=>'听力',16=>'应用文写作',17=>'读后续写'),
+	);
+
+    public function init()
+    {
+        parent::init();
+
+        @ini_set('memory_limit', '1024M');
+        set_time_limit(0);
     }
-	
-	public function actionIndex($school_id='',$YII_ENV='development') {
-        $pdoParam = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8";');
-	    // 连接业务库
-	    $school_dsn = 'mysql:host='.Yii::app()->params["default_server"]['addr'].';dbname='.Yii::app()->params["default_db"]['name'].';';
-	    $school_dbh = new PDO($school_dsn,Yii::app()->params["default_server"]['username'],Yii::app()->params["default_server"]['password'],array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8";'));
-
-	    $school_str = '';
-	    if ($school_id) {
-	        $school_str  =   $school_id;
-	    } else {
-	        // 获取所有可用的学校
-	        $school_obj = $school_dbh->query('SELECT school_id FROM `school` WHERE `status`=0');
-	        $school_info=	$school_obj->fetchAll(PDO::FETCH_ASSOC);
-	        if (empty($school_info)) {
-	            exit('未找到可用的学校!');
-	        }
-	        
-	        $school_array = array();
-	        foreach ($school_info as $school) {
-	            array_push($school_array, $school['school_id']);
-	        }
-	        
-	        $school_str = implode(',', $school_array);
-	    }
-        if(!$school_str){
-            exit('未找到学校数据库链接信息!');
+
+    public function actionIndex($school_id = '', $YII_ENV = 'development')
+    {
+		// 连接业务库
+//        $pdoParam = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8";');
+//        $businessServer = Yii::app()->params["businessDb"];
+        $databaseFields = 'database_host,database_name,database_user,database_password,school_id';
+//        $busDsn = 'mysql:host=' . $businessServer['addr'] . ';dbname=' . Yii::app()->params["default_db"]['name'] . ';';
+//        $busDbh = new PDO($busDsn, $businessServer['username'], $businessServer['password'], $pdoParam);
+        $busDbh = Yii::app()->businessDb;
+        // 获取所有可用的学校
+        if ($school_id) {
+            $dataSql = "SELECT {$databaseFields} FROM `database` WHERE `school_id` IN ({$school_id})";
+        } else {
+            $dataSql = "SELECT {$databaseFields} FROM `database` WHERE `school_id` IN (SELECT school_id FROM `school` WHERE `status`=0)";
         }
-	    // 找出学校的链接信息
-	    $data_obj = $school_dbh->query('SELECT *  FROM `database` WHERE `school_id` IN ('.$school_str.')');
-	    if(!$data_obj){
+
+        // 找出学校的链接信息
+        $dataObj = $busDbh->query($dataSql);
+        $dataInfo = $dataObj->fetchAll(PDO::FETCH_ASSOC);
+        if (empty($dataInfo)) {
             exit('未找到学校数据库链接信息!');
         }
-	    $data_info=	$data_obj->fetchAll(PDO::FETCH_ASSOC);
-	    if (empty($data_info)) {
-	        exit('未找到学校数据库链接信息!');
-	    }
-	   
-	    // 关闭链接
-	    $school_dbh = null;
-
-	    $my_path = dirname(dirname(dirname(__FILE__)));
-	    $callback_url = Yii::app()->params['server_callback_url'];
-	    $coach_server_callback_url = Yii::app()->params['coach_server_callback_url'];
-	    $mathml_type  = Yii::app()->params['formula_type'];
-        $xbpaper_callback_url = Yii::app()->params['xbpaper_callback_url']; //校本卷库word回调地址
-	    $request_url  = Yii::app()->params['word_analysis_url'];
-		$_callback_url	=	'';
-	    
-	   // echo $mathml_type;die;
-	    // 发送Word处理
-	    foreach ($data_info as $data) {
-	        echo 'STARTING==>'.$data['school_id']. "\n";
-	        
-	        $temp_dsn = 'mysql:host='.$data['database_host'].';dbname='.$data['database_name'].';';
-	        $temp_dbh = new PDO($temp_dsn,$data['database_user'],$data['database_password'],array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8";'));
-	        	        
-	        $temp_obj = $temp_dbh->query('SELECT * FROM `topic_word` WHERE `exam_group_id`!="" and `status`=0');
-	        $temp_info= $temp_obj->fetchAll(PDO::FETCH_ASSOC);
-	        if (empty($temp_info)) {
-	            echo 'not found any word in school_'.$data['school_id']. "\n";
-	        } else {
-
-	            foreach ($temp_info as $info) {
-					if(empty($info['exam_group_id']))
-					{
-						continue;
-					}
 
+		 // 获取学校所属的省份
+        $schoolIds = array();
+        $schoolProvince = array();
+        foreach($dataInfo as $tempSchool) {
+            $schoolIds[] = $tempSchool['school_id'];
+        }
 
-                    if(false !== strpos($info['word_path'],'http://'))
-                    {
-                        $time = time();
-                        $arr = self::getFile($info['word_path'],'/tem',$info['uploader_id'].$time.'.docx');
-                        if($arr)
-                        {
-                            if (file_exists($arr['save_path']))
-                            {
-                                $_callback_url = $callback_url;
-                                if(!empty($info['exam_group_id']))
-                                {
-                                    $_callback_url = $coach_server_callback_url;
-                                }
-                                //校本卷库
-                                if($info['type_id']==1){
-                                    $_callback_url = $xbpaper_callback_url;
-                                }
-
-                                $retRes = self::curlWord($request_url,$_callback_url,$info['word_id'],$arr['save_path'],$data['school_id']);
-
-                                $json_array = json_decode($retRes,true);
-                                $temp_dbh = new PDO($temp_dsn,$data['database_user'],$data['database_password'],$pdoParam);
-                                if (!$json_array || $json_array['errcode'] > 0) {
-                                    $temp_dbh->exec("UPDATE `topic_word` SET `status` = '3',`wrong_reason` = '".$json_array['errmsg']."',`content` ='".$retRes."'  WHERE `word_id` ='".$info['word_id']."'");
-                                } else {
-                                    $temp_dbh->exec("UPDATE `topic_word` SET `status` = '1',`file_queue`='".$json_array['docsbefore']."' WHERE `word_id` ='".$info['word_id']."'");
-                                }
-                                $temp_dbh = null;
-                            }
-                        }
-                        @unlink($arr['save_path']);
-                    }else {
-                        if (file_exists($my_path . '/' . $info['word_path'])) {
-                            echo 'Send the word path : ' . $info['word_path'] . "\n";
-                            $_callback_url = $callback_url;
-                            if (!empty($info['exam_group_id'])) {
-                                $_callback_url = $coach_server_callback_url;
-                            }
-                            $retRes = self::curlWord($request_url, $_callback_url, $info['word_id'], $my_path . '/' . $info['word_path'], $data['school_id'], $mathml_type);
-                            $json_array = json_decode($retRes, true);
-                            if (!$json_array || $json_array['errcode'] > 0) {
-                                $temp_dbh->exec("UPDATE `topic_word` SET `status` = '3',`wrong_reason` = '" . $json_array['errmsg'] . "',`content` ='" . $retRes . "'  WHERE `word_id` ='" . $info['word_id'] . "'");
-                            } else {
-                                $temp_dbh->exec("UPDATE `topic_word` SET `status` = '1',`file_queue`='" . $json_array['docsbefore'] . "' WHERE `word_id` ='" . $info['word_id'] . "'");
-                            }
-                        } else {
-                            echo 'lost the word path : ' . $my_path . '/' . $info['word_path'] . "\n";
+		$schoolIdString = implode(',', $schoolIds);
+        $schoolObj = $busDbh->query("SELECT s.school_id,r.region_name FROM `school` s LEFT JOIN `region` r ON r.region_id = s.province_id WHERE s.`school_id` IN ({$schoolIdString})");
+        $schoolInfo = $schoolObj->fetchAll(PDO::FETCH_ASSOC);
+        foreach ($schoolInfo as $key => $tempProvince) {
+            $schoolProvince[$tempProvince['school_id']] = $tempProvince['region_name'];
+        }
+
+		// 获取所有学科
+        $packSubject = array();
+        $subjectObj = $busDbh->query('SELECT subject_id,subject_name,section FROM `subject`')->fetchAll(PDO::FETCH_ASSOC);
+        foreach($subjectObj as $tempSubject) {
+            $packSubject[$tempSubject['subject_id']]['name'] = $tempSubject['subject_name'];
+            $packSubject[$tempSubject['subject_id']]['section'] = $tempSubject['section'];
+        }
+
+        $busDbh = null; // 关闭链接
+        $callbackUrl = ''; // 回调地址
+        $analysisUrl = ''; // 解析地址
+        $myPath = dirname(dirname(dirname(__FILE__)));
+        $scienceWordAnalysisUrl = Yii::app()->params['science_word_analysis_url']; // 物理解析地址
+        $subjectCoachCallbackUrl = Yii::app()->params['subject_coach_callback_url']; // 全学科第三方试卷解析回调
+		
+		// 新解析工具
+		$rapidAnalysisUrl = Yii::app()->params['rapid_analysis_url']; // 解析地址
+        $rapidCallbackUrl = Yii::app()->params['rapid_callback_url']; // 解析回调
+
+        // 发送Word处理
+        foreach ($dataInfo as $data) {
+            echo 'STARTING==>' . $data['school_id'] . "\n";
+
+            $temp_dsn = 'mysql:host=' . $data['database_host'] . ';dbname=' . $data['database_name'] . ';';
+            $temp_dbh = new PDO($temp_dsn, $data['database_user'], $data['database_password'], $pdoParam);
+            $temp_obj = $temp_dbh->query('SELECT word_id,exam_group_id,word_path,uploader_id,type_id,subject_id,allsubject_file_path,source FROM `topic_word` WHERE `status`=0 AND `source` != 4');
+            $temp_info = $temp_obj->fetchAll(PDO::FETCH_ASSOC);
+            if (empty($temp_info)) {
+                echo 'not found any word in school_' . $data['school_id'] . "\n";
+            } else {
+                foreach ($temp_info as $info) {
+
+					// 老版解析工具
+					if (empty($info['allsubject_file_path'])) {
+                        $analysisUrl = $scienceWordAnalysisUrl; // 高中物理解析地址
+                        if ($info['exam_group_id']) {
+                            $callbackUrl = $subjectCoachCallbackUrl;
                         }
-                    }
-	            }
-	        }
-	        
-	        echo 'ENDING==>'.$data['school_id']. "\n\n";
-	    }
-	}
-
-	// POST word
-    public function curlWord($request_url,$word_api_url,$word_id,$postFilePath,$school_id){
-
-		/*if (substr(PHP_VERSION, 0, 3) >= '5.5') {
-	        $cfile = curl_file_create($postFilePath,'application/vnd.openxmlformats-officedocument.wordprocessingml.document','wordname'); // try adding
-			if ($formulaType == 1) {
-				$imgdata = array('callback_url'=>$word_api_url.'/wordapi/index/sid/'.$school_id.'/wid/'.$word_id,'file' => $cfile,'type'=>'batch','format'=>'mathml');
-			} else {
-				$imgdata = array('callback_url'=>$word_api_url.'/wordapi/index/sid/'.$school_id.'/wid/'.$word_id,'file' => $cfile,'type'=>'batch');
-			}
-	    } else {
-			if ($formulaType == 1) {
-				$imgdata = array('callback_url'=>$word_api_url.'/wordapi/index/sid/'.$school_id.'/wid/'.$word_id,'file' => '@'.$postFilePath,'type'=>'batch','format'=>'mathml');
-			} else {
-				$imgdata = array('callback_url'=>$word_api_url.'/wordapi/index/sid/'.$school_id.'/wid/'.$word_id,'file' => '@'.$postFilePath,'type'=>'batch');
-			}
-	    }*/
-
-		if (substr(PHP_VERSION, 0, 3) >= '5.5') {
-		   $pathName = pathinfo($postFilePath);
-	       $cfile = curl_file_create($postFilePath,'application/vnd.openxmlformats-officedocument.wordprocessingml.document',$pathName['basename']);
-		   $imgdata = array('callback_url'=>$word_api_url.'/sid/'.$school_id.'/wid/'.$word_id.'/flag/1','sid'=>$school_id,'flag'=>1,'mydata' => $cfile);
-	    } else {
-    	    $imgdata = array('callback_url'=>$word_api_url.'/sid/'.$school_id.'/wid/'.$word_id.'/flag/1','sid'=>$school_id,'flag'=>1,'mydata' => '@'.$postFilePath);
-	    }
-
-		$curl = curl_init();
-		curl_setopt($curl, CURLOPT_URL, $request_url);
-		curl_setopt($curl, CURLOPT_USERAGENT,'Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15');
-		curl_setopt($curl, CURLOPT_HTTPHEADER,array('User-Agent: Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15','Referer: http://someaddress.tld','Content-Type: multipart/form-data'));
-		//curl_setopt($ch, CURLOPT_HEADER, false);
-		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
-		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
-		curl_setopt($curl, CURLOPT_POST, true);
-		curl_setopt($curl, CURLOPT_POSTFIELDS, $imgdata);
-		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
-		$r = curl_exec($curl);
-		curl_close($curl);
-		return $r;
-	}
-
-    protected function getFile($url, $save_dir = '', $filename = '', $type = 0) {
-
-        $file_type = strtolower(substr($url ,strrpos($url ,'.')+1));
+
+						if (empty($callbackUrl) || empty($analysisUrl)) continue;
+						echo $analysisUrl.'----'.$callbackUrl. "\n";
+
+						if (false !== strpos($info['word_path'], 'http://')) {
+							$time = time();
+							$arr = self::getFile($info['word_path'], '/tem', $info['uploader_id'] . $time . '.docx');
+							if ($arr && file_exists($arr['save_path'])) {
+								$retRes = self::curlWord($analysisUrl, $callbackUrl, $info['word_id'], $arr['save_path'], $data['school_id']);
+								$json_array = json_decode($retRes, true);
+								$temp_dbh = new PDO($temp_dsn, $data['database_user'], $data['database_password'], $pdoParam);
+								if (!$json_array || $json_array['errcode'] > 0) {
+									$temp_dbh->exec("UPDATE `topic_word` SET `status` = '3',`wrong_reason` = '" . $json_array['errmsg'] . "',`content` ='" . $retRes . "'  WHERE `word_id` ='" . $info['word_id'] . "'");
+								} else {
+									$temp_dbh->exec("UPDATE `topic_word` SET `status` = '1',`file_queue`='" . $json_array['docsbefore'] . "' WHERE `word_id` ='" . $info['word_id'] . "'");
+								}
+								$temp_dbh = null;
+								@unlink($arr['save_path']);
+								echo 'Send the word id : ' . $info['word_id'] . "\n";
+							}
+						} else {
+							if (file_exists($myPath . '/' . $info['word_path'])) {
+								echo 'Send the word path : ' . $info['word_path'] . "\n";
+
+								$retRes = self::curlWord($analysisUrl, $callbackUrl, $info['word_id'], $myPath . '/' . $info['word_path'], $data['school_id']);
+								$json_array = json_decode($retRes, true);
+								$temp_dbh = new PDO($temp_dsn, $data['database_user'], $data['database_password'], $pdoParam);
+								if (!$json_array || $json_array['errcode'] > 0) {
+									$temp_dbh->exec("UPDATE `topic_word` SET `status` = '3',`wrong_reason` = '" . $json_array['errmsg'] . "',`content` ='" . $retRes . "'  WHERE `word_id` ='" . $info['word_id'] . "'");
+								} else {
+									$temp_dbh->exec("UPDATE `topic_word` SET `status` = '1',`file_queue`='" . $json_array['docsbefore'] . "' WHERE `word_id` ='" . $info['word_id'] . "'");
+								}
+							} else {
+								echo 'lost the word path : ' . $myPath . '/' . $info['word_path'] . "\n";
+							}
+						}
+					} else {
+						$paperTopicType = array();
+						$typeNames = $info['subject_id'] == 8 ? $this->topicTypeName[8] : $this->topicTypeName[3];
+
+						// 考试信息
+						$exam = $temp_dbh->query('SELECT `name`,`type`,`exam_id` FROM `exam` WHERE `exam_group_id`="' . $info['exam_group_id'].'"')->fetch(PDO::FETCH_ASSOC);
+						if (empty($exam)) continue;
+
+						// 在线答题卡PDF
+						$card = $temp_dbh->query('SELECT `online_card_pdf` FROM `third_answer_sheet` WHERE `exam_group_id`="' . $info['exam_group_id'].'"')->fetch(PDO::FETCH_ASSOC);
+						$onlineCardPdf = $card && !empty($card['online_card_pdf']) ? $card['online_card_pdf'] : '';
+
+						// 获取考试试题信息
+						$paperTopics = $temp_dbh->query('select ptr.topic_id,ptr.type from paper p left join paper_topic_relation ptr ON ptr.paper_id = p.paper_id where p.exam_id="'.$exam['exam_id'].'" order by ptr.order asc')->fetchAll(PDO::FETCH_ASSOC);
+						if (empty($paperTopics)) continue;
+						
+						if ($info['subject_id'] == 8) { // 英语试卷获取大题逻辑题型
+							$largeTopics = $temp_dbh->query('select ptl.logic_type from paper p left join paper_topic_large ptl ON ptl.paper_id = p.paper_id where p.exam_id="'.$exam['exam_id'].'" order by ptl.topic_no asc')->fetchAll(PDO::FETCH_ASSOC);
+							if ($largeTopics) {
+								foreach ($largeTopics as $largeTopic) {
+									$paperTopicType[] = isset($typeNames[$largeTopic['logic_type']]) ? $typeNames[$largeTopic['logic_type']] : '';
+								}
+							}
+						} else {
+							foreach ($paperTopics as $paperTopic) {
+								$paperTopicType[] = isset($typeNames[$paperTopic['type']]) ? $typeNames[$paperTopic['type']] : '解答题';
+							}
+						}
+
+						$wordParams = array(
+							'source' => 'xue_guan',
+							'paper_name' => $exam['name'],
+							'subject' => isset($packSubject[$info['subject_id']]) ? $packSubject[$info['subject_id']]['name'] : '',
+							'period' => isset($packSubject[$info['subject_id']]) && $packSubject[$info['subject_id']]['section'] == 1 ? '高中' : '初中',
+							'province' => isset($schoolProvince[$data['school_id']]) ? $schoolProvince[$data['school_id']] : '中国',
+							'category' => isset($this->examType[$exam['type']]) ? array($this->examType[$exam['type']]) : array(),
+							'is_cloud' => 1, 
+							'file_list' => json_decode($info['allsubject_file_path'],true),
+							'item_num_info' => array(
+								'total_nums' => count($paperTopics),
+								'paper_topic_type' => $paperTopicType,
+								'paper_card_pdf' => $onlineCardPdf
+							),
+							'callback_url' => $rapidCallbackUrl . '/sid/' . $data['school_id'] . '/wid/' . $info['word_id']
+						);
+						$retrunJson = self::curlFile($rapidAnalysisUrl, json_encode($wordParams));
+						$returnResult = json_decode($retrunJson, true);
+						if (isset($returnResult['id']) && $returnResult['id'] != 0) {
+							$temp_dbh->exec("UPDATE `topic_word` SET `status` = '1',`params_id`='" . $returnResult['id'] . "' WHERE `word_id` ='" . $info['word_id'] . "'");
+						} else {
+							$temp_dbh->exec("UPDATE `topic_word` SET `status` = '3',`wrong_reason` = '发送解析异常',`content` ='" . $retrunJson . "'  WHERE `word_id` ='" . $info['word_id'] . "'");
+						}
+						echo 'Send the word id : ' . $info['word_id'] . "\n";
+					}
+                }
+            }
+
+            $temp_dbh = null;
+            echo 'ENDING==>' . $data['school_id'] . "\n\n";
+        }
+    }
+
+    // POST word
+    public function curlWord($analysisUrl, $word_api_url, $word_id, $postFilePath, $school_id)
+    {
+        if (substr(PHP_VERSION, 0, 3) >= '5.5') {
+            $pathName = pathinfo($postFilePath);
+            $cfile = curl_file_create($postFilePath, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', $pathName['basename']);
+            $imgdata = array(
+				'callback_url' => $word_api_url . '/sid/' . $school_id . '/wid/' . $word_id . '/is_cloud/1',
+				'sid' => $school_id,
+				'is_cloud' => 1,
+				'mydata' => $cfile
+			);
+        } else {
+            $imgdata = array(
+				'callback_url' => $word_api_url . '/sid/' . $school_id . '/wid/' . $word_id . '/is_cloud/1',
+				'sid' => $school_id,
+				'is_cloud' => 1,
+				'mydata' => '@' . $postFilePath
+			);
+        }
+
+        $curl = curl_init();
+        curl_setopt($curl, CURLOPT_URL, $analysisUrl);
+        curl_setopt($curl, CURLOPT_USERAGENT, 'Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15');
+        curl_setopt($curl, CURLOPT_HTTPHEADER, array('User-Agent: Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15', 'Referer: http://someaddress.tld', 'Content-Type: multipart/form-data'));
+        //curl_setopt($ch, CURLOPT_HEADER, false);
+        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
+        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
+        curl_setopt($curl, CURLOPT_POST, true);
+        curl_setopt($curl, CURLOPT_POSTFIELDS, $imgdata);
+        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
+        $r = curl_exec($curl);
+        curl_close($curl);
+        return $r;
+    }
+
+    protected function getFile($url, $save_dir = '', $filename = '', $type = 1)
+    {
+
+        $file_type = strtolower(substr($url, strrpos($url, '.') + 1));
 
         //获取远程文件所采用的方法
         if ($type) {
@@ -192,9 +245,10 @@ class WordPushCommand extends CConsoleCommand {
             $content = ob_get_contents();
             ob_end_clean();
         }
-        //echo $content;
+
         $size = strlen($content);
         $test_dir = tempnam($save_dir, $filename);
+
         //文件大小
         $fp2 = @fopen($test_dir, 'w');
         fwrite($fp2, $content);
@@ -202,12 +256,31 @@ class WordPushCommand extends CConsoleCommand {
         unset($content, $url);
         $path = explode('.', $test_dir);
 
-        @rename($test_dir,$path[0].'.'.$file_type);
+        @rename($test_dir, $path[0] . '.' . $file_type);
         return array(
             'file_name' => $filename,
-            'save_path' => $path[0].'.'.$file_type,
+            'save_path' => $path[0] . '.' . $file_type,
             'file_size' => $size
         );
     }
 
+	// POST WORD
+    public function curlFile($analysisUrl, $wordParams)
+    {
+        $ch = curl_init();
+        curl_setopt($ch, CURLOPT_HEADER, 0); // 不输出头部
+        curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 返回数据等待
+        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); // 连接等待时间
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 获取到的内容不直接输出, 而是返回
+        curl_setopt($ch, CURLOPT_URL, $analysisUrl);
+        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)');
+        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
+        curl_setopt($ch, CURLOPT_POST, 1);
+        curl_setopt($ch, CURLOPT_POSTFIELDS, $wordParams);
+		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($wordParams)));
+        $output = curl_exec($ch);
+		$errnoNumber = curl_errno($ch);
+        curl_close($ch);
+        return $errnoNumber ? 'curl_errno:' . $errnoNumber : $output;
+    }
 }

+ 589 - 0
protected/controllers/ParseapiController.php

@@ -0,0 +1,589 @@
+<?php
+
+/**
+ * word试题解析入库操作类
+ * @author Andy
+ * @date 2021-08-20
+ * @company 上海互教教育科技有限公司.
+ */
+class ParseapiController extends CController
+{
+    public $supportTypeName = array(1=>'选择题','2'=>'多选题',11=>'多选题',5=>'填空题',7=>'解答题');
+    public $charToNum = array('A'=>0,'B'=>1,'C'=>2,'D'=>3,'E'=>4,'F'=>5,'G'=>6,'H'=>7,'I'=>8,'J'=>9,'K'=>10,'L'=>11,'M'=>12,'N'=>13);
+    public function init()
+    {
+        set_time_limit(0);
+        @ini_set('memory_limit', '512M');
+    }
+
+    public function actionIndex()
+    {
+        // 获取curl过来值
+        $wordId = isset($_GET['wid']) ? intval($_GET['wid']) : 0;
+        $schoolId = isset($_GET['sid']) ? intval($_GET['sid']) : 0;
+        if (!$wordId || !$schoolId) {
+            exit('word或学校ID异常');
+        }
+        
+        // 连接业务库
+//        $busDsn = 'mysql:host=' . Yii::app()->params["businessDb"]['addr'] . ';dbname=' . Yii::app()->params["default_db"]['name'] . ';';
+//        $busDbh = new PDO($busDsn, Yii::app()->params["default_server"]['username'], Yii::app()->params["default_server"]['password'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8";'));
+        $busDbh = Yii::app()->businessDb;
+        $getDataBase = $busDbh->query('SELECT * FROM `database` WHERE `school_id`=' . $schoolId);
+        $dataBaseInfo = $getDataBase->fetch(PDO::FETCH_ASSOC);
+        if (empty($dataBaseInfo)) {
+            exit('未找到数据库链接信息!');
+        }
+
+        // 连接学校库
+        $busDbh = null;
+        $schDsn = 'mysql:host=' . $dataBaseInfo['database_host'] . ';dbname=' . $dataBaseInfo['database_name'] . ';';
+        $schDbh = new PDO($schDsn, $dataBaseInfo['database_user'], $dataBaseInfo['database_password'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8";'));
+        $wordInfo = $schDbh->query('SELECT `word_id`,`word_name`,`subject_id`,`uploader_id`,`type_id`,`exam_group_id` FROM `topic_word` WHERE `word_id`=' . $wordId)->fetch(PDO::FETCH_ASSOC);
+        if (empty($wordInfo)) {
+            exit('未找到上传word信息!');
+        }
+
+        $parseJson = file_get_contents('php://input');
+        $result = json_decode($parseJson, true);
+        if (empty($result) || $result['errcode'] > 0) { // 解析失败
+            $stmt = $schDbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+            $stmt->execute(array(':wid' => $wordId, ':reason' => $result['errmsg'], ':content' => $parseJson, ':time' => time()));
+            exit('解析失败!');
+        } else {
+            if ($result['callback_type'] == 1) { // 表示人工智能解析完成,更新当前试卷为可预览状态
+                $sctmt = $schDbh->prepare('UPDATE `topic_word` SET `status` = 5,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                $sctmt->execute(array(':wid' => $wordId, ':time' => time(), ':content' => $parseJson));
+                exit('更新试卷解析完成状态成功');
+            } elseif ($result['callback_type'] == 2) { // 试卷解析确认完成,返回试题结构处理
+
+                // 验证试题内容是否为空
+                if (empty($result['items'])) {
+                    $stmt = $schDbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                    $stmt->execute(array(':wid' => $wordId, ':reason' => '返回word试题内容为空', ':content' => $parseJson, ':time' => time()));
+                    exit('返回试题内容为空');
+                } else {
+                    $sctmt = $schDbh->prepare('UPDATE `topic_word` SET `content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                    $sctmt->execute(array(':wid' => $wordId, ':time' => time(), ':content' => $parseJson));
+                }
+
+                // 处理各个端口上传的试题解析
+                if ($wordInfo['exam_group_id']) { // 助教端第三方试卷解析
+                    if ($wordInfo['subject_id'] == 8) { // 高中英语解析单独处理
+                            self::thirdpartyEnglish($schDbh, $result['items'], $wordInfo,$schoolId);
+                    } else {
+                            self::thirdpartyPaper($schDbh, $result['items'], $wordInfo,$schoolId);
+                    }
+                }
+            } else {
+                exit('解析请求异常,请指定合法的callback_type类型');
+            }
+
+            // 处理完
+            $resu = $schDbh->prepare('UPDATE `topic_word` SET `status` = 2,`parse_time`=:time WHERE `word_id` =:wid');
+            $resu->execute(array(':wid' => $wordId, ':time' => time()));
+
+            // 插入解析时间记录
+            $resPro = $schDbh->prepare("INSERT INTO `exam_process` (`exam_group_id`, `action_type`, `action_time`) VALUES (:exam_group_id, :tempType, :time)");
+            $resPro->execute(array(':exam_group_id' => $wordInfo['exam_group_id'], ':tempType' => 4, ':time' => time()));
+
+            $schDbh = null;
+            exit('解析完成!');
+        }
+    }
+ 
+    /**
+     * 第三方试卷试题解析
+     * @param $topics 
+     * @return string
+     */
+    public function thirdpartyPaper($schDbh, $topics, $word,$schoolId)
+    {   
+        $apiTopics = array();
+        $errorMsg = null;
+        $apiParam = Yii::app()->params['api'][0];
+        $apiParam['prefix'] .= 'topic_clear_redis/ctopic';
+        $mathSubject = Yii::app()->params['math_subjects'];
+		$topicDiffculty = array('超易'=>1,'易'=>2,'中档偏易'=>3,'中档偏难'=>4,'难'=>5,'超难'=>6);
+
+        // 获取试卷试题并做相关验证等
+        $paperTopics = $schDbh->query('select pt.topic_id,pt.type,pp.paper_id from paper_topic_relation pt JOIN (select p.paper_id from exam e left JOIN paper p on e.exam_id = p.exam_id where e.exam_group_id = ' . $word['exam_group_id'] . ' GROUP BY e.exam_group_id) as pp on pt.paper_id = pp.paper_id order by pt.order asc')->fetchAll(PDO::FETCH_ASSOC);
+        if (empty($paperTopics)) {
+            $errorMsg = '未找到考试试题';
+        } elseif (count($paperTopics) != count($topics)) {
+            $errorMsg = 'WORD题量与试卷题量不同';
+        }
+
+        if ($errorMsg) {
+            $stmt = $schDbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,parse_time=:time WHERE `word_id` =:wid');
+            $stmt->execute(array(':wid' => $word['word_id'], ':reason' => $errorMsg, ':time' => time()));
+            exit($errorMsg);
+        }
+
+        // 删除试题缓存
+        $tempTopicIds = array();
+        foreach ($paperTopics as $tempTopic) {
+                $tempTopicIds[] = $tempTopic['topic_id'];
+        }
+        if ($tempTopicIds) {
+                self::getApiData($apiParam, 2, json_encode(array('topicIds' => $tempTopicIds)), 3);
+        }
+
+        // 更新试题操作
+        foreach($topics as $key => $item) {
+            $topicId = $paperTopics[$key]['topic_id'];
+            $apiTopics[] = $topicId;
+			$bankType = (int)$item['topic_type_id'];
+			$diffName = isset($item['difficulty']) ? $item['difficulty'] : '中档偏易';
+			$difficulty = isset($topicDiffculty[$diffName]) ? $topicDiffculty[$diffName] : 3;
+
+            // 对高中数学与全学科题型及选项设置不同处理
+			$optionsRank = isset($item['options_rank']) ? (int)$item['options_rank'] : 1;
+            //if (in_array($word['subject_id'], $mathSubject)) {
+            //    $optionsRank = $item['options_rank'] - 1;
+            //} else {
+            //    $optionsRank = isset($item['options_rank']) ? (int)$item['options_rank'] : 1;
+            //}
+
+            try {
+                $schDbh->beginTransaction(); // 开启事务
+
+                // topic表
+                $exeTopic = $schDbh->prepare('UPDATE `topic` SET `topic_title` = :topic_title,`topic_difficulty` = :topic_difficulty,`source_title`=:source_title,`bank_type`=:bank_type,`parse_content`=:parse_content,`update_time`=:update_time WHERE `topic_id` =:topic_id');
+                $exeTopic->execute(array(':topic_id' => $topicId, ':topic_title' => $item['stem'],':topic_difficulty'=>$difficulty,':bank_type'=>$bankType, ':source_title' => 'word上传试题', ':parse_content' => $item['parse'], ':update_time' => time()));
+
+                // topic_item
+                $exeItem = $schDbh->prepare('UPDATE `topic_item` SET `topic_title` = :topic_title WHERE `topic_id` =:topic_id');
+                $exeItem->execute(array(':topic_id' => $topicId, ':topic_title' => $item['stem']));
+                
+                // 选项及答案处理
+                $exeOption = $schDbh->prepare('delete from `topic_item_option` WHERE `topic_id` =:topic_id');
+                $exeOption->execute(array(':topic_id' => $topicId));
+
+                // 选择题选项处理
+                if (isset($item['options']) && $item['options']) { // 含有选项的试题
+                    $optionKeys = array();
+                    foreach ($this->charToNum as $char => $num) {
+                        if (strpos($item['key'], $char) !== false) {
+                            $optionKeys[] = $char;
+                        }
+                    }
+
+                    $correct = 'A';
+                    $rowThr = $schDbh->prepare('INSERT INTO `topic_item_option`(`topic_id`, `option_content`, `option_correct`,`sort_order`) VALUES (:tpid,:content,:correct,:sort_order)');
+                    foreach ($item['options'] as $vk => $option) {
+                        $isTrue = in_array($correct, $optionKeys) ? 1 : 0;
+                        $getRowThr = $rowThr->execute(array(':tpid'=>$topicId,':content'=>$option,':correct'=>$isTrue,':sort_order'=>$vk));
+                        ++$correct;
+                    }
+                } else {
+                    $rowFiv = $schDbh->prepare('INSERT INTO `topic_item_option`(`topic_id`, `option_content`) VALUES (:tpid,:content)');
+                    if (is_array($item['key']) && $item['key']) {
+                        foreach ($item['key'] as $topicKey) {
+                            $getRowFiv = $rowFiv->execute(array(':tpid' => $topicId, ':content' => $topicKey));
+                        }
+                    } else {
+                        $getRowFiv = $rowFiv->execute(array(':tpid' => $topicId, ':content' => $item['key']));
+                        if (!$getRowFiv) {
+                            throw new PDOException('插入topic_item_option表失败!');
+                        }
+                    }
+                }
+
+                // 组卷完成标识
+                $resu = $schDbh->prepare('UPDATE `exam_group` SET `is_answersheet` = 1 WHERE `exam_group_id` =:exam_group_id');
+                $exeSheet = $resu->execute(array(':exam_group_id' => $word['exam_group_id']));
+                if (!$exeSheet) {
+                    throw new PDOException('更新exam_group表失败!');
+                }
+
+                // word与试题关系
+                $rowFor = $schDbh->prepare('INSERT INTO `word_topic_relation`(`word_id`, `topic_id`) VALUES (:wid,:toid)');
+                $getRowFor = $rowFor->execute(array(':wid' => $word['word_id'], ':toid' => $topicId));
+                if (!$getRowFor) {
+                    throw new PDOException('插入word_to_topic表失败!');
+                }
+
+                $schDbh->commit();
+            } catch (PDOException $e) {
+                $schDbh->rollback();
+                $exeReason = $schDbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,parse_time=:time WHERE `word_id` =:wid');
+                $exeReason->execute(array(':wid' => $word['word_id'], ':reason' => $e->getMessage(), ':time' => time()));
+                exit($e->getMessage());
+            }
+        }
+        if($apiTopics){
+            //调用试题检索接口
+            $this->searchTopics($apiTopics,$schoolId);
+        }
+    }
+
+    // 第三方英语新解析处理
+    public function thirdpartyEnglish($schDbh, $topics, $word,$schoolId)
+    {
+        $errorMsg = null;
+        $apiParam = Yii::app()->params['api'][0];
+        $mathSubject = Yii::app()->params['math_subjects'];
+        $topicDiffculty = array('超易'=>1,'易'=>2,'中档偏易'=>3,'中档偏难'=>4,'难'=>5,'超难'=>6,);
+
+        // 获取全学科英语题型
+        $basicType = array();
+        $topicTypeConfig = array();
+        $topicTypeJson = self::getApiData(array(
+                'username' => $apiParam['username'],
+                'password' => $apiParam['password'],
+                'prefix' => $apiParam['prefix'] . 'all_subject/topic_type/subjectId/' . $word['subject_id']
+        ), 1, '', 3);
+        $topicTypeRes = json_decode($topicTypeJson, true);
+        if (isset($topicTypeRes['status']) && $topicTypeRes['status'] == 1 && $topicTypeRes['data']) {
+                foreach ($topicTypeRes['data'] as $topicType) {
+                        $basicType[$topicType['topic_type_id']] = $topicType['btt_id'];
+                        $topicTypeConfig[$topicType['topic_type_id']] = $topicType;
+                }
+                unset($topicTypeJson,$topicTypeRes);
+        }
+
+        // 获取试卷试题并做相关验证等
+        $paperTopics = $schDbh->query('select pt.topic_id,pt.stem_id,pt.paper_id from paper_topic_relation pt JOIN (select p.paper_id from exam e left JOIN paper p on e.exam_id = p.exam_id where e.exam_group_id = ' . $word['exam_group_id'] . ' GROUP BY e.exam_group_id) as pp on pt.paper_id = pp.paper_id order by pt.order asc')->fetchAll(PDO::FETCH_ASSOC);
+        if (empty($paperTopics)) {
+            $stmt = $schDbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,parse_time=:time WHERE `word_id` =:wid');
+            $stmt->execute(array(':wid' => $word['word_id'], ':reason' => '未找到考试试题', ':time' => time()));
+            exit('未找到考试试题');
+        }
+
+        $paperId = 0;
+        $stemTopicIds = array();
+        //$packItemRelate = array();
+        foreach ($paperTopics as $paperTopic) {
+                $paperId = $paperTopic['paper_id'];
+                $stemTopicIds[] = $paperTopic['topic_id'];
+                //$packItemRelate[$paperTopic['topic_id']] = $paperTopic['stem_id'];
+        }
+
+        // 更新试题内容
+        foreach ($topics as $topic) {
+                    $slaveNum = isset($topic['slave']) && $topic['slave'] ? count($topic['slave']) : 0;
+                    $diffName = isset($topic['difficulty']) ? $topic['difficulty'] : '中';
+                    $difficulty = isset($topicDiffculty[$diffName]) ? $topicDiffculty[$diffName] : 3;
+                    $answerType = isset($topic['answer_type']) && $topic['answer_type'] ? (int)$topic['answer_type'] : 0;
+                    $basicTypeId = isset($basicType[$topic['topic_type_id']]) ? $basicType[$topic['topic_type_id']] : 0;
+                    try {
+                            // 判断并处理当前题目是否含有大小题
+                            //$schDbh->beginTransaction();
+                            if ($slaveNum > 0) {
+                                    $slaveTopicIds = array_splice($stemTopicIds, 0, $slaveNum);
+                                    if (empty($slaveTopicIds)) continue;
+
+                                    $largeTopicId = self::insertLargeTopic($schDbh, $slaveTopicIds, array(
+                                            'title' => $topic['content'],
+                                            'analysis' => $topic['parse'],
+                                            'answer_type' => $answerType,
+                                            'word_id' => $word['word_id'],
+                                            'exam_group_id' => $word['exam_group_id'],
+                                            'difficulty' => $difficulty,
+                                            'bank_type' => $topic['topic_type_id'],
+                                            'type_id' => $basicTypeId
+                                    ));
+
+                                    // 更新小题试题内容
+                                    foreach ($topic['slave'] as $skey => $slaveTopic) {
+                                            if (!isset($slaveTopicIds[$skey])) continue;
+                                            $tempSlaveTopicId = $slaveTopicIds[$skey];
+                                            $parse = isset($slaveTopic['parse']) ? $slaveTopic['parse'] : '';
+                                            $slaveAnswerType = isset($slaveTopic['answer_type']) ? (int)$slaveTopic['answer_type'] : 0;
+                                            $slaveTitle = isset($slaveTopic['content']) ? $slaveTopic['content'] : '';
+                                            $slaveOption = isset($slaveTopic['options']) && $slaveTopic['options'] ? $slaveTopic['options'] : '';
+
+                                            // 特殊处理七选五等题型选项问题
+                                            if ($basicTypeId == 2 && empty($slaveOption)) {
+                                                    if (isset($topicTypeConfig[$topic['topic_type_id']]['config']['general_setting']['slave_setting'])) {
+                                                            $slaveConfig = $topicTypeConfig[$topic['topic_type_id']]['config']['general_setting']['slave_setting'];
+                                                            $optionFixation = isset($slaveConfig['option_number']['fixation'])?$slaveConfig['option_number']['fixation']:array();
+                                                            if (isset($optionFixation['is_checked']) && $optionFixation['is_checked'] && isset( $optionFixation['number']) &&  $optionFixation['number']) {
+                                                                    $letter = 'A';
+                                                                    for ($i=0; $i<$optionFixation['number']; $i++){
+                                                                            $slaveOption[] = array('option' => $letter, 'content' => '');
+                                                                            ++$letter;
+                                                                    }
+                                                            }
+                                                    }
+                                            }
+
+                                            self::updateTopicInfo($schDbh, array(
+                                                    'topic_id' => $tempSlaveTopicId,
+                                                    'parse' => $parse,
+                                                    'answer_type' => $slaveAnswerType,
+                                                    'title' => $slaveTitle,
+                                                    'difficulty' => $difficulty,
+                                                    'bank_type' => $topic['topic_type_id'],
+                                                    'type_id' => $basicTypeId,
+                                                    'options' => $slaveOption,
+                                                    'answer' => isset($slaveTopic['answer']) ? $slaveTopic['answer'] : array()
+                                            ));
+                                    }
+                            } else {
+                                    $spliceTopicIds = array_splice($stemTopicIds, 0, 1);
+                                    if (!isset($spliceTopicIds[0])) continue;
+                                    $topicId = $spliceTopicIds[0];
+                                    self::updateTopicInfo($schDbh, array(
+                                            'topic_id' => $topicId,
+                                            'parse' => isset($topic['parse']) ? $topic['parse'] : '',
+                                            'answer_type' => $answerType,
+                                            'title' => isset($topic['content']) ? $topic['content'] : '',
+                                            'difficulty' => $difficulty,
+                                            'bank_type' => $topic['topic_type_id'],
+                                            'type_id' => $basicTypeId,
+                                            'options' => isset($topic['options']) && $topic['options'] ? $topic['options'] : '',
+                                            'answer' => isset($topic['answer']) ? $topic['answer'] : array()
+                                    ));
+
+                                    // 大题对应大题id更新
+                                    $schDbh->prepare("UPDATE `paper_topic_relation` SET `logic_type` = {$topic['topic_type_id']} WHERE `topic_id` = '{$topicId}'")->execute();
+                            }
+
+                            //$schDbh->commit();
+                    } catch (PDOException $e) {
+                            //$schDbh->rollback();
+            $exeReason = $schDbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,parse_time=:time WHERE `word_id` =:wid');
+            $exeReason->execute(array(':wid' => $word['word_id'], ':reason' => $e->getMessage(), ':time' => time()));
+            exit($e->getMessage());
+                    }
+            }
+
+        // 获取试卷的大题信息
+        $paperLargeTopic = $schDbh->query('SELECT `stem_id`,`topic_id`,`logic_type`,`order` FROM `paper_topic_relation` pt WHERE pt.`paper_id`="'.$paperId.'" order by pt.order asc')->fetchAll(PDO::FETCH_ASSOC);
+        if ($paperLargeTopic) {
+                $largerRelate = array();
+                $largeTopicInfo = array();
+                $taskCheckTopics = array();
+                $paperLargeTopicIds = array();
+                foreach ($paperLargeTopic as $ptlInfo) {
+                        $paperLargeTopicIds[] = $ptlInfo['stem_id'];
+                        $largerRelate[$ptlInfo['topic_id']] = $ptlInfo['stem_id'];
+                        if (!isset($largeTopicInfo[$ptlInfo['stem_id']])) {
+                                $largeTopicInfo[$ptlInfo['stem_id']] = array(
+                                        'stem_id' => $ptlInfo['stem_id'],
+                                        'logic_type' => $ptlInfo['logic_type'],
+                                        'order' => $ptlInfo['order']
+                                );
+                                $taskCheckTopics[] = array('topic_id' => $ptlInfo['stem_id'], 'topic_type_id' => $ptlInfo['logic_type']);
+                        }
+                }
+
+                // 如果是全学科题库标注任务推送给题库
+                $zsyapiParam = Yii::app()->params['api'][1];
+                $zsyapiParam['prefix'] .= 'task_exam/check_topic';
+                self::getApiData($zsyapiParam, 2, json_encode(array('examGroupId' => $word['exam_group_id'], 'topics' => $taskCheckTopics)), 5);
+
+                // 更新试卷大题关联表
+                $examInfo = array();
+                $paperLargeSql = 'INSERT INTO `paper_topic_large` (`paper_id`, `large_topic_id`, `topic_no`, `logic_type`) VALUES ';
+                $papers = $schDbh->query('select p.paper_id,e.exam_id,e.tpl_data from exam e left JOIN paper p on e.exam_id = p.exam_id where e.exam_group_id = ' . $word['exam_group_id'])->fetchAll(PDO::FETCH_ASSOC);
+                foreach ($papers as $paper) {
+                        $examInfo[] = array('exam_id' => $paper['exam_id'], 'tpl_data' => $paper['tpl_data']);
+                        $exsitNum = $schDbh->query("SELECT count(*) as num FROM `paper_topic_large` WHERE `paper_id`='{$paper['paper_id']}'")->fetch(PDO::FETCH_ASSOC);
+                        if ($exsitNum['num'] > 0) continue;
+
+                        $paperLargeVal = array();
+                        foreach ($largeTopicInfo as $plTopic) {
+                                $paperLargeVal[] = "('{$paper['paper_id']}', '{$plTopic['stem_id']}', '{$plTopic['order']}', '{$plTopic['logic_type']}')";
+                        }
+                        $schDbh->prepare($paperLargeSql . implode(',', $paperLargeVal))->execute();
+                }
+
+                // 更新tpl_data new_items大小题关系及题型
+                $packTopicBasic = array();
+                $paperLargeTopicIdStr = implode(',', array_unique($paperLargeTopicIds));
+                $topicBasic = $schDbh->query('SELECT `topic_id`,`topic_type`,`bank_type` FROM `topic` WHERE `topic_id` in ('.$paperLargeTopicIdStr.')')->fetchAll(PDO::FETCH_ASSOC);
+                foreach ($topicBasic as $loopBasic) {
+                        $packTopicBasic[$loopBasic['topic_id']] = $loopBasic;
+                }
+
+                foreach ($examInfo as $tempExam) {
+                        $tplArr = json_decode($tempExam['tpl_data'], true);
+                        if ($tplArr && isset($tplArr['new_items']) && $tplArr['new_items']) {
+                                foreach ($tplArr['new_items'] as &$loopNewItem) {
+                                        if (isset($loopNewItem['topicId'])) {
+                                                $tplTopicId = (string)$loopNewItem['topicId'];
+                                                if (isset($largerRelate[$tplTopicId]) && $largerRelate[$tplTopicId] != $loopNewItem['stemId']) {
+                                                        $loopNewItem['stemAlias'] = '';
+                                                        $loopNewItem['stemId'] = $largerRelate[$tplTopicId];
+                                                }
+                                        }
+                                        if (isset($loopNewItem['stemId'])) {
+                                                $tplStemId = (string)$loopNewItem['stemId'];
+                                                if (isset($packTopicBasic[$loopNewItem['stemId']])) {
+                                                        $loopNewItem['topic_type'] = $packTopicBasic[$loopNewItem['stemId']]['bank_type'];
+                                                        // $loopNewItem['basicTopicType'] = $packTopicBasic[$loopNewItem['stemId']]['topic_type'];
+                                                }
+                                        }
+                                }
+                                $tplData = self::jsonEncode($tplArr);
+                                $schDbh->prepare("UPDATE `exam` SET `tpl_data` ='{$tplData}' WHERE `exam_id` ='{$tempExam['exam_id']}'")->execute();
+                        }
+                }
+
+                // 删除试题缓存
+                self::getApiData(array(
+                        'username' => $apiParam['username'],
+                        'password' => $apiParam['password'],
+                        'prefix' => $apiParam['prefix'] . 'topic_clear_redis/ctopic'
+                ), 2, json_encode(array('topicIds' => array_keys($largeTopicInfo))), 3);
+                //调用试题检索接口
+                $this->searchTopics(array_keys($largeTopicInfo),$schoolId);
+        }
+
+        // 组卷完成标识
+        $resu = $schDbh->prepare('UPDATE `exam_group` SET `is_answersheet` = 1 WHERE `exam_group_id` =:exam_group_id');
+        $exeSheet = $resu->execute(array(':exam_group_id' => $word['exam_group_id']));
+        if (!$exeSheet) {
+            $stmt = $schDbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,parse_time=:time WHERE `word_id` =:wid');
+            $stmt->execute(array(':wid' => $word['word_id'], ':reason' => '更新exam_group表失败!', ':time' => time()));
+            exit('更新exam_group表失败!');
+        }
+    }
+
+	// 更新试题内容
+	private static function updateTopicInfo($schDbh, $topic)
+	{
+		// topic
+		$exeTopic = $schDbh->prepare('UPDATE `topic` SET `topic_title` = :topic_title,`topic_difficulty` = :topic_difficulty,`source_title`=:source_title,`bank_type`=:bank_type,`parse_content`=:parse_content,`update_time`=:update_time,`answer_type`=:answer_type,`topic_type`=:topic_type WHERE `topic_id` =:topic_id');
+		$exeTopic->execute(array(':topic_id' => $topic['topic_id'], ':topic_title' => $topic['title'],':topic_difficulty'=>$topic['difficulty'],':bank_type'=>$topic['bank_type'], ':source_title' => 'word上传试题', ':parse_content' => $topic['parse'], ':update_time' => time(), ':answer_type'=>$topic['answer_type'], ':topic_type'=>$topic['type_id']));
+
+		$slaItem = $schDbh->prepare('UPDATE `topic_item` SET `topic_title` = :topic_title WHERE `topic_id` =:topic_id');
+		$slaItem->execute(array(':topic_id' => $topic['topic_id'], ':topic_title' => $topic['title']));
+
+		// topic_item_option
+		if (isset($topic['options']) && $topic['options']) { // 含有选项的试题
+			$slaOption = $schDbh->prepare('delete from `topic_item_option` WHERE `topic_id` =:topic_id');
+			$slaOption->execute(array(':topic_id' => $topic['topic_id']));
+
+			$tempAnswer = isset($topic['answer']) ? $topic['answer'] : array();
+			$rowThr = $schDbh->prepare('INSERT INTO `topic_item_option`(`topic_id`, `option_content`, `option_correct`,`sort_order`) VALUES (:tpid,:content,:correct,:sort_order)');
+			foreach ($topic['options'] as $svk => $seOption) {
+				$isslaTrue = in_array($seOption['option'], $tempAnswer) ? 1 : 0;
+				$rowThr->execute(array(':tpid'=>$topic['topic_id'],':content'=>$seOption['content'],':correct'=>$isslaTrue,':sort_order'=>$svk));
+			}
+		} elseif (isset($topic['answer']) && $topic['answer']) {
+			$slaOption = $schDbh->prepare('delete from `topic_item_option` WHERE `topic_id` =:topic_id');
+			$slaOption->execute(array(':topic_id' => $topic['topic_id']));
+
+			$slaFiv = $schDbh->prepare('INSERT INTO `topic_item_option`(`topic_id`, `option_content`) VALUES (:tpid,:content)');
+			foreach ($topic['answer'] as $vk => $slaAnswer) {
+				$slaFiv->execute(array(':tpid'=>$topic['topic_id'],':content'=>$slaAnswer));
+			}
+		}
+		return true;
+	}
+
+	// 新增大题并更新相关信息
+	private static function insertLargeTopic($schDbh, $slaveTopic, $topic)
+	{
+		// 获取文件夹id
+		$defaultFolder = $schDbh->query('SELECT `folder_id` FROM `topic_folder` WHERE `subject_id`=8 and `is_system`=1')->fetch(PDO::FETCH_ASSOC);
+        $folderId = empty($defaultFolder) ? 0 : $defaultFolder['folder_id'];
+
+		// 获取组卷教师id
+		$groupInfo = $schDbh->query("SELECT `teacher_id` FROM `exam_group` WHERE `exam_group_id`='{$topic['exam_group_id']}'")->fetch(PDO::FETCH_ASSOC);
+        $teacherId = empty($groupInfo) ? 0 : $groupInfo['teacher_id'];
+
+        // 创建大题
+		$largeRow = $schDbh->prepare('INSERT INTO `topic`(`topic_type`, `topic_difficulty`, `folder_id`, `subject_id`,`source_title`, `parse_content`, `creator_id`,`updater_id`, `create_time`,`update_time`,`is_word_topic`,`answer_type`,`bank_type`) VALUES (:ttype,:diff,:fid,:sid,:sotitle,:ana,:ceid,:upid,:time,:utime,1,:answer_type,:bank_type)');
+		$largeRow->execute(array(':ttype' => $topic['type_id'], ':diff' => $topic['difficulty'], ':fid' => $folderId, ':sid' => 8, ':sotitle' => 'word上传试题', ':ana' => $topic['analysis'], ':ceid' => $teacherId, ':upid' => $teacherId, ':time' => time(), ':utime' => time(), ':answer_type'=>$topic['answer_type'], ':bank_type'=>$topic['bank_type']));
+		
+		$largeTopicId = $schDbh->lastInsertId();
+		if (!$largeTopicId) {
+			throw new PDOException('新增大题信息异常!');
+		}
+		
+		// 更新大题相关表
+		$tempSlaveTopicStr = implode(',', $slaveTopic);
+		$tRelate = $schDbh->prepare("UPDATE `topic` SET `stem_id` = {$largeTopicId} WHERE `topic_id` in ({$tempSlaveTopicStr})");
+		$tRelate->execute();
+
+		$ptRelate = $schDbh->prepare("UPDATE `paper_topic_relation` SET `stem_id`={$largeTopicId},`logic_type`={$topic['bank_type']} WHERE `topic_id` in ({$tempSlaveTopicStr})");
+		$ptRelate->execute();
+
+		// 插入解析时间记录
+		$tsInsert = $schDbh->prepare("INSERT INTO `topic_stem` (`stem_id`, `topic_ids`, `stem_content`, `subject_id`) VALUES (:stem_id, :topic_ids, :stem_content, :subject_id)");
+		$tsInsert->execute(array(':stem_id' => $largeTopicId, ':topic_ids' => $tempSlaveTopicStr, ':stem_content' => $topic['title'], ':subject_id' => 8));
+
+		// word与试题关系
+        $rowFor = $schDbh->prepare('INSERT INTO `word_topic_relation`(`word_id`, `topic_id`) VALUES (:wid,:toid)');
+        $rowFor->execute(array(':wid' => $topic['word_id'], ':toid' => $largeTopicId));
+		return true;
+	}
+
+	private static function getApiData($apiParam, $flag = 1, $data, $timeOut = 0,$extraHeaders = array())
+    {
+        $result = FALSE;
+        $ch = @curl_init();
+        if ($ch) {
+            $headers = array(
+                'Content-Type: application/json',
+                'Content-Length: ' . strlen($data),
+            );
+            if($extraHeaders){
+                $headers = array_merge($headers,$extraHeaders);
+            }
+            // Digest认证
+            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
+            curl_setopt($ch, CURLOPT_USERPWD, $apiParam['username'] . ':' . $apiParam['password']);
+
+            // 不输出头部
+            curl_setopt($ch, CURLOPT_HEADER, 0);
+            if ($timeOut) {
+                curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
+                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
+            }
+            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+
+            // curl_exec 获取到的内容不直接输出, 而是返回
+            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+
+            // 请求重启路由器的地址 传参 进行重启
+            curl_setopt($ch, CURLOPT_URL, $apiParam['prefix']);
+
+            curl_setopt($ch, CURLOPT_USERAGENT, 'Api Client/1.0.0 (chengfei@liancaitech.com)');
+            if ($flag == 2) {
+                curl_setopt($ch, CURLOPT_POST, 1);
+                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+            }
+
+            $result = curl_exec($ch);
+            if (curl_errno($ch)) {
+                return 'curl_errno:' . curl_errno($ch);
+            }
+
+            // 释放资源
+            curl_close($ch);
+        }
+        return $result;
+    }
+
+	// json中文处理
+	private static function jsonEncode($arr)
+	{
+		$jsonSupport = version_compare(PHP_VERSION, '5.4', '>=');
+		if ($jsonSupport) {
+			$result = json_encode($arr, JSON_UNESCAPED_UNICODE);
+		} else {
+			$result = json_encode($arr);
+			$result = preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", $result);
+		}
+		return $result;
+	}
+        
+        //全学科试题调用java检索缓存接口
+        public function searchTopics($topicIds = array(),$schoolId = 0){
+            $apiParam = Yii::app()->params['api'][3];
+            if($apiParam && $topicIds && $schoolId){
+                $url = $apiParam['prefix'].'cgi/teacher/schtk/qxk/school-topic-flush/'.$schoolId;
+                self::getApiData(array(
+                        'username' => $apiParam['username'],
+                        'password' => $apiParam['password'],
+                        'prefix' => $url
+                ), 2, json_encode($topicIds), 3,array('X-Basic-V:2'));
+            }
+        }
+}

+ 1427 - 0
protected/controllers/WordapiController.php

@@ -0,0 +1,1427 @@
+<?php
+header("Content-type: text/html; charset=utf-8");
+
+/**
+ * word试题导入接口控制器类
+ * @author jiangfei
+ * @date 2016-03-12 10:30:00
+ * @company 上海风车教育有限公司.
+ */
+class WordapiController extends CController
+{
+    public $ucloud = '';
+    public $webSiteUrl = '';
+    public $charToNum = array('A'=>0,'B'=>1,'C'=>2,'D'=>3,'E'=>4,'F'=>5);
+    public $flag = 1; // 解析返回的图片是否上传ucloud 0否 1是
+    public $mathSubject = array(3,6,51);
+
+    public function init()
+    {
+        @ini_set('memory_limit', '512M');
+        set_time_limit(0);
+        //$this->ucloud = new Ucloud();
+        $this->ucloud = new Qcloud();
+        $this->webSiteUrl = Yii::app()->params['siteurl'];
+        $this->flag = isset($_GET['flag']) ? intval($_GET['flag']) : 1;
+    }
+
+    public function actionIndex()
+    {
+        // 获取curl过来值
+        $word_id = isset($_GET['wid']) ? intval($_GET['wid']) : 0;
+        $school_id = isset($_GET['sid']) ? intval($_GET['sid']) : 0;
+        if (empty($word_id) || empty($school_id)) {
+            exit('未找到word Id或者学校id');
+        }
+        
+        // 连接业务库
+//        $busDsn = 'mysql:host=' . Yii::app()->params["default_server"]['addr'] . ';dbname=' . Yii::app()->params["default_db"]['name'] . ';';
+//        $busdbh = new PDO($busDsn, Yii::app()->params["default_server"]['username'], Yii::app()->params["default_server"]['password'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8";'));
+        $busdbh = Yii::app()->businessDb;
+        $getDataBase = $busdbh->query('SELECT * FROM `database` WHERE `school_id`=' . $school_id);
+        $dataBaseInfo = $getDataBase->fetch(PDO::FETCH_ASSOC);
+        if (empty($dataBaseInfo)) {
+            exit('未找到数据库链接信息!');
+        }
+        $busdbh = null;
+
+        // 连接学校库
+        $schDsn = 'mysql:host=' . $dataBaseInfo['database_host'] . ';dbname=' . $dataBaseInfo['database_name'] . ';';
+        $schdbh = new PDO($schDsn, $dataBaseInfo['database_user'], $dataBaseInfo['database_password'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8";'));
+        $wordInfo = $schdbh->query('SELECT `word_id`,`word_name`,`subject_id`,`uploader_id` FROM `topic_word` WHERE `word_id`=' . $word_id)->fetch(PDO::FETCH_ASSOC);
+        if (empty($wordInfo)) {
+            exit('未找到上传word信息!');
+        }
+
+        $getWordJson = file_get_contents('php://input');
+        $jsonArray = json_decode($getWordJson, true);
+        if (!$jsonArray || $jsonArray['errcode'] > 0) { // 解析失败
+            $docUrl = isset($jsonArray['docurl']) ? $jsonArray['docurl'] : '';
+            $word_down_url = self::downloadWord($wordInfo, $docUrl, $school_id);
+            $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,`file_path` = :path,parse_time=:time WHERE `word_id` =:wid');
+            $stmt->execute(array(':wid' => $word_id, ':reason' => $jsonArray['errmsg'], ':content' => $getWordJson, ':path' => $word_down_url, ':time' => time()));
+            exit('解析失败!');
+        } else {
+            if (empty($jsonArray['items'])) {
+                $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                $stmt->execute(array(':wid' => $word_id, ':reason' => '返回word试题内容为空', ':content' => $getWordJson, ':time' => time()));
+                exit('返回试题内容为空');
+            } else {
+                $sctmt = $schdbh->prepare('UPDATE `topic_word` SET `content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                $sctmt->execute(array(':wid' => $word_id, ':time' => time(), ':content' => $getWordJson));
+            }
+
+            // 试题入库操作
+            foreach ($jsonArray['items'] as $key => $val) {
+
+                // 试题类型ID
+				switch ($val['type']) {
+                    case '选择':
+                        $type_id = 1;
+                        break;
+                    case '多选':
+                        $type_id = 2;
+                        break;
+                    case '填空':
+                        $type_id = 5;
+                        break;
+                    default:
+                        $type_id = 7;
+                }
+
+                //处理答案
+                if (!empty($val['key'])) {
+                    $val['key'] = self::strip_content_tags($val['key']);
+                    $val['key'] = self::downloadImg($val['key'], $school_id);
+                }
+
+                // 处理题干中
+                if (empty($val['stem'])) {
+                    continue;
+                } else {
+                    $val['stem'] = self::strip_content_tags($val['stem']);
+                    $val['stem'] = self::downloadImg($val['stem'], $school_id);
+
+                    // 若是填空题下划线处理
+                    if ($val['type'] == '填空') {
+                        preg_match_all('/_{5,}/', $val['stem'], $matgap);
+                        if (!empty($matgap[0])) {
+                            $nnum = 0;
+                            foreach ($matgap[0] as $km => $vm) {
+                                $nnum = $km + 1;
+                                $val['stem'] = preg_replace('/_{3,}/', '<img class="tiankong" src="/images/list_' . $nnum . '.png">', $val['stem'], 1);
+                            }
+
+                            // 填空题是否多个答案
+                            preg_match_all('/<p>(.*?)<\/p>/', $val['key'], $key_array);
+                            if ($nnum > 1 && $key_array[1]) {
+                                $result_array = array_filter($key_array[1]);
+                                if ($result_array) {
+                                    if (count($result_array) == $nnum) { // 如果填空数与答案数匹配
+                                        $val['key'] = $key_array[1];
+                                    } else { // 出现填空数与答案数不一致情况处理
+                                        $new_array = array();
+                                        $new_nnum = $nnum - 1;
+                                        for ($t = 0; $t <= $new_nnum; $t++) {
+                                            if (isset($result_array[$t])) {
+                                                $new_array[] = $result_array[$t];
+                                            } else {
+                                                $new_array[] = '';
+                                            }
+                                        }
+                                        $val['key'] = $new_array;
+                                    }
+                                }
+                            }
+                        }
+                    }
+                }
+
+                // 试题解析
+                if (!empty($val['analysis'])) {
+                    $val['analysis'] = self::downloadImg($val['analysis'], $school_id);
+                    $val['analysis'] = self::strip_content_tags($val['analysis']);
+                }
+                // 单选题处理
+                if (!empty($val['options'])) {
+                    foreach ($val['options'] as $vk => &$vp) {
+                        $vp = self::downloadImg($vp, $school_id);
+                        $vp = self::strip_content_tags($vp);
+                        // $val['options'][$vk] = $vp;
+                    }
+                }
+
+                // 获取默认文件夹id
+                $subjectId = in_array($wordInfo['subject_id'],$this->mathSubject) ? 3 : $wordInfo['subject_id'];
+                $defaultFolder = $schdbh->query('SELECT `folder_id` FROM `topic_folder` WHERE `subject_id`='.$subjectId.' and `is_system`=1')->fetch(PDO::FETCH_ASSOC);
+                $folderId = empty($defaultFolder) ? 0 : $defaultFolder['folder_id'];
+
+                // 获取试题id
+                //$getUid =   $schdbh->query('SELECT UUID_SHORT() AS uuid')->fetch(PDO::FETCH_ASSOC);
+                //$resUid =   substr($getUid['uuid'],-6);
+
+                $now_time = time();
+                $difficulty = isset($val['difficulty']) ? $val['difficulty'] : 1;
+
+                // 试题入库处理
+                try {
+                    $schdbh->beginTransaction(); // 开启事务
+
+                    // topic表
+                    $row = null;
+                    $row = $schdbh->prepare('INSERT INTO `topic`(`topic_type`, `topic_title`, `topic_difficulty`, `folder_id`, `subject_id`,`source_title`, `parse_content`, `creator_id`,`updater_id`, `create_time`,`update_time`,`is_word_topic`) VALUES (:ttype,:ttile,:tdiff,:fid,:sid,:sotitle,:ana,:ceid,:upid,:time,:utime,1)'); // 执行第一个 SQL
+                    $row->execute(array(':ttype' => $type_id, ':ttile' => $val['stem'], ':tdiff' => $difficulty, ':fid' => $folderId, ':sid' => $wordInfo['subject_id'], ':sotitle' => 'word上传试题', ':ana' => $val['analysis'], ':ceid' => $wordInfo['uploader_id'], ':upid' => $wordInfo['uploader_id'], ':time' => $now_time, ':utime' => $now_time));
+                    $resUid = $schdbh->lastInsertId();
+                    if (!$resUid) {
+                        throw new PDOException('插入topic表失败!');
+                    }
+
+                    // topic_item
+                    $rowTwo = null;
+                    $rowTwo = $schdbh->prepare('INSERT INTO `topic_item`(`topic_id`, `topic_type`, `topic_title`) VALUES (:tpid,:type,:title)');
+                    $getRowTwo = $rowTwo->execute(array(':tpid' => $resUid, ':type' => $type_id, ':title' => $val['stem']));
+                    if (!$getRowTwo) {
+                        throw new PDOException('插入topic_item表失败!');
+                    }
+
+                    // 单选题处理
+                    if ($type_id == 1 || $type_id == 2) {
+
+                        // 获取正确答案
+                        $answerNums = array();
+                        $getAnswer = str_replace(array(" ", " ", "\t", "\n", "\r"), '', strip_tags($val['key']));
+                        $getAnswer = strtoupper($getAnswer);
+                        foreach ($this->charToNum as $char => $num) {
+                            if (strpos($getAnswer, $char) !== false) {
+                                $answerNums[] = $num;
+                            }
+                        }
+
+                        $rowThr = null;
+                        $rowThr = $schdbh->prepare('INSERT INTO `topic_item_option`(`topic_id`, `option_content`, `option_correct`) VALUES (:tpid,:content,:correct)');
+                        foreach ($val['options'] as $vk => $option) {
+                            $is_true = 0;
+                            if (in_array($vk, $answerNums)) {
+                                    $is_true = 1;
+                            }
+                            $getRowThr = $rowThr->execute(array(':tpid' => $resUid, ':content' => $option, ':correct' => $is_true));
+                        }
+                    } else {
+                        $rowFiv = null;
+                        $rowFiv = $schdbh->prepare('INSERT INTO `topic_item_option`(`topic_id`, `option_content`) VALUES (:tpid,:content)');
+                        if (is_array($val['key']) && $val['key']) {
+                            foreach ($val['key'] as $topicKey) {
+                                $getRowFiv = $rowFiv->execute(array(':tpid' => $resUid, ':content' => $topicKey));
+                            }
+                        } else {
+                            $getRowFiv = $rowFiv->execute(array(':tpid' => $resUid, ':content' => $val['key']));
+                            if (!$getRowFiv) {
+                                throw new PDOException('插入topic_item_option表失败!');
+                            }
+                        }
+                    }
+
+                    // word与试题关系
+                    $rowFor = null;
+                    $rowFor = $schdbh->prepare('INSERT INTO `word_topic_relation`(`word_id`, `topic_id`) VALUES (:wid,:toid)');
+                    $getRowFor = $rowFor->execute(array(':wid' => $word_id, ':toid' => $resUid));
+                    if (!$getRowFor) {
+                        throw new PDOException('插入word_to_topic表失败!');
+                    }
+
+                    $schdbh->commit();
+                } catch (PDOException $e) {
+                    $schdbh->rollback(); // 执行失败,事务回滚
+                    exit($e->getMessage());
+                }
+            }
+
+            // 处理完
+            $resu = $schdbh->prepare('UPDATE `topic_word` SET `status` = 2,`parse_time`=:time WHERE `word_id` =:wid');
+            $resu->execute(array(':wid' => $word_id, ':time' => time()));
+
+            $schdbh = null;
+            exit('解析完成!');
+        }
+    }
+
+    public function actionCoach()
+    {
+        $apiParam = Yii::app()->params['api'][0];
+        $apiParam['prefix'] .= 'topic_clear_redis/ctopic';
+        $apiTopics = array();
+        // 获取curl过来值
+        $word_id = isset($_GET['wid']) ? intval($_GET['wid']) : 0;
+        $school_id = isset($_GET['sid']) ? intval($_GET['sid']) : 0;
+        if (empty($word_id) || empty($school_id)) {
+            exit('未找到word Id或者学校id');
+        }
+
+        // 连接业务库
+        $busDsn = 'mysql:host=' . Yii::app()->params["default_server"]['addr'] . ';dbname=' . Yii::app()->params["default_db"]['name'] . ';';
+        $busdbh = new PDO($busDsn, Yii::app()->params["default_server"]['username'], Yii::app()->params["default_server"]['password'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8";'));
+        $getDataBase = $busdbh->query('SELECT * FROM `database` WHERE `school_id`=' . $school_id);
+        $dataBaseInfo = $getDataBase->fetch(PDO::FETCH_ASSOC);
+        if (empty($dataBaseInfo)) {
+            exit('未找到数据库链接信息!');
+        }
+        $busdbh = null;
+        $isQxk = 0;
+        // 连接学校库
+        $schDsn = 'mysql:host=' . $dataBaseInfo['database_host'] . ';dbname=' . $dataBaseInfo['database_name'] . ';';
+        $schdbh = new PDO($schDsn, $dataBaseInfo['database_user'], $dataBaseInfo['database_password'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8";'));
+        $wordInfo = $schdbh->query('SELECT `word_id`,`word_name`,`subject_id`,`uploader_id`,`exam_group_id` FROM `topic_word` WHERE `word_id`=' . $word_id)->fetch(PDO::FETCH_ASSOC);
+        if (empty($wordInfo)) {
+            exit('未找到上传word信息!');
+        }
+        $examGroupInfo = $schdbh->query('SELECT `qxk_paper_id` FROM `exam_group` WHERE `exam_group_id`=' . $wordInfo['exam_group_id'])->fetch(PDO::FETCH_ASSOC);
+        if($examGroupInfo && $examGroupInfo['qxk_paper_id']){
+            $isQxk = 1;
+        }
+        
+        $paper_topic_relation_data = $schdbh->query('select pt.*,pp.* from paper_topic_relation pt join  (select p.paper_id ,e.subject_id as subject_id,e.exam_group_id from exam e left JOIN  paper p on e.exam_id = p.exam_id where e.exam_group_id = ' . $wordInfo['exam_group_id'] . ' GROUP BY e.exam_group_id) as pp on pt.paper_id = pp.paper_id order by pt.type asc,pt.order asc')->fetchAll(PDO::FETCH_ASSOC);
+        if (empty($paper_topic_relation_data)) {
+            $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+            $stmt->execute(array(':wid' => $word_id, ':reason' => '此考试无题', ':content' => '', ':time' => time()));
+
+        }
+		$relate_topic_id = array();
+        $p_topic_type_num = array();
+        foreach ($paper_topic_relation_data as $v) {
+			$relate_topic_id[] = $v['topic_id'];
+            $p_topic_type_num[$v['type']][] = $v['topic_id'];
+        }
+
+        $getWordJson = file_get_contents('php://input');
+        $jsonArray = json_decode($getWordJson, true);
+        if (!$jsonArray || $jsonArray['errcode'] > 0) { // 解析失败
+            $docUrl = isset($jsonArray['docurl']) ? $jsonArray['docurl'] : '';
+            $word_down_url = self::downloadWord($wordInfo, $docUrl, $school_id);
+            $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,`file_path` = :path,parse_time=:time WHERE `word_id` =:wid');
+            $stmt->execute(array(':wid' => $word_id, ':reason' => $jsonArray['errmsg'], ':content' => $getWordJson, ':path' => $word_down_url, ':time' => time()));
+            exit('解析失败!');
+        } else {
+
+            if (empty($jsonArray['items'])) {
+                $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                $stmt->execute(array(':wid' => $word_id, ':reason' => '返回word试题内容为空', ':content' => $getWordJson, ':time' => time()));
+                exit('返回试题内容为空');
+            } else {
+                $sctmt = $schdbh->prepare('UPDATE `topic_word` SET `content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                $sctmt->execute(array(':wid' => $word_id, ':time' => time(), ':content' => $getWordJson));
+
+            }
+
+            if (count($paper_topic_relation_data) != count($jsonArray['items'])) {
+
+                $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                $stmt->execute(array(':wid' => $word_id, ':reason' => 'WORD题量与试卷题量不同', ':content' => $getWordJson, ':time' => time()));
+                exit('WORD题量与试卷题量不同');
+            }
+			
+            // 删除已存在试题缓存
+            if ($relate_topic_id) {
+                    self::getApiData($apiParam, 2, json_encode(array('topicIds' => $relate_topic_id)), 3);
+            }
+
+            $topic_type_num = array();
+            foreach ($jsonArray['items'] as $key => $val) {
+                // 试题类型ID
+                $type_id = 0;
+                if ($val['type'] == '选择') {
+                    $type_id = 1;
+                    $topic_type_num[$type_id][] = $type_id;
+                } else if ($val['type'] == '多选') {
+					$type_id = 2;
+                    $topic_type_num[$type_id][] = $type_id;
+				} else if ($val['type'] == '填空') {
+                    $type_id = 5;
+                    $topic_type_num[$type_id][] = $type_id;
+                } else if ($val['type'] == '简答') {
+					if (isset($val['is_optional']) && $val['is_optional']) {
+						$topic_type_num[17][] = 7;
+					} else {
+						$type_id = 7;
+						$topic_type_num[$type_id][] = $type_id;
+					}
+                }
+            }
+
+            //验证题型题量
+            if ($topic_type_num && $p_topic_type_num) {
+                if (isset($topic_type_num[1]) && isset($p_topic_type_num[1])) {
+                    if (count($topic_type_num[1]) != count($p_topic_type_num[1])) {
+
+                        $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                        $stmt->execute(array(':wid' => $word_id, ':reason' => 'word单选题量与试卷的单选题量不同', ':content' => $getWordJson, ':time' => time()));
+                        exit('word单选题量与试卷的单选题量不同');
+
+                    }
+                } elseif (isset($p_topic_type_num[1]) && !isset($topic_type_num[1])) {
+                    $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                    $stmt->execute(array(':wid' => $word_id, ':reason' => 'word单选题量与试卷的单选题量不同', ':content' => $getWordJson, ':time' => time()));
+                    exit('word单选题量与试卷的单选题量不同');
+                }
+
+				if (isset($topic_type_num[2]) && isset($p_topic_type_num[2])) {
+                    if (count($topic_type_num[2]) != count($p_topic_type_num[2])) {
+
+                        $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                        $stmt->execute(array(':wid' => $word_id, ':reason' => 'word多选题量与试卷的多选题量不同', ':content' => $getWordJson, ':time' => time()));
+                        exit('word多选题量与试卷的多选题量不同');
+
+                    }
+                } elseif (isset($p_topic_type_num[2]) && !isset($topic_type_num[2])) {
+                    $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                    $stmt->execute(array(':wid' => $word_id, ':reason' => 'word多选题量与试卷的多选题量不同', ':content' => $getWordJson, ':time' => time()));
+                    exit('word多选题量与试卷的多选题量不同');
+                }
+
+                if (isset($topic_type_num[5]) && isset($p_topic_type_num[5])) {
+                    if (count($topic_type_num[5]) != count($p_topic_type_num[5])) {
+
+                        $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                        $stmt->execute(array(':wid' => $word_id, ':reason' => 'word填空题量与试卷的填空题量不同', ':content' => $getWordJson, ':time' => time()));
+                        exit('word填空题量与试卷的填空题量不同');
+                    }
+                } elseif (isset($p_topic_type_num[5]) && !isset($topic_type_num[5])) {
+                    $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                    $stmt->execute(array(':wid' => $word_id, ':reason' => 'word填空题量与试卷的填空题量不同', ':content' => $getWordJson, ':time' => time()));
+                    exit('word填空题量与试卷的填空题量不同');
+                }
+                if (isset($topic_type_num[7]) && isset($p_topic_type_num[7])) {
+                    if (count($topic_type_num[7]) != count($p_topic_type_num[7])) {
+
+                        $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                        $stmt->execute(array(':wid' => $word_id, ':reason' => 'word解答题量与试卷的解答题量不同', ':content' => $getWordJson, ':time' => time()));
+                        exit('word解答题量与试卷的解答题量不同');
+                    }
+
+                } elseif (isset($p_topic_type_num[7]) && !isset($topic_type_num[7])) {
+                    $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                    $stmt->execute(array(':wid' => $word_id, ':reason' => 'word解答题量与试卷的解答题量不同', ':content' => $getWordJson, ':time' => time()));
+                    exit('word解答题量与试卷的解答题量不同');
+                }
+
+				if (isset($topic_type_num[17]) && isset($p_topic_type_num[17])) {
+					 if (count($topic_type_num[17]) != count($p_topic_type_num[17])) {
+                        $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                        $stmt->execute(array(':wid' => $word_id, ':reason' => 'word选做题量与试卷的选做题量不同', ':content' => $getWordJson, ':time' => time()));
+                        exit('word选做题量与试卷的选做题量不同');
+                    }
+				} elseif (isset($p_topic_type_num[17]) && !isset($topic_type_num[17])) {
+					$stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                    $stmt->execute(array(':wid' => $word_id, ':reason' => '上传Word需包含选做题', ':content' => $getWordJson, ':time' => time()));
+                    exit('上传Word需包含选做题');
+				}
+            }
+
+
+            // 试题入库操作
+            foreach ($jsonArray['items'] as $key => $val) {
+                $apiTopics[] = $paper_topic_relation_data[$key]['topic_id'];
+                // 试题类型ID
+                switch ($val['type']) {
+                    case '选择':
+                        $type_id = 1;
+                        break;
+                    case '多选':
+                        $type_id = 2;
+                        break;
+                    case '填空':
+                        $type_id = 5;
+                        break;
+                    default:
+                        $type_id = 7;
+                }
+
+                //处理答案
+                if (!empty($val['key'])) {
+                    $val['key'] = self::downloadImg($val['key'], $school_id);
+                    $val['key'] = self::strip_content_tags($val['key']);
+                }
+
+                // 处理题干中的公式
+                if (empty($val['stem'])) {
+                    continue;
+                } else {
+                    $val['stem'] = self::downloadImg($val['stem'], $school_id);
+                    $val['stem'] = self::strip_content_tags($val['stem']);
+
+                    // 若是填空题下划线处理
+                    if ($val['type'] == '填空') {
+                        preg_match_all('/_{5,}/', $val['stem'], $matgap);
+                        if (!empty($matgap[0])) {
+                            $nnum = 0;
+                            foreach ($matgap[0] as $km => $vm) {
+                                $nnum = $km + 1;
+                                $val['stem'] = preg_replace('/_{3,}/', '<img class="tiankong" src="/images/list_' . $nnum . '.png">', $val['stem'], 1);
+                            }
+
+                            // 填空题是否多个答案
+                            preg_match_all('/<p>(.*?)<\/p>/', $val['key'], $key_array);
+                            if ($nnum > 1 && $key_array[1]) {
+                                $result_array = array_filter($key_array[1]);
+                                if ($result_array) {
+                                    if (count($result_array) == $nnum) { // 如果填空数与答案数匹配
+                                        $val['key'] = $key_array[1];
+                                    } else { // 出现填空数与答案数不一致情况处理
+                                        $new_array = array();
+                                        $new_nnum = $nnum - 1;
+                                        for ($t = 0; $t <= $new_nnum; $t++) {
+                                            if (isset($result_array[$t])) {
+                                                $new_array[] = $result_array[$t];
+                                            } else {
+                                                $new_array[] = '';
+                                            }
+                                        }
+                                        $val['key'] = $new_array;
+                                    }
+                                }
+                            }
+                        }
+                    }
+                }
+
+                // 试题解析
+                if (!empty($val['analysis'])) {
+                    $val['analysis'] = self::downloadImg($val['analysis'], $school_id);
+                    $val['analysis'] = self::strip_content_tags($val['analysis']);
+                }
+
+                // 单选题处理
+                if (!empty($val['options'])) {
+                    foreach ($val['options'] as $vk => &$vp) {
+                        $vp = self::downloadImg($vp, $school_id);
+                        $vp = self::strip_content_tags($vp);
+                        // $val['options'][$vk] = $vp;
+                    }
+                }
+
+                // 获取默认文件夹id
+                $defaultFolder = $schdbh->query('SELECT `folder_id` FROM `topic_folder` WHERE `is_system`=1')->fetch(PDO::FETCH_ASSOC);
+                $folderId = empty($defaultFolder['folder_id']) ? 0 : $defaultFolder['folder_id'];
+
+                // 获取试题id
+                //$getUid =   $schdbh->query('SELECT UUID_SHORT() AS uuid')->fetch(PDO::FETCH_ASSOC);
+                //$resUid =   substr($getUid['uuid'],-6);
+
+                // 设置默认难度
+                $difficulty = isset($val['difficulty']) ? $val['difficulty'] : 1;
+
+                // 试题入库处理
+                try {
+                    $schdbh->beginTransaction(); // 开启事务
+
+                    $now_time = time();
+
+                    // topic表
+                    $row = null;
+
+                    $stmt = $schdbh->prepare('UPDATE `topic` SET `topic_title` = :topic_title,`topic_difficulty` = :topic_difficulty,`source_title`=:source_title,`parse_content`=:parse_content,`update_time`=:update_time,`is_word_topic`=:is_word_topic WHERE `topic_id` =:topic_id');
+                    $stmt->execute(array(':topic_id' => $paper_topic_relation_data[$key]['topic_id'], ':topic_title' => $val['stem'], ':topic_difficulty' => $difficulty, ':source_title' => 'word上传试题', ':parse_content' => $val['analysis'], ':update_time' => time(), ':is_word_topic' => 0));
+
+                    // topic_item
+                    $stmt = $schdbh->prepare('UPDATE `topic_item` SET `topic_title` = :topic_title WHERE `topic_id` =:topic_id');
+                    $stmt->execute(array(':topic_id' => $paper_topic_relation_data[$key]['topic_id'], ':topic_title' => $val['stem']));
+
+
+                    // 单选题处理
+                    if ($type_id == 1 || $type_id == 2) {
+
+                        // 获取正确答案
+                        $answerNums = array();
+                        $getAnswer = str_replace(array(" ", " ", "\t", "\n", "\r"), '', strip_tags($val['key']));
+                        $getAnswer = strtoupper($getAnswer);
+                        foreach ($this->charToNum as $char => $num) {
+                            if (strpos($getAnswer, $char) !== false) {
+                                $answerNums[] = $num;
+                            }
+                        }
+                        $topic_option_data = $schdbh->query('SELECT * FROM `topic_item_option` WHERE `topic_id`=' . $paper_topic_relation_data[$key]['topic_id'] . ' and option_correct = 1')->fetch(PDO::FETCH_ASSOC);
+                        if ($topic_option_data) {
+                            if (count($val['options']) < ($topic_option_data['sort_order'] + 1)) {
+                                throw new PDOException('此题选项未包含设置的答案项!');
+                            }
+
+                            $stmt = $schdbh->prepare('delete from  `topic_item_option`  WHERE `topic_id` =:topic_id');
+                            $stmt->execute(array(':topic_id' => $paper_topic_relation_data[$key]['topic_id']));
+                            $rowThr = null;
+                            $rowThr = $schdbh->prepare('INSERT INTO `topic_item_option`(`topic_id`, `option_content`, `option_correct`,`sort_order`) VALUES (:tpid,:content,:correct,:sort_order)');
+
+
+                            foreach ($val['options'] as $vk => $option) {
+                                $is_true = 0;
+                                if ($topic_option_data) {
+                                    if (in_array($vk, $answerNums)) {
+										$is_true = 1;
+									}
+                                }
+
+                                $getRowThr = $rowThr->execute(array(':tpid' => $paper_topic_relation_data[$key]['topic_id'], ':content' => $option, ':correct' => $is_true, ':sort_order' => $vk));
+                            }
+                        } else {
+                            if (count($val['options']) < $anserNum + 1) {
+                                throw new PDOException('此题选项未包含设置的答案项!');
+                            }
+                            $stmt = $schdbh->prepare('delete from  `topic_item_option`  WHERE `topic_id` =:topic_id');
+                            $stmt->execute(array(':topic_id' => $paper_topic_relation_data[$key]['topic_id']));
+                            $rowFiv = null;
+                            $rowThr = $schdbh->prepare('INSERT INTO `topic_item_option`(`topic_id`, `option_content`, `option_correct`,`sort_order`) VALUES (:tpid,:content,:correct,:sort_order)');
+
+                            foreach ($val['options'] as $vk => $option) {
+                                $is_true = 0;
+                                if ($anserNum == $vk) {
+                                    $is_true = 1;
+                                }
+
+                                $getRowThr = $rowThr->execute(array(':tpid' => $paper_topic_relation_data[$key]['topic_id'], ':content' => $option, ':correct' => $is_true, ':sort_order' => $vk));
+                            }
+                        }
+
+
+                    } else {
+                        $stmt = $schdbh->prepare('delete from  `topic_item_option`  WHERE `topic_id` =:topic_id');
+                        $stmt->execute(array(':topic_id' => $paper_topic_relation_data[$key]['topic_id']));
+                        $rowFiv = null;
+                        $rowFiv = $schdbh->prepare('INSERT INTO `topic_item_option`(`topic_id`, `option_content`) VALUES (:tpid,:content)');
+                        if (is_array($val['key']) && $val['key']) {
+                            foreach ($val['key'] as $topicKey) {
+                                $getRowFiv = $rowFiv->execute(array(':tpid' => $paper_topic_relation_data[$key]['topic_id'], ':content' => $topicKey));
+                            }
+                        } else {
+                            $getRowFiv = $rowFiv->execute(array(':tpid' => $paper_topic_relation_data[$key]['topic_id'], ':content' => $val['key']));
+                            if (!$getRowFiv) {
+                                throw new PDOException('插入topic_item_option表失败!');
+                            }
+                        }
+                    }
+
+                    // word与试题关系
+                    $rowFor = null;
+                    $rowFor = $schdbh->prepare('INSERT INTO `word_topic_relation`(`word_id`, `topic_id`) VALUES (:wid,:toid)');
+                    $getRowFor = $rowFor->execute(array(':wid' => $word_id, ':toid' => $paper_topic_relation_data[$key]['topic_id']));
+                    if (!$getRowFor) {
+                        throw new PDOException('插入word_to_topic表失败!');
+                    }
+
+                    $schdbh->commit();
+                } catch (PDOException $e) {
+                    $schdbh->rollback(); // 执行失败,事务回滚
+
+                    $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                    $stmt->execute(array(':wid' => $word_id, ':reason' => $e->getMessage(), ':content' => $getWordJson, ':time' => time()));
+
+                    exit($e->getMessage());
+                }
+
+            }
+
+            // 处理完
+            $resu = $schdbh->prepare('UPDATE `topic_word` SET `status` = 2,`parse_time`=:time WHERE `word_id` =:wid');
+            $resu->execute(array(':wid' => $word_id, ':time' => time()));
+
+            $resu = $schdbh->prepare('UPDATE `exam_group` SET `is_answersheet` = 1 WHERE `exam_group_id` =:exam_group_id');
+            $resu->execute(array(':exam_group_id' => $wordInfo['exam_group_id']));
+
+            // 插入解析时间记录
+            $resPro = $schdbh->prepare("INSERT INTO `exam_process` (`exam_group_id`, `action_type`, `action_time`) VALUES (:exam_group_id, :tempType, :time)");
+            $resPro->execute(array(':exam_group_id' => $wordInfo['exam_group_id'], ':tempType' => 4, ':time' => time()));
+
+            // 监控日志
+            //$teachInfo  = $schdbh->query('SELECT `teacher_name` FROM `teacher` WHERE `teacher_id`="'.$wordInfo['uploader_id'].'"')->fetch(PDO::FETCH_ASSOC);
+            BMonitorLog::model()->addLog(array(
+                'school_id' => $school_id,
+                'teacher_id' => $wordInfo['uploader_id'],
+                'log_content' => array(
+                    '助教',
+                    '上传了',
+                    $wordInfo['word_name'],
+                    '试卷'
+                )
+            ));
+
+            $schdbh = null;
+            if($apiTopics && $isQxk){
+                //调用试题检索接口
+                $this->searchTopics($apiTopics,$school_id);
+            }
+            exit('解析完成!');
+        }
+    }
+
+    /**
+     * @param $string
+     * @return mixed
+     * 校本卷库word解析
+     */
+    public function actionXbpaper()
+    {
+
+        // 获取curl过来值
+        $word_id = isset($_GET['wid']) ? intval($_GET['wid']) : 0;
+        $school_id = isset($_GET['sid']) ? intval($_GET['sid']) : 0;
+        if (empty($word_id) || empty($school_id)) {
+            exit('未找到word Id或者学校id');
+        }
+
+        // 连接业务库
+        $busDsn = 'mysql:host=' . Yii::app()->params["default_server"]['addr'] . ';dbname=' . Yii::app()->params["default_db"]['name'] . ';';
+        $busdbh = new PDO($busDsn, Yii::app()->params["default_server"]['username'], Yii::app()->params["default_server"]['password'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8";'));
+        $getDataBase = $busdbh->query('SELECT * FROM `database` WHERE `school_id`=' . $school_id);
+        $dataBaseInfo = $getDataBase->fetch(PDO::FETCH_ASSOC);
+        if (empty($dataBaseInfo)) {
+            exit('未找到数据库链接信息!');
+        }
+        $busdbh = null;
+
+        // 连接学校库
+        $schDsn = 'mysql:host=' . $dataBaseInfo['database_host'] . ';dbname=' . $dataBaseInfo['database_name'] . ';';
+        $schdbh = new PDO($schDsn, $dataBaseInfo['database_user'], $dataBaseInfo['database_password'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8";'));
+        $wordInfo = $schdbh->query('SELECT `word_id`,`word_name`,`subject_id`,`uploader_id`,`topic_paper_id` FROM `topic_word` WHERE `word_id`=' . $word_id)->fetch(PDO::FETCH_ASSOC);
+        if (empty($wordInfo)) {
+            exit('未找到上传word信息!');
+        }
+
+        $getWordJson = file_get_contents('php://input');
+        $jsonArray = json_decode($getWordJson, true);
+        if (!$jsonArray || $jsonArray['errcode'] > 0) { // 解析失败
+            $docUrl = isset($jsonArray['docurl']) ? $jsonArray['docurl'] : '';
+            $word_down_url = self::downloadWord($wordInfo, $docUrl, $school_id);
+            $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,`file_path` = :path,parse_time=:time WHERE `word_id` =:wid');
+            $stmt->execute(array(':wid' => $word_id, ':reason' => $jsonArray['errmsg'], ':content' => $getWordJson, ':path' => $word_down_url, ':time' => time()));
+            exit('解析失败!');
+        } else {
+
+            if (empty($jsonArray['items'])) {
+                $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                $stmt->execute(array(':wid' => $word_id, ':reason' => '返回word试题内容为空', ':content' => $getWordJson, ':time' => time()));
+                exit('返回试题内容为空');
+            } else {
+                $sctmt = $schdbh->prepare('UPDATE `topic_word` SET `content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                $sctmt->execute(array(':wid' => $word_id, ':time' => time(), ':content' => $getWordJson));
+            }
+
+            // 试题入库操作
+            foreach ($jsonArray['items'] as $key => $val) {
+
+                // 试题类型ID
+                switch ($val['type']) {
+                    case '选择':
+                        $type_id = 1;
+                        break;
+                    case '多选':
+                        $type_id = 2;
+                        break;
+                    case '填空':
+                        $type_id = 5;
+                        break;
+                    default:
+                        $type_id = 7;
+                }
+
+                //处理答案
+                if (!empty($val['key'])) {
+                    $val['key'] = self::downloadImg($val['key'], $school_id);
+                    $val['key'] = self::strip_content_tags($val['key']);
+                }
+
+                // 处理题干中的公式
+                if (empty($val['stem'])) {
+                    continue;
+                } else {
+                    $val['stem'] = self::downloadImg($val['stem'], $school_id);
+                    $val['stem'] = self::strip_content_tags($val['stem']);
+
+                    // 若是填空题下划线处理
+                    if ($val['type'] == '填空') {
+                        preg_match_all('/_{5,}/', $val['stem'], $matgap);
+                        if (!empty($matgap[0])) {
+                            $nnum = 0;
+                            foreach ($matgap[0] as $km => $vm) {
+                                $nnum = $km + 1;
+                                $val['stem'] = preg_replace('/_{3,}/', '<img class="tiankong" src="/images/list_' . $nnum . '.png">', $val['stem'], 1);
+                            }
+
+                            // 填空题是否多个答案
+                            preg_match_all('/<p>(.*?)<\/p>/', $val['key'], $key_array);
+                            if ($nnum > 1 && $key_array[1]) {
+                                $result_array = array_filter($key_array[1]);
+                                if ($result_array) {
+                                    if (count($result_array) == $nnum) { // 如果填空数与答案数匹配
+                                        $val['key'] = $key_array[1];
+                                    } else { // 出现填空数与答案数不一致情况处理
+                                        $new_array = array();
+                                        $new_nnum = $nnum - 1;
+                                        for ($t = 0; $t <= $new_nnum; $t++) {
+                                            if (isset($result_array[$t])) {
+                                                $new_array[] = $result_array[$t];
+                                            } else {
+                                                $new_array[] = '';
+                                            }
+                                        }
+                                        $val['key'] = $new_array;
+                                    }
+                                }
+                            }
+                        }
+                    }
+                }
+
+                // 试题解析
+                if (!empty($val['analysis'])) {
+                    $val['analysis'] = self::downloadImg($val['analysis'], $school_id);
+                    $val['analysis'] = self::strip_content_tags($val['analysis']);
+                }
+
+                // 单选题处理
+                if (!empty($val['options'])) {
+                    foreach ($val['options'] as $vk => &$vp) {
+                        $vp = self::downloadImg($vp, $school_id);
+                        $vp = self::strip_content_tags($vp);
+                        // $val['options'][$vk] = $vp;
+                    }
+                }
+
+                // 获取默认文件夹id
+                $folderId = 0;
+
+                // 获取试题id
+                //$getUid =   $schdbh->query('SELECT UUID_SHORT() AS uuid')->fetch(PDO::FETCH_ASSOC);
+                //$resUid =   substr($getUid['uuid'],-6);
+
+                $now_time = time();
+                $difficulty = isset($val['difficulty']) ? $val['difficulty'] : 1;
+
+                // 试题入库处理
+                try {
+                    $schdbh->beginTransaction(); // 开启事务
+
+                    // topic表 topic_from=1 校本卷库的题
+                    $row = null;
+                    $row = $schdbh->prepare('INSERT INTO `topic`(`topic_type`, `topic_title`, `topic_difficulty`, `folder_id`, `subject_id`,`source_title`, `parse_content`, `creator_id`,`updater_id`, `create_time`,`update_time`,`topic_from`) VALUES (:ttype,:ttile,:tdiff,:fid,:sid,:sotitle,:ana,:ceid,:upid,:time,:utime,1)'); // 执行第一个 SQL
+                    $row->execute(array(':ttype' => $type_id, ':ttile' => $val['stem'], ':tdiff' => $difficulty, ':fid' => $folderId, ':sid' => $wordInfo['subject_id'], ':sotitle' => 'word上传试题', ':ana' => $val['analysis'], ':ceid' => $wordInfo['uploader_id'], ':upid' => $wordInfo['uploader_id'], ':time' => $now_time, ':utime' => $now_time));
+                    $resUid = $schdbh->lastInsertId();
+                    if (!$resUid) {
+                        throw new PDOException('插入topic表失败!');
+                    }
+
+                    //topic_paper_relation
+                    $rowTpr = null;
+                    $rowTpr = $schdbh->prepare('INSERT INTO `topic_paper_relation`(`paper_id`, `topic_id`, `topic_type`, `topic_score`, `order`) VALUES (:paperId,:topicId,:topicType,:topicScore,:order)'); // 执行第一个 SQL
+                    $rowTpr->execute(array(':paperId' => $wordInfo['topic_paper_id'], ':topicId' => $resUid, ':topicType' => $type_id, ':topicScore' => $val['score'], ':order' => $key));
+                    $resTpr = $schdbh->lastInsertId();
+                    if (!$resTpr) {
+                        throw new PDOException('插入topic_paper_relation表失败!');
+                    }
+
+
+                    // topic_item
+                    $rowTwo = null;
+                    $rowTwo = $schdbh->prepare('INSERT INTO `topic_item`(`topic_id`, `topic_type`, `topic_title`) VALUES (:tpid,:type,:title)');
+                    $getRowTwo = $rowTwo->execute(array(':tpid' => $resUid, ':type' => $type_id, ':title' => $val['stem']));
+                    if (!$getRowTwo) {
+                        throw new PDOException('插入topic_item表失败!');
+                    }
+
+                    // 单选题处理
+                    if ($type_id == 1 || $type_id == 2) {
+
+                        // 获取正确答案
+                        $answerNums = array();
+                        $getAnswer = str_replace(array(" ", " ", "\t", "\n", "\r"), '', strip_tags($val['key']));
+                        $getAnswer = strtoupper($getAnswer);
+                        foreach ($this->charToNum as $char => $num) {
+                            if (strpos($getAnswer, $char) !== false) {
+                                $answerNums[] = $num;
+                            }
+                        }
+
+                        $rowThr = null;
+                        $rowThr = $schdbh->prepare('INSERT INTO `topic_item_option`(`topic_id`, `option_content`, `option_correct`,`sort_order`) VALUES (:tpid,:content,:correct,:sort_order)');
+                        foreach ($val['options'] as $vk => $option) {
+                            $is_true = 0;
+                            if (in_array($vk, $answerNums)) {
+								$is_true = 1;
+							}
+                            $getRowThr = $rowThr->execute(array(':tpid' => $resUid, ':content' => $option, ':correct' => $is_true, 'sort_order' => $vk));
+                        }
+                    } else {
+                        $rowFiv = null;
+                        $rowFiv = $schdbh->prepare('INSERT INTO `topic_item_option`(`topic_id`, `option_content`) VALUES (:tpid,:content)');
+                        if (is_array($val['key']) && $val['key']) {
+                            foreach ($val['key'] as $topicKey) {
+                                $getRowFiv = $rowFiv->execute(array(':tpid' => $resUid, ':content' => $topicKey));
+                            }
+                        } else {
+                            $getRowFiv = $rowFiv->execute(array(':tpid' => $resUid, ':content' => $val['key']));
+                            if (!$getRowFiv) {
+                                throw new PDOException('插入topic_item_option表失败!');
+                            }
+                        }
+                    }
+
+                    // word与试题关系
+                    $rowFor = null;
+                    $rowFor = $schdbh->prepare('INSERT INTO `word_topic_relation`(`word_id`, `topic_id`) VALUES (:wid,:toid)');
+                    $getRowFor = $rowFor->execute(array(':wid' => $word_id, ':toid' => $resUid));
+                    if (!$getRowFor) {
+                        throw new PDOException('插入word_to_topic表失败!');
+                    }
+
+                    $schdbh->commit();
+                } catch (PDOException $e) {
+                    $schdbh->rollback(); // 执行失败,事务回滚
+                    exit($e->getMessage());
+                }
+            }
+
+            // 处理完
+            $resu = $schdbh->prepare('UPDATE `topic_word` SET `status` = 2,`parse_time`=:time WHERE `word_id` =:wid');
+            $resu->execute(array(':wid' => $word_id, ':time' => time()));
+
+            // 监控日志
+            $teachInfo = $schdbh->query('SELECT `teacher_name` FROM `teacher` WHERE `teacher_id`="' . $wordInfo['uploader_id'] . '"')->fetch(PDO::FETCH_ASSOC);
+            BMonitorLog::model()->addLog(array(
+                'school_id' => $school_id,
+                'teacher_id' => $wordInfo['uploader_id'],
+                'log_content' => array(
+                    $teachInfo['teacher_name'],
+                    '上传了',
+                    $wordInfo['word_name'],
+                    '校本卷库'
+                )
+            ));
+
+            $schdbh = null;
+            exit('解析完成!');
+        }
+    }
+
+    /**
+     * 全学科第三方试卷解析
+     * @param $string
+     * @return mixed
+     */
+	public function actionAllSubjectCoach()
+	{
+                $apiTopics = array();
+		// 获取curl过来值
+                $word_id = isset($_GET['wid']) ? intval($_GET['wid']) : 0;
+                $school_id = isset($_GET['sid']) ? intval($_GET['sid']) : 0;
+                if (empty($word_id) || empty($school_id)) {
+                    exit('未找到word Id或者学校id');
+                }
+		// 连接业务库
+                $busDsn = 'mysql:host=' . Yii::app()->params["default_server"]['addr'] . ';dbname=' . Yii::app()->params["default_db"]['name'] . ';';
+                $busdbh = new PDO($busDsn, Yii::app()->params["default_server"]['username'], Yii::app()->params["default_server"]['password'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8";'));
+                $getDataBase = $busdbh->query('SELECT * FROM `database` WHERE `school_id`=' . $school_id);
+                $dataBaseInfo = $getDataBase->fetch(PDO::FETCH_ASSOC);
+                if (empty($dataBaseInfo)) {
+                    exit('未找到数据库链接信息!');
+                }
+                $busdbh = null;
+
+                // 连接学校库
+                $schDsn = 'mysql:host=' . $dataBaseInfo['database_host'] . ';dbname=' . $dataBaseInfo['database_name'] . ';';
+                $schdbh = new PDO($schDsn, $dataBaseInfo['database_user'], $dataBaseInfo['database_password'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8";'));
+                $wordInfo = $schdbh->query('SELECT `word_id`,`word_name`,`subject_id`,`uploader_id`,`exam_group_id` FROM `topic_word` WHERE `word_id`=' . $word_id)->fetch(PDO::FETCH_ASSOC);
+                if (empty($wordInfo)) {
+                    exit('未找到上传word信息!');
+                }
+		
+		$getWordJson = file_get_contents('php://input');
+                $jsonArray = json_decode($getWordJson, true);
+		if (empty($jsonArray) || $jsonArray['errcode'] == 1 || empty($jsonArray['items'])) {
+                    $errMsg = array();
+                    if (isset($jsonArray['errmsgs']) && $jsonArray['errmsgs']) {
+                        if (is_array($jsonArray['errmsgs'])) {
+                            foreach ($jsonArray['errmsgs'] as $msg) {
+                                $errMsg[] = key($msg) . ':' . implode(', ', $msg[key($msg)]);
+                            }
+                        } else {
+                            $errMsg[] = $jsonArray['errmsgs'];
+                        }
+                    }
+
+                    $errMsg = $errMsg ? implode('<br/>', $errMsg) : '解析异常';
+                    $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,`file_path` = :path,parse_time=:time WHERE `word_id` =:wid');
+                    $stmt->execute(array(':wid' => $word_id, ':reason' => $errMsg, ':content' => $getWordJson, ':path' => '', ':time' => time()));
+                    exit('解析失败!');
+                } else {
+			// 获取科目题型
+			$tempTypeName = array(1=>'选择题','2'=>'多选题',11=>'多选题',5=>'填空题',7=>'解答题');
+			$apiParam = Yii::app()->params['api'][0];
+			$apiParam['prefix'] .= 'all_subject/topic_type/subjectId/' . $wordInfo['subject_id'];
+			$topicTypeJson = self::getApiData($apiParam, 1, '', 3);
+			$topicTypes = json_decode($topicTypeJson, true);
+			if (isset($topicTypes['status'])) {
+				if ($topicTypes['status'] == 0 || empty($topicTypes['data'])) {
+					$stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason, parse_time=:time WHERE `word_id` =:wid');
+					$stmt->execute(array(':wid' => $word_id, ':reason' => '未找到科目题型', ':time' => time()));
+					exit('未找到科目题型');
+				} elseif ($topicTypes['status'] == 1 && $topicTypes['data']) {
+					$topicTypes = $topicTypes['data'];
+				}
+			}
+
+			// 查询考试试题
+			$paper_topic_relation_data = $schdbh->query('select pt.topic_id,pt.type,pp.* from paper_topic_relation pt join (select p.paper_id ,e.subject_id as subject_id,e.exam_group_id from exam e left JOIN  paper p on e.exam_id = p.exam_id where e.exam_group_id = ' . $wordInfo['exam_group_id'] . ' GROUP BY e.exam_group_id) as pp on pt.paper_id = pp.paper_id order by pt.order asc')->fetchAll(PDO::FETCH_ASSOC);
+			if (empty($paper_topic_relation_data)) {
+				$stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+				$stmt->execute(array(':wid' => $word_id, ':reason' => '未找到考试试题', ':content' => $getWordJson, ':time' => time()));
+				exit('未找到考试试题');
+			}
+
+			if (count($paper_topic_relation_data) != count($jsonArray['items'])) {
+                            $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status`=3,`wrong_reason`=:reason,`content`=:content,parse_time=:time WHERE `word_id`=:wid');
+                            $stmt->execute(array(':wid' => $word_id, ':reason' => 'WORD题量与试卷题量不同', ':content' => $getWordJson, ':time' => time()));
+                            exit('WORD题量与试卷题量不同');
+                        }
+			
+			$relate_topic_id = array();
+			$p_topic_type_num = array();
+			$relate_topic_type = array();
+			foreach ($paper_topic_relation_data as $v) {
+				$relate_topic_id[] = $v['topic_id'];
+				$p_topic_type_num[$v['type']][] = $v['topic_id'];
+				if (!in_array($v['type'], $relate_topic_type)) {
+					$relate_topic_type[] = $v['type'];
+				}
+			}
+
+			// 题型格式
+			$topicTypeName = array();
+			$topicTypeConfig = array();
+			foreach ($topicTypes as $topicType) {
+				$topicTypeName[$topicType['topic_type_name']] = $topicType['topic_type_id'];
+				$topicTypeConfig[$topicType['topic_type_id']] = $topicType;
+			}
+
+			// 删除已存在试题缓存
+			$apiParam = Yii::app()->params['api'][0];
+			$apiParam['prefix'] .= 'topic_clear_redis/ctopic';
+			self::getApiData($apiParam, 2, json_encode(array('topicIds' => $relate_topic_id)), 3);
+			
+			$topic_type_num = array(); // 解析结果各题型数量
+			$topic_type_error = array(); // 验证是否存在非题库题型
+			$parse_topic_type = array(); // 解析返回的题型ID
+			$topic_type_name = array();
+			$bankTypeParam = Yii::app()->params['subject_topic_type_matching']; // 全学科基本题型与老题库对应
+			foreach ($jsonArray['items'] as $loop) {
+				if (!isset($topicTypeName[$loop['type']])) {
+					$topic_type_error[] = "题库不存在【{$loop['type']}】题型不存在";
+				} else {
+					$tempTypeId = (int)$topicTypeName[$loop['type']];
+					$typeConfig = $topicTypeConfig[$tempTypeId];
+					if (isset($bankTypeParam[$typeConfig['btt_id']])) {
+						if (!isset($topic_type_num[$bankTypeParam[$typeConfig['btt_id']]])) {
+							$parse_topic_type[] = $bankTypeParam[$typeConfig['btt_id']];
+							$topic_type_num[$bankTypeParam[$typeConfig['btt_id']]] = array();
+						}
+						$topic_type_num[$bankTypeParam[$typeConfig['btt_id']]][] = 1;
+					}
+				}
+			}
+
+			if ($topic_type_error) {
+				$stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content, parse_time=:time WHERE `word_id` =:wid');
+				$stmt->execute(array(':wid' => $word_id, ':reason' => implode('<br/>', $topic_type_error), ':content' => $getWordJson, ':time' => time()));
+				exit('题型不存在');
+			}
+
+			// 验证试卷题型是否和解析题型完全匹配
+			/*if ($relate_topic_type && $parse_topic_type) {
+				foreach ($relate_topic_type as $rttId) {
+					if (in_array($rttId, $parse_topic_type)) {
+						array_splice($parse_topic_type,array_search($rttId ,$parse_topic_type),1);
+					} else {
+						$topic_type_error[] = "上传Word未包含考试创建的题型({$rttId})";
+					}
+				}
+
+				if (count($parse_topic_type) > 0) {
+					$topic_type_error[] = '上传的题型与试卷题型不一致';
+				}
+
+				if ($topic_type_error) {
+					$stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content, parse_time=:time WHERE `word_id` =:wid');
+					$stmt->execute(array(':wid' => $word_id, ':reason' => implode('<br/>', $topic_type_error),':content' => $getWordJson, ':time' => time()));
+					exit('上传的题型与试卷题型不一致');
+				}
+			}
+
+			// 验证题型数量
+			$validate_topic_info = array();
+			foreach ($p_topic_type_num as $vtnKey => $vtnVal) {
+				if (!isset($topic_type_num[$vtnKey]) || count($vtnVal) != count($topic_type_num[$vtnKey])) {
+					$validate_topic_info[] = 'word'.$tempTypeName[$vtnKey].'题量与试卷的题量不同';
+				}
+			}
+			
+			if ($validate_topic_info) {
+				$stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+				$stmt->execute(array(':wid' => $word_id, ':reason' => implode('<br/>', $validate_topic_info),':content' => $getWordJson, ':time' => time()));
+				exit(implode("<br/>",$validate_topic_info));
+			}*/
+
+			// 获取默认文件夹id
+			$defaultFolder = $schdbh->query('SELECT `folder_id` FROM `topic_folder` WHERE `is_system`=1')->fetch(PDO::FETCH_ASSOC);
+			$folderId = empty($defaultFolder['folder_id']) ? 0 : $defaultFolder['folder_id'];
+
+			// 解析试题内容
+			foreach ($jsonArray['items'] as $key => $item) {
+				$topicId = $paper_topic_relation_data[$key]['topic_id'];
+                                $apiTopics[] = $topicId;
+				$typeId = (int)$topicTypeName[$item['type']];
+                                $typeConfig = $topicTypeConfig[$typeId];
+
+				// 试题入库处理
+                                try {
+                                    $schdbh->beginTransaction(); // 开启事务
+
+                                    $now_time = time();
+                                    $difficulty = isset($item['difficulty']) ? $item['difficulty'] : 1;
+
+                                    // topic表
+                                    $stmt = $schdbh->prepare('UPDATE `topic` SET `topic_title` = :topic_title,`topic_difficulty` = :topic_difficulty,`source_title`=:source_title,`bank_type`=:bank_type,`parse_content`=:parse_content,`update_time`=:update_time WHERE `topic_id` =:topic_id');
+                                    $stmt->execute(array(':topic_id' => $topicId, ':topic_title' => $item['stem'],':topic_difficulty'=>$difficulty,':bank_type'=>$typeId, ':source_title' => 'word上传试题', ':parse_content' => $item['analysis'], ':update_time' => time()));
+
+                                    // topic_item
+                                    $stmt = $schdbh->prepare('UPDATE `topic_item` SET `topic_title` = :topic_title WHERE `topic_id` =:topic_id');
+                                    $stmt->execute(array(':topic_id' => $topicId, ':topic_title' => $item['stem']));
+
+                                                        $stmt = $schdbh->prepare('delete from `topic_item_option` WHERE `topic_id` =:topic_id');
+                                    $stmt->execute(array(':topic_id' => $topicId));
+
+                                                        // 选择题选项处理
+                                                        if (isset($item['options']) && $item['options']) { // 含有选项的试题
+                                                                //$optionKeys = explode(',', $item['key']);
+                                                                $optionKeys = array();
+                                                                foreach ($this->charToNum as $char => $num) {
+                                                                        if (strpos($item['key'], $char) !== false) {
+                                                                                $optionKeys[] = $char;
+                                                                        }
+                                                                }
+
+                                                                $rowThr = $schdbh->prepare('INSERT INTO `topic_item_option`(`topic_id`, `option_content`, `option_correct`,`sort_order`) VALUES (:tpid,:content,:correct,:sort_order)');
+                                                                $correct = 'A';
+                                                                foreach ($item['options'] as $vk => $option) {
+                                                                        $is_true = in_array($correct, $optionKeys) ? 1 : 0;
+                                                                        $getRowThr = $rowThr->execute(array(':tpid'=>$topicId,':content'=>$option,':correct'=>$is_true,':sort_order'=>$vk));
+                                                                        ++$correct;
+                                                                }
+                                                        } else {
+                                        $rowFiv = $schdbh->prepare('INSERT INTO `topic_item_option`(`topic_id`, `option_content`) VALUES (:tpid,:content)');
+                                        if (is_array($item['key']) && $item['key']) {
+                                            foreach ($item['key'] as $topicKey) {
+                                                $getRowFiv = $rowFiv->execute(array(':tpid' => $topicId, ':content' => $topicKey));
+                                            }
+                                        } else {
+                                            $getRowFiv = $rowFiv->execute(array(':tpid' => $topicId, ':content' => $item['key']));
+                                            if (!$getRowFiv) {
+                                                throw new PDOException('插入topic_item_option表失败!');
+                                            }
+                                        }
+                                                        }
+
+                                    // word与试题关系
+                                    $rowFor = null;
+                                    $rowFor = $schdbh->prepare('INSERT INTO `word_topic_relation`(`word_id`, `topic_id`) VALUES (:wid,:toid)');
+                                    $getRowFor = $rowFor->execute(array(':wid' => $word_id, ':toid' => $topicId));
+                                    if (!$getRowFor) {
+                                        throw new PDOException('插入word_to_topic表失败!');
+                                    }
+
+                                    $schdbh->commit();
+                                } catch (PDOException $e) {
+                                    $schdbh->rollback(); // 执行失败,事务回滚
+
+                                    $stmt = $schdbh->prepare('UPDATE `topic_word` SET `status` = 3,`wrong_reason` = :reason,`content` = :content,parse_time=:time WHERE `word_id` =:wid');
+                                    $stmt->execute(array(':wid' => $word_id, ':reason' => $e->getMessage(), ':content' => $getWordJson, ':time' => time()));
+                                    exit($e->getMessage());
+                                }
+			}
+			//exit($topicId);
+		}
+
+		// 处理完
+		$resu = $schdbh->prepare('UPDATE `topic_word` SET `status` = 2,`parse_time`=:time,`content` = :content WHERE `word_id` =:wid');
+		$resu->execute(array(':wid' => $word_id, ':time' => time(), ':content' => $getWordJson));
+
+		$resu = $schdbh->prepare('UPDATE `exam_group` SET `is_answersheet` = 1 WHERE `exam_group_id` =:exam_group_id');
+		$resu->execute(array(':exam_group_id' => $wordInfo['exam_group_id']));
+
+		// 插入解析时间记录
+		$resPro = $schdbh->prepare("INSERT INTO `exam_process` (`exam_group_id`, `action_type`, `action_time`) VALUES (:exam_group_id, :tempType, :time)");
+		$resPro->execute(array(':exam_group_id' => $wordInfo['exam_group_id'], ':tempType' => 4, ':time' => time()));
+
+		// 监控日志
+		BMonitorLog::model()->addLog(array(
+			'school_id' => $school_id,
+			'teacher_id' => $wordInfo['uploader_id'],
+			'log_content' => array('助教','上传了',$wordInfo['word_name'],'试卷')
+		));
+
+		$schdbh = null;
+                if($apiTopics){
+                    //调用试题检索接口
+                    $this->searchTopics($apiTopics,$school_id);
+                }
+		exit('解析完成!');
+	}
+
+    // 试题内容相关过滤处理等
+    function strip_content_tags($str)
+    {
+        if (empty($str)) return $str;
+        $allow_tags = "<br><dd><dl><div><dt><img><label><li><ol><p><span><sub><sup><table><tbody><td><tfoot><th><thead><tr><ul>";
+        // $str = htmlspecialchars_decode($str);
+        $str = preg_replace('/alt=[\\\'|\\"](.*?)[\\\'|\\"]/', '', $str);
+        return $str;
+//        return strip_tags($str, $allow_tags);
+    }
+
+    // 下载远程图片
+    function downloadImg($content, $school_id)
+    {
+        $img_date = date('Ymd');
+        $school_id = empty($school_id) ? 1 : $school_id;
+
+		// 如果解析返回的图片是已上传ucloud则无需处理
+		if ($this->flag == 1) {
+			return $content;
+		}
+
+        // 匹配所有远程图片
+        $img_array = array();
+        preg_match_all("/<img.*?src=[\\\'| \\\"](.*?(?:[\.gif|\.jpg|\.png]))[\\\'|\\\"].*?[\/]?>/is", $content, $img_array);
+        if (empty($img_array[1])) {
+            return $content;
+        }
+
+        // 文件保存目录URL
+        $save_url = '/uploadfiles/wordimg/' . $school_id . '/' . date('Y') . '/' . date('m') . '/' . date('d');
+        $save_path = dirname(dirname(dirname(__FILE__))) . $save_url;
+
+        // 创建文件夹
+        if (!is_dir($save_path)) {
+            @mkdir($save_path, 0777, true);
+        }
+
+        foreach ($img_array[1] as $key => $value) {
+
+            // 保存到本地图片名称
+            $imgInfo = pathinfo($value);
+            $imgname = uniqid() . '.' . $imgInfo['extension'];
+
+            // 保存到本地的实际文件地址(包含路径和名称)
+            $fileName = $save_path . '/' . $imgname;
+			self::curlDownloadImage($value, $fileName);
+
+            // 教师端访问的地址
+            $fileurl = $this->webSiteUrl . $save_url . "/" . $imgname;
+
+            // 判断图片是否要压缩
+            self::imgCompress($fileName);
+
+            // 替换原来的图片地址
+            $uploadInfo = $this->ucloud->putFile('teacher'.$save_url .'/'. $imgname, $fileName);
+            if ($uploadInfo['status']) {
+                $content = str_replace($value, $uploadInfo['url'], $content);
+                @unlink($fileName);
+            } else {
+                $content = str_replace($value, $fileurl, $content);
+            }
+        }
+        return $content;
+    }
+
+	/**
+     * 采集远程图片
+     * @param string $url 远程文件地址
+     * @param string $fileName 保存后的文件名
+     * @return bool
+     */
+    function curlDownloadImage($url, $fileName = '')
+    {
+        if (empty($url) || empty($fileName)) {
+            return false;
+        }
+
+        // 获取远程文件资源
+        $ch = curl_init();
+        curl_setopt($ch, CURLOPT_URL, $url);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
+        $tempFile = curl_exec($ch);
+        curl_close($ch);
+
+        // 保存文件
+        $fp = @fopen($fileName, "w");
+        fwrite($fp, $tempFile);
+        fclose($fp);
+        return true;
+    }
+
+    // 压缩图片尺寸以及比例
+    public static function imgCompress($imgSrc = '')
+    {
+        $standardWidth = 2000;
+        if (empty($imgSrc)) {
+			return true;
+		} elseif (!file_exists($imgSrc)) {
+			return true;
+		}
+
+        list($width, $height, $type) = getimagesize($imgSrc);
+        if ($width < $standardWidth) {
+            return true;
+        }
+
+        $multiple = round($width / $standardWidth, 2);
+        $newWidth = 2000;
+        $newHeight = ceil($height / $multiple);
+
+        if (!$newWidth || !$newHeight) return true;
+
+        $imgType = image_type_to_extension($type, false);
+        $imageCreateType = 'image' . $imgType; // 创建新图像
+        $funCreateFromType = 'imagecreatefrom' . $imgType; // 创建新图像
+
+        $imageP = imagecreatetruecolor($newWidth, $newHeight);
+        $colorBlack = imagecolorallocatealpha($imageP, 0, 0, 0, 127);//拾取一个完全透明的颜色
+        imagealphablending($imageP, false);//关闭混合模式,以便透明颜色能覆盖原画布
+        imagefill($imageP, 0, 0, $colorBlack);//填充
+        $image = $funCreateFromType($imgSrc);
+
+        imagecopyresampled($imageP, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
+        imagesavealpha($imageP, true);
+        $imageCreateType($imageP, $imgSrc);
+        imagedestroy($image);
+        imagedestroy($imageP);
+        return true;
+    }
+
+    // 下载错题word文本
+    function downloadWord($word_info, $word_url, $school_id)
+    {
+        //暂时修改
+        return "";
+        if (empty($word_info) || empty($word_url) || empty($school_id)) return '';
+        // 文件保存目录URL
+        $save_url = '/uploadfiles/words/wrong_word/' . $school_id . '/' . date('Y') . '/' . date('m') . '/' . date('d');
+        $save_path = dirname(dirname(dirname(__FILE__))) . $save_url;
+
+        // 创建文件夹
+        if (!is_dir($save_path)) {
+            @mkdir($save_path, 0777, true);
+        }
+
+        // 保存到本地word名称
+        $wordInfo = pathinfo($word_info['word_name']);
+        $wordname = $word_info['word_id'] . '.' . $wordInfo['extension'];
+
+        // 保存到本地的实际文件地址(包含路径和名称)
+        $fileName = $save_path . '/' . $wordname;
+
+        // 实际访问的地址
+        $fileurl = Yii::app()->params['siteurl'] . $save_url . "/" . $wordname;
+
+        // 读取远程图片
+        set_time_limit(0);
+        $get_file = @file_get_contents($word_url);
+
+        if ($get_file) {
+            $fp = @fopen($fileName, "w");
+            @fwrite($fp, $get_file);
+            @fclose($fp);
+
+            return $fileurl;
+        }
+        return '';
+    }
+
+    // 公式转换(2018-11-29停用)
+    function formulaTransform($string)
+    {
+        preg_match_all("/(data-latex=\\\"([^\"]*\\\"))|(\\$.*?\\$)|(\\\\\\[.*?\\\\\\])/", $string, $get_math_thr);
+        if ($get_math_thr[0]) {
+            $uniqueMath = array_unique($get_math_thr[0]);
+            foreach ($uniqueMath as $vvtr) {
+                if (substr($vvtr, 0, 10) !== "data-latex") {
+                    $mathmlOptThr = saveMathtex($vvtr);
+                    if ($mathmlOptThr['status'] == 1) {
+                        $string = str_replace($vvtr, '<img src="' . $mathmlOptThr['fileUrl'] . '" class="gsImgLatex mathType" width="' . $mathmlOptThr['imgWidth'] . '" height="' . $mathmlOptThr['imgHeight'] . '"/>', $string);
+                    }
+                }
+            }
+        }
+
+        // LaTeX与MathML转换(暂时注销 2016-10-08)
+        //$myMathml  =   new MathMlEncode();
+        //$string	   =   $myMathml->replaceForJsMathml($string);
+        return $string;
+    }
+
+    private static function getApiData($apiParam, $flag = 1, $data, $timeOut = 0,$extraHeaders = array())
+    {
+        $result = FALSE;
+        $ch = @curl_init();
+        if ($ch) {
+            $headers = array(
+                'Content-Type: application/json',
+                'Content-Length: ' . strlen($data),
+            );
+            if($extraHeaders){
+                $headers = array_merge($headers,$extraHeaders);
+            }
+            // Digest认证
+            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
+            curl_setopt($ch, CURLOPT_USERPWD, $apiParam['username'] . ':' . $apiParam['password']);
+
+            // 不输出头部
+            curl_setopt($ch, CURLOPT_HEADER, 0);
+            if ($timeOut) {
+                curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
+                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
+            }
+            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+
+            // curl_exec 获取到的内容不直接输出, 而是返回
+            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+
+            // 请求重启路由器的地址 传参 进行重启
+            curl_setopt($ch, CURLOPT_URL, $apiParam['prefix']);
+
+            curl_setopt($ch, CURLOPT_USERAGENT, 'Api Client/1.0.0 (chengfei@liancaitech.com)');
+            if ($flag == 2) {
+                curl_setopt($ch, CURLOPT_POST, 1);
+                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+            }
+
+            $result = curl_exec($ch);
+            if (curl_errno($ch)) {
+                return 'curl_errno:' . curl_errno($ch);
+            }
+
+            // 释放资源
+            curl_close($ch);
+        }
+        return $result;
+    }
+    
+    
+    //全学科试题调用java检索缓存接口
+    public function searchTopics($topicIds = array(),$schoolId = 0){
+        $apiParam = Yii::app()->params['api'][3];
+        if($apiParam && $topicIds && $schoolId){
+            $url = $apiParam['prefix'].'cgi/teacher/schtk/qxk/school-topic-flush/'.$schoolId;
+            self::getApiData(array(
+                    'username' => $apiParam['username'],
+                    'password' => $apiParam['password'],
+                    'prefix' => $url
+            ), 2, json_encode($topicIds), 3,array('X-Basic-V:2'));
+        }
+    }
+}