123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509 |
- <?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['teacherSiteurl'];
- $this->flag = isset($_GET['flag']) ? intval($_GET['flag']) : 1;
- }
- /**
- * 全学科第三方试卷解析
- * @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 = Yii::app()->businessDb;
- $dataBaseInfo = $busDsn->createCommand('SELECT * FROM `database` WHERE `school_id`=' . $school_id)->queryRow();
- 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('题型不存在');
- }
- // 获取默认文件夹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()));
- $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'));
- }
- }
- }
|