ApiController.class.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. <?php
  2. namespace Common\Controller;
  3. use Think\Controller;
  4. class ApiController extends Controller {
  5. public $userId = 0;
  6. public function __construct(){
  7. parent::__construct();
  8. $token = I('token', '');
  9. if(ACTION_NAME=='push'){
  10. return;
  11. }
  12. if (I('debug')==1){
  13. $this->userId = I('user_id','1000001');
  14. }elseif (!empty($token)){
  15. $user = S('user_'.$token);
  16. if (!empty($user)){
  17. $user = json_decode($user,true);
  18. }else{
  19. $data = array('code'=>2,'msg'=>'Token失效, 请重新登录!');
  20. $this->ajaxReturn($data);
  21. }
  22. $this->userId = $user['user_id'];
  23. }else{
  24. $this->userId = session('user_id');
  25. }
  26. if ($this->userId<0){
  27. $data = array('code'=>2,'msg'=>'Token失效, 请重新登录!');
  28. $this->ajaxReturn($data);
  29. }
  30. $info = M('User')->where(array('user_id'=>$this->userId))->find();
  31. $imei = I('user_imei');
  32. if (empty($imei)){
  33. $imei = $_SERVER['HTTP_IMEI'];
  34. }
  35. if (!empty($imei) && !empty($info['imei']) && $imei!=$info['imei']){
  36. $title = '已在另一地点登录,如非本人操作,请及时修改密码!';
  37. $data = array('code'=>2,'msg'=>$title);
  38. $this->returnData($data);
  39. }
  40. if ($info==NULL){
  41. $data = array('code'=>2,'msg'=>'用户id错误');
  42. $this->ajaxReturn($data);
  43. }
  44. //S('userInfo'.$this->userId,$info);
  45. }
  46. //获取单词释义字符串
  47. public function getWordsText($row){
  48. $str = '';
  49. $wordsKeys = array('words_n','words_pron','words_adj','words_num','words_v','words_adv','words_art','words_prep','words_conj','words_int','words_vt','words_vi','words_other',);
  50. foreach ($wordsKeys as $key){
  51. if (!empty($row[$key])){
  52. $arr = explode('_', $key);
  53. $str .= $arr[1].'.'.$row[$key];
  54. }
  55. }
  56. return $str;
  57. }
  58. //获取单词释义字符串
  59. public function getWordsText1($row,$type){
  60. $str = array();
  61. $wordsKeys = array('words_n','words_pron','words_adj','words_num','words_v','words_adv','words_art','words_prep','words_conj','words_int','words_vt','words_vi','words_other',);
  62. foreach ($wordsKeys as $key){
  63. if (!empty($row[$key])){
  64. $arr = explode('_', $key);
  65. if ($type==2){
  66. $str[] = $row[$key];
  67. }else{
  68. $str[] = $arr[1].'. '.$row[$key];
  69. }
  70. }
  71. }
  72. if ($type==4){
  73. return mb_substr(implode($str, ' '), 0, 60,'UTF-8');
  74. }else{
  75. return $str;
  76. }
  77. }
  78. /**
  79. * 发送短信注册码
  80. * @param unknown $mobile
  81. * @param unknown $code
  82. */
  83. public function sendPhone($mobile, $code){
  84. Vendor('Sms.SmsSingleSender');
  85. $smsConf = C('SMS_CONFIG');
  86. $sender=new \SmsSingleSender($smsConf['appId'], $smsConf['appKey']);
  87. $result = $sender->send(0, "86", $mobile,
  88. "您在碰词儿的验证码是".$code.",请于5分钟内填写。如非本人操作,请忽略本短信。", "", "");
  89. $rsp = json_decode($result,true);
  90. if(isset($rsp['result']) && $rsp['result']==0){
  91. return TRUE;
  92. }else{
  93. return FALSE;
  94. }
  95. }
  96. //获取课程名称相同时,新的课程名称
  97. public function getCourseName($courseName){
  98. $course = M('Course')->where(array('course_name'=>$courseName,'is_delete'=>1))->field('course_id')->find();
  99. $res = M('TitleNum')->where(array('title_name'=>$courseName))->field('title_id,title_num')->find();
  100. if ($res!=NULL){
  101. $courseName = $courseName.'('.($res['title_num']+1).')';
  102. M('TitleNum')->where(array('title_id'=>$res['title_id']))->setInc('title_num');
  103. }else if($course!=NULL){
  104. $courseName = $courseName.'('.($res['title_num']+1).')';
  105. M('TitleNum')->add(array('title_name'=>$courseName,'operate_dt'=>time()));
  106. //$courseName = $courseName;
  107. }
  108. return $courseName;
  109. }
  110. //复制一份课程下面的单词
  111. public function copyWords($oldCourseId,$newCourseId,$wordsId=''){
  112. $wordsSortInfo = M('WordsSort')->where(array('course_id'=>$oldCourseId,'user_id'=>$this->userId))->field('sort_id')->find();
  113. if ($wordsSortInfo != NULL){
  114. M('WordsSort')->where(array('sort_id'=>$wordsSortInfo['sort_id']))->save(array('course_id'=>$newCourseId));
  115. }
  116. if (empty($wordsId)){
  117. $wordsList = M('Words')->where(array('course_id'=>$oldCourseId,'is_delete'=>1))->order('words_id asc')->select();
  118. }else{
  119. $wordsList = M('Words')->where(array('course_id'=>$oldCourseId,'is_delete'=>1,'words_id'=>array('NOT IN',$wordsId),))->order('words_id asc')->select();
  120. }
  121. foreach ($wordsList as $words){
  122. if (empty($words['words_name'])){
  123. continue;
  124. }
  125. $words['s_words_id']=$words['words_id'];
  126. unset($words['words_id']);
  127. $words['course_id'] = $newCourseId;
  128. $words['words_source'] = 2;
  129. $words['operate_dt'] = time();
  130. M('Words')->add($words);
  131. }
  132. }
  133. //推送消息
  134. public function pushMsg($content, $userId=''){
  135. $httpCurl = new \Org\Net\HttpCurl();
  136. $pushApiUrl = 'http://127.0.0.1:2121/';
  137. if (is_array($userId)){
  138. foreach ($userId as $uid){
  139. $data = array(
  140. 'type' => 'publish',
  141. 'content' => $content,
  142. //'content' => '{"code": 0,"msg": "已应战,请准备开始对战!","data": {"record_id": "11","user_id": "1000005","ref_user_id": "1000010"}}',
  143. 'to' => $uid,
  144. );
  145. $res = $httpCurl->post($pushApiUrl, $data, '');
  146. if ($res=='offline'){
  147. //return $uid;
  148. return $this->retryPushMsg($content, $uid);
  149. }
  150. }
  151. return FALSE;
  152. }else if(!empty($userId)){
  153. $data = array(
  154. 'type' => 'publish',
  155. 'content' => $content,
  156. 'to' => $userId,
  157. );
  158. $res = $httpCurl->post($pushApiUrl, $data, '');
  159. if ($res=='offline'){
  160. //return $userId;
  161. return $this->retryPushMsg($content, $userId);
  162. }
  163. return FALSE;
  164. }else{
  165. $data = array(
  166. 'type' => 'publish',
  167. 'content' => $content,
  168. 'to' => '',
  169. );
  170. $res = $httpCurl->post($pushApiUrl, $data, '');
  171. if ($res=='offline'){
  172. //return $uid;
  173. return $this->retryPushMsg($content, $userId);
  174. }
  175. return FALSE;
  176. }
  177. }
  178. //重试socket推送消息
  179. private function retryPushMsg($content, $to_user, $retry=2){
  180. sleep(2);
  181. $pushApiUrl = 'http://127.0.0.1:2121/';
  182. $httpCurl = new \Org\Net\HttpCurl();
  183. $data = array(
  184. 'type' => 'publish',
  185. 'content' => $content,
  186. 'to' => $to_user,
  187. );
  188. $res = $httpCurl->post($pushApiUrl, $data, '');
  189. if ($res=='offline' && $retry==2){
  190. $this->retryPushMsg($content, $to_user, 3);
  191. }
  192. if ($res=='offline'){
  193. return $to_user;
  194. }
  195. return FALSE;
  196. }
  197. //获取在线用户
  198. public function online(){
  199. $pushApiUrl = 'http://127.0.0.1:2121/';
  200. $httpCurl = new \Org\Net\HttpCurl();
  201. $data = array('type' => 'online',);
  202. $res = $httpCurl->post($pushApiUrl, $data, '');
  203. return json_decode($res,TRUE);
  204. }
  205. /**
  206. * 发送友盟推送消息
  207. * @param integer $uid 用户id
  208. * @param string $title 推送的标题
  209. * @param integer $type 1:官方小秘书 2:我的评论
  210. * @return boolear 是否成功
  211. */
  212. public function umengPush($uid,$title){
  213. // 获取token
  214. $userInfo = D('User')->where(array('user_id'=>$uid))->field('access_token')->find();
  215. // 如果没有token说明移动端没有登录;则不发送通知
  216. if ($userInfo==NULL || empty($userInfo['access_token'])) {
  217. return false;
  218. }
  219. $device_tokens = $userInfo['access_token'];
  220. // 导入友盟
  221. Vendor('Umeng.Umeng');
  222. // 自定义字段 根据实际环境分配;如果不用可以忽略
  223. $status=1;
  224. // 消息未读总数统计 根据实际环境获取未读的消息总数 此数量会显示在app图标右上角
  225. $count_number=1;
  226. $data=array(
  227. 'key'=>'status',
  228. 'value'=>"$status",
  229. 'count_number'=>$count_number
  230. );
  231. // 判断device_token 64位表示为苹果 否则为安卓
  232. if(strlen($device_tokens)==64){
  233. $key=C('UMENG_IOS_APP_KEY');
  234. $timestamp=C('UMENG_IOS_SECRET');
  235. $umeng=new \Umeng($key, $timestamp);
  236. $umeng->sendIOSUnicast($data,$title,$device_tokens);
  237. }else{
  238. $key=C('UMENG_ANDROID_APP_KEY');
  239. $timestamp=C('UMENG_ANDROID_SECRET');
  240. $umeng=new \Umeng($key, $timestamp);
  241. $umeng->sendAndroidUnicast($data,$title,$device_tokens);
  242. }
  243. return true;
  244. }
  245. //返回数据
  246. public function returnData($data){
  247. if (!is_array($data['data'])){
  248. $data['data'] = new \stdClass();
  249. }
  250. $this->ajaxReturn($data);
  251. }
  252. //获取好友昵称
  253. public function getUserNickname(){
  254. $userNameArr = S($this->userId.'_user_nickname');
  255. if (!$userNameArr && !is_array($userNameArr)){
  256. $condition['user_id|ref_user_id'] = $this->userId;
  257. $condition['friend_status'] = 2;
  258. $res = M('Friend')->where($condition)->field('user_id,ref_user_id,user_nickname,ref_user_nickname')->order('friend_id desc')->select();
  259. if ($res==NULL){
  260. $userNameArr = array();
  261. }
  262. $userNameArr = array();
  263. foreach ($res as $r){
  264. if ($r['user_id']==$this->userId){
  265. $userNameArr[$r['ref_user_id']] = $r['ref_user_nickname'];
  266. }else{
  267. $userNameArr[$r['user_id']] = $r['user_nickname'];
  268. }
  269. }
  270. S($this->userId.'_user_nickname',$userNameArr);
  271. }
  272. return $userNameArr;
  273. }
  274. /**
  275. * 添加队列(lpush)
  276. * @param string $value
  277. * @return int 队列长度
  278. */
  279. public function pushQueue($key, $value){
  280. //Vendor('Sms.SmsSingleSender');
  281. //$sender=new \SmsSingleSender($smsConf['appId'], $smsConf['appKey']);
  282. $queue = new \Com\Queue();
  283. //$queueName = 'pk_words_'.$recordId;
  284. $queue->setQueueName($key);
  285. $queueVal = serialize($value);
  286. return $queue->push($queueVal);
  287. }
  288. /**
  289. * 读取队列(brpop)
  290. * @return string|nil
  291. */
  292. public function popQueue($key){
  293. $queue = new \Com\Queue();
  294. //$queueName = 'pk_words_'.$recordId;
  295. $queue->setQueueName($key);
  296. $queueVal = $queue->pop();
  297. if (empty($queueVal)){
  298. return FALSE;
  299. }else{
  300. return unserialize($queueVal);
  301. }
  302. }
  303. public function flushQueue($key){
  304. $queue = new \Com\Queue();
  305. $queue->setQueueName($key);
  306. $queue->flushQueue();
  307. }
  308. //添加循环队列
  309. public function rpushQueue($key,$value){
  310. $queue = new \Com\RingQueue();
  311. //$queueName = 'pk_words_'.$recordId;
  312. $queue->setQueueName($key);
  313. $queueVal = serialize($value);
  314. return $queue->push($queueVal);
  315. }
  316. //读取循环队列
  317. public function rpopQueue($key){
  318. $queue = new \Com\RingQueue();
  319. //$queueName = 'pk_words_'.$recordId;
  320. $queue->setQueueName($key);
  321. $queueVal = $queue->pop();
  322. if (empty($queueVal)){
  323. return FALSE;
  324. }else{
  325. return unserialize($queueVal);
  326. }
  327. }
  328. /**
  329. * 连接redis
  330. * @return \Redis
  331. */
  332. public function getRedis(){
  333. if ( !extension_loaded('redis') ) {
  334. E(L('_NOT_SUPPORT_').':redis');
  335. }
  336. $options = array(
  337. 'host' => C('REDIS_HOST') ? : '127.0.0.1',
  338. 'port' => C('REDIS_PORT') ? : 6379,
  339. 'timeout' => C('DATA_CACHE_TIMEOUT') ? : false,
  340. 'expire'=>3600,
  341. 'persistent' => false,
  342. );
  343. $this->options = $options;
  344. $this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME');
  345. $this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX');
  346. $this->options['length'] = isset($options['length'])? $options['length'] : 0;
  347. $func = $options['persistent'] ? 'pconnect' : 'connect';
  348. $this->redis = new \Redis;
  349. $options['timeout'] === false ?
  350. $this->redis->$func($options['host'], $options['port']) :
  351. $this->redis->$func($options['host'], $options['port'], $options['timeout']);
  352. //添加redis 密码
  353. if(C('REDIS_AUTH')){
  354. $this->redis->auth(C('REDIS_AUTH'));
  355. }
  356. return $this->redis;
  357. }
  358. }