Charlie 9 years ago
parent
commit
1afd88d2ff

+ 1 - 0
www/protected/config/main.php

@@ -36,6 +36,7 @@ return array(
         //            ),
         'dataview',
         'common',
+        'api',
         'o2o',
     ),
 

+ 10 - 0
www/protected/modules/api/ApiModule.php

@@ -0,0 +1,10 @@
+<?php
+class ApiModule extends CWebModule
+{
+    public function init()
+    {
+        $this->setImport(array(
+            'api.controllers.*',
+        ));
+    }
+}

+ 266 - 0
www/protected/modules/api/controllers/ApiBaseController.php

@@ -0,0 +1,266 @@
+<?php
+/**
+ * api接口公共基类
+ */
+class ApiBaseController extends CController{
+
+    //api访问前进行签名验证
+    /**
+     * @return bool
+     */
+    protected function verify() {
+       if(!empty(Yii::app()->request->getParam('no_sign'))&&(YII_DEBUG == true)){
+           return true;
+       }
+       if(Yii::app()->request->getParam('app_client_id') == 1){
+            $this->check_version();
+        }
+       $result = $this->api_check_sign();
+       return $result;
+    }
+
+    //用户行为需要增加爪币,调用此方法
+    protected function addScore($user_id,$action){
+        $result = Service::factory('ScoreService')->syncScore($user_id,$action);
+        if($result){
+            $score_value = Service::factory('VariableService')->getVariable($action);
+            return array('status'=>true,'score'=>intval($score_value),'current_score'=>$result);
+        }else{
+            return array('status'=>false);
+        }
+    }
+
+    /**
+     * 增加用户活跃天数
+     * @param string $user_id
+     */
+    protected function addActive($user_id){
+        $cache = new ARedisCache();
+        $key = 'user_active_'.date('Ymd').$user_id;
+        $status = $cache->get($key);
+        if($status){
+            return false;
+        }else{
+            $cache->set($key,1,86400);
+            $list = new ARedisList('user_active_list');
+            $list->push($user_id);
+            return true;
+        }
+    }
+    
+
+    //判断用户是否是当日首次访问应用,可以将一些定期任务放入此方法内调用
+    protected function today_first_login($user_id){
+        $date = date('Ymd');
+        $Key = HelperKey::generateUserActionKey('login',$date,$user_id);
+        $status = UserActionRedis::get($Key);
+        if(!$status && !empty($user_id)){
+            UserActionRedis::set($Key,true);//设置用户状态为已签到
+            $syncData['user_id'] = $user_id;
+            $syncData['app_client_id'] = intval(Yii::app()->request->getParam('app_client_id'));
+            $syncData['device_id'] = Yii::app()->request->getParam('device_id');
+            $syncData['channel'] = Yii::app()->request->getParam('channel'); 
+            $syncData['app_version'] = Yii::app()->request->getParam('app_version'); 
+            $syncData['phone_type'] = Yii::app()->request->getParam('phone_type');
+            $syncData['os_version'] = Yii::app()->request->getParam('os_version');
+            $syncData['last_visit_time'] = time();
+            $list = new ARedisList('user_info_update');
+            $list->push(serialize($syncData));
+            $add_score = $this->addScore($user_id,'score_first_open');
+            if($add_score['status']){
+                return $add_score;
+            }
+        }
+    }
+
+    //所有访问者 记录资料信息  通过device_id
+    protected function log_visitor($request){
+        $mongo = new MongoClient(DB_CONNETC);
+        $device_id = CommonFn::get_val_if_isset($request,'device_id',"");
+        $os_version = CommonFn::get_val_if_isset($request,'os_version',"");
+
+        $api_version = CommonFn::get_val_if_isset($request,'api_version',"");
+        $app_version = CommonFn::get_val_if_isset($request,'app_version',"");
+        $phone_type = CommonFn::get_val_if_isset($request,'phone_type',"");
+
+        $user_id = CommonFn::get_val_if_isset($request,'user_id',"");
+        $channel = CommonFn::get_val_if_isset($request,'channel',"");
+        $app_client_id = CommonFn::get_val_if_isset($request,'app_client_id',"");
+        if(isset($request['city_info']) && $request['city_info']){
+            $city_info =  json_decode($request['city_info'],true);
+            //防止city_info出现非法数据
+            if(!isset($city_info['province'])){
+                $city_info['province'] = '';
+                $city_info['city'] = '';
+                $city_info['area'] = '';
+            }elseif(!isset($city_info['city'])){
+                $city_info['city'] = '';
+                $city_info['area'] = '';
+            }elseif(!isset($city_info['area'])){
+                $city_info['area'] = '';
+            }
+        }
+
+        if(isset($request['position']) && $request['position']){
+            $position_arr = json_decode($request['position'],true);
+            $position[0] = isset($position_arr['lng'])?floatval($position_arr['lng']):0;
+            $position[1] = isset($position_arr['lat'])?floatval($position_arr['lat']):0;
+        }
+
+        if($device_id){
+            $criteria = new EMongoCriteria();
+            $criteria->device_id('==',$device_id);
+            $visitor = Visitors::model()->find($criteria);
+            if($visitor){
+                $visitor->device_id = $device_id;
+                $visitor->os_version = $os_version;
+                $visitor->api_version = $api_version;
+                $visitor->time = time();
+                if(!isset($visitor->first_time) || !$visitor->first_time){
+                    $visitor->first_time = time();
+                }
+                $visitor->channel = $channel;
+                $visitor->app_version = $app_version;
+                $visitor->phone_type = $phone_type;
+                $visitor->user_id = $user_id;
+                $visitor->app_client_id = $app_client_id;
+                if(isset($city_info) && !empty($city_info)){
+                    $visitor->city_info = $city_info;
+                }
+                if(isset($position) && !empty($position)){
+                    $visitor->position = $position;
+                }
+                $visitor->update(array('device_id','os_version','api_version','first_time','time','channel','app_version','phone_type','user_id','app_client_id','city_info','position'));
+            }else{
+                $visitor = new Visitors();
+                $visitor->device_id = $device_id;
+                $visitor->os_version = $os_version;
+                $visitor->api_version = $api_version;
+                $visitor->time = time();
+                $visitor->first_time = time();
+                $visitor->channel = $channel;
+                $visitor->app_version = $app_version;
+                $visitor->phone_type = $phone_type;
+                $visitor->user_id = $user_id;
+                $visitor->app_client_id = $app_client_id;
+                if(isset($city_info) && !empty($city_info)){
+                    $visitor->city_info = $city_info;
+                }
+                if(isset($position) && !empty($position)){
+                    $visitor->position = $position;
+                }
+                $visitor->save();
+            }
+        }
+    }
+
+
+    //签名验证方法
+    //每次GET/POST请求的参数,凡是在这个列表以内的参数名字:["id","app_client_id","time","topic_id","group_id","user_id","post_id"]加上private_key按key字母升序排列拼接,然后md5运算之后生成
+    protected function api_check_sign(){
+        //return true;
+        $need_args=array('device_id','os_version','api_version','time','channel','app_client_id','app_version','sign');
+        $sign_args=array("id","app_client_id","time","topic_id","group_id","user_id","post_id","app_version");
+
+        $request=array();
+        if(is_array($_GET)){
+            foreach($_GET as $k=>$v){
+                $request[$k]=$v;
+            }
+        }
+        if(is_array($_POST)){
+            foreach($_POST as $k=>$v){
+                $request[$k]=$v;
+            }
+        }
+        $device_id = CommonFn::get_val_if_isset($request,'device_id',"");
+        $temp_args=array();
+        $sign='';
+        if(is_array($request)){
+            foreach($request as $_key => $_value) {
+                if($_key!='sign'){
+                    if(in_array($_key,$sign_args)){
+                        $temp_args[$_key]=$_value;
+                    }
+                }else{
+                    $sign = $_value;
+                }
+            }
+        }
+        if($sign){
+            if($request['app_client_id'] == 2){
+                $temp_args['private_key'] = Yii::app()->params['androidPrivateKey'];
+            }elseif($request['app_client_id'] == 1){
+                $temp_args['private_key'] = Yii::app()->params['iosPrivateKey'];
+            }else{
+                CommonFn::requestAjax(false,'签名验证失败');
+            }
+
+            if(isset($temp_args)&&!empty($temp_args)){
+                ksort($temp_args);
+            }
+            $arg_str='';
+            foreach($temp_args as $k=>$v){
+                if($arg_str==''){
+                    $arg_str .= $k.'='.$v;
+                }else{
+                    $arg_str .= '&'.$k.'='.$v;
+                }
+            }
+            $new_sign=md5($arg_str);
+            if($new_sign!=$sign){
+                CommonFn::requestAjax(false,'签名验证失败');
+            }
+        }else{
+            CommonFn::requestAjax(false,'签名验证失败');
+        }
+        return true;
+    }
+
+    public function syncPosition(){
+        $position_arr =  json_decode(Yii::app()->request->getParam('position'),true);
+        $position[0] = isset($position_arr['lng'])?floatval($position_arr['lng']):0;
+        $position[1] = isset($position_arr['lat'])?floatval($position_arr['lat']):0;
+        $user_id = Yii::app()->request->getParam('user_id','');
+        $city_info =  json_decode(Yii::app()->request->getParam('city_info'),true);
+        if($user_id && ($city_info || $position[0])){
+            $user_obj = RUser::get(new MongoId($user_id));
+            if($user_obj && (!isset($user_obj->position[0]) || !$user_obj->position[0])){
+                $user_obj->city_info = $city_info;
+                $user_obj->position = $position;
+                $user_obj->update(array('city_info','position'),true);
+            }
+        }
+    }
+
+    public function check_version(){
+        $version = Yii::app()->request->getParam('app_version');
+        $app_client_id = Yii::app()->request->getParam('app_client_id');
+        if(Yii::app()->request->getParam('no_sign')){
+            return true;
+        }
+        if( empty($version)||empty($app_client_id)){
+            CommonFn::requestAjax(false,CommonFn::getMessage('message','request_illegal'));
+        }
+        if($app_client_id == 2){
+            $limit_version = Yii::app()->params['android_latest_version'];
+            $leatest_version = Service::factory('VariableService')->getVariable('android_new_version');
+        }elseif($app_client_id == 1){
+            $limit_version = Yii::app()->params['ios_latest_version'];
+            $leatest_version = Service::factory('VariableService')->getVariable('ios_new_version');
+        }else{
+            CommonFn::requestAjax(false,CommonFn::getMessage('message','request_illegal'));
+        }
+        if(!CommonFn::compareVersion(Yii::app()->request->getParam('app_version',''),$limit_version)){
+            if($app_client_id == 2){
+                $download_url = 'http://7xjqyz.com5.z0.glb.clouddn.com/wozhua_guanwang.apk';
+                $info = array('new_version'=>$leatest_version,'download'=>$download_url);
+            }else{
+                $info = array('new_version'=>$leatest_version);
+            }
+            CommonFn::requestAjax(true,CommonFn::getMessage('message', 'have_newer'),$info,203);
+        }
+    }
+
+
+}

+ 619 - 0
www/protected/modules/api/controllers/CommonController.php

@@ -0,0 +1,619 @@
+<?php
+/**
+ * 公用API
+ */
+class CommonController extends ApiBaseController {
+    public function beforeAction($action){
+        $weixin_use = array('staticsource','getsubcity', 'getallcity');
+        if(in_array(strtolower($action->id),$weixin_use)){
+            return true;
+        }
+        return $this->verify();
+    }
+    public function actionDiscover(){
+        $page = intval(Yii::app()->getRequest()->getParam("page",1));
+        $page = $page?$page:1;
+        $type = Yii::app()->request->getParam('type','');
+        $user_id = Yii::app()->request->getParam('user_id','');
+        $device_id = Yii::app()->request->getParam('device_id','');
+        if($type == 'digest'){
+            $city_info =  json_decode(Yii::app()->request->getParam('city_info'),true);
+            //防止city_info出现非法数据
+            if(!isset($city_info['province'])){
+                $city_info['province'] = '';
+                $city_info['city'] = '';
+                $city_info['area'] = '';
+            }elseif(!isset($city_info['city'])){
+                $city_info['city'] = '';
+                $city_info['area'] = '';
+            }elseif(!isset($city_info['area'])){
+                $city_info['area'] = '';
+            }
+            $z_User = new ZUser();
+            $user = $z_User->idExist($user_id);
+            $z_group = new ZGroup();
+            $res_topics = array();
+            $actiontime = CommonFn::getFirstTime(ActionTimeRedis::TYPE_GET_INDEX,$device_id,$page);
+            $_user = null;
+            if($user){
+                $_user = $user['_id'];
+            }
+            $picked_groups = $z_group->get_user_picked_groups($_user,$city_info,false,true);
+            $picked_groups = $z_group->filter_special($picked_groups);
+            $parsed_groups = array();
+            foreach($picked_groups as $picked_group){
+                $parsed_groups[] = new MongoId($picked_group['_id']);
+            }
+            $pagesize = Yii::app()->params['indexPageSize'];
+            $conditions = array(
+                                            'group'=>array('in',$parsed_groups),
+                                            'status'=>array('==',1),
+                                            'time'=>array('<=',$actiontime)
+                                        );
+            $order = array(
+                'time'=>'desc',
+            );
+            $model = new Topic();
+            $pagedata = CommonFn::getPagedata($model,$page,$pagesize,$conditions,$order,false,false);
+            $topics = $pagedata['res'];
+            foreach($topics as $topic){
+                $_topic = $model->parseRow($topic,array('id','content','city_info','time','time_str','group','visit_count','reply_count','fav_count','like_count','user','pics','voice','video','last_post_time','last_post_time_str'));
+                if($user){
+                    $z_like = new ZLike();
+                    $like = $z_like->getLikeByLikeObj((string)$user['_id'],$_topic['id']);
+                    if(empty($like)){
+                        $_topic['is_liked'] = false;
+                    }else{
+                        $_topic['is_liked'] = true;
+                    }
+                }else{
+                    $_topic['is_liked'] = false;
+                }
+                $res_topics[] = $_topic;
+            }
+            CommonFn::requestAjax(true,'',$res_topics,200,array('sum_count' => $pagedata['sum_count'],'sum_page'=>$pagedata['sum_page'],'page_size'=>$pagedata['page_size'],'current_page'=>$pagedata['current_page'])); 
+        }else{
+            
+        }
+
+    }
+
+    //推荐帖子
+    public function actionIndex(){
+        $page = intval(Yii::app()->getRequest()->getParam("page",1));
+        $city_info =  json_decode(Yii::app()->request->getParam('city_info'),true);
+        if(empty($page)){
+            $page = 1;
+        }
+        $user_id = Yii::app()->request->getParam('user_id','');
+        $device_id = Yii::app()->request->getParam('device_id','');
+        //防止city_info出现非法数据
+        if(!isset($city_info['province'])){
+            $city_info['province'] = '';
+            $city_info['city'] = '';
+            $city_info['area'] = '';
+        }elseif(!isset($city_info['city'])){
+            $city_info['city'] = '';
+            $city_info['area'] = '';
+        }elseif(!isset($city_info['area'])){
+            $city_info['area'] = '';
+        }
+        $z_User = new ZUser();
+        $user = $z_User->idExist($user_id);
+        $z_group = new ZGroup();
+        $z_topic = new ZTopic();
+        $arr = array();
+        $actiontime = CommonFn::getFirstTime(ActionTimeRedis::TYPE_GET_INDEX,$device_id,$page);
+        $_user = null;
+        if($user){
+            $_user = $user['_id'];
+        }
+        $picked_groups = $z_group->get_user_picked_groups($_user,$city_info,false,true);
+        $picked_groups = $z_group->filter_special($picked_groups);
+        $parsed_groups = array();
+        foreach($picked_groups as $picked_group){
+            $parsed_groups[] = new MongoId($picked_group['_id']);
+        }
+        $pagesize = Yii::app()->params['indexPageSize'];
+        $conditions = array(
+                                        'group'=>array('in',$parsed_groups),
+                                        'status'=>array('==',1),
+                                        'time'=>array('<=',$actiontime)
+                                    );
+        $order = array(
+            'time'=>'desc',
+        );
+        $model = new Topic();
+        $pagedata = CommonFn::getPagedata($model,$page,$pagesize,$conditions,$order,false,false);
+        $topics = $pagedata['res'];
+        $front_topic_user = '';
+        $last_topics = array();
+        foreach($topics as $topic){
+            $_topic = $model->parseRow($topic,array('id','content','city_info','time','time_str','group','visit_count','reply_count','fav_count','like_count','user','pics','voice','video','last_post_time','last_post_time_str'));
+            if($user){
+                $z_like = new ZLike();
+                $like = $z_like->getLikeByLikeObj((string)$user['_id'],$_topic['id']);
+                if(empty($like)){
+                    $_topic['is_liked'] = false;
+                }else{
+                    $_topic['is_liked'] = true;
+                }
+            }else{
+                $_topic['is_liked'] = false;
+            }
+            if($_topic['user']['id'] == $front_topic_user){
+                $last_topics[] = array('type'=>'topic','item'=>$_topic);
+            }else{
+                $front_topic_user = $_topic['user']['id'];
+                $arr[] = array('type'=>'topic','item'=>$_topic);
+            }
+        }
+        $arr = array_merge($arr,$last_topics);
+        CommonFn::requestAjax(true,'',$arr,200,array('sum_count' => $pagedata['sum_count'],'sum_page'=>$pagedata['sum_page'],'page_size'=>$pagedata['page_size'],'current_page'=>$pagedata['current_page'])); 
+    }
+
+    //首页轮播的图
+    public function actionSlide(){
+        $city_info =  json_decode(Yii::app()->request->getParam('city_info'),true);
+        $city_info_pro = isset($city_info['province'])?$city_info['province']:'';
+        $criteria = new EMongoCriteria();
+        $criteria->status('==', 1);
+        if(CommonFn::compareVersion('2.7.2',Yii::app()->request->getParam('app_version',''))){
+            $criteria->type('!=','subject');
+        }
+        $criteria->sort('order', EMongoCriteria::SORT_DESC);
+        $cursor = Slide::model()->findAll($criteria);
+        $rows = CommonFn::getRows($cursor); 
+        foreach ($rows as $key => $value) {
+            if(isset($value['city_info'])&&isset($value['city_info']['province'])&&$value['city_info']['province']!=$city_info_pro&&$value['city_info']['province']!=''){
+                unset($rows[$key]);
+            }elseif(isset($value['end_time'])&&$value['end_time']<=time()&&$value['end_time']!==0&&!empty($value['end_time'])){
+                unset($rows[$key]);
+            }
+        }
+
+        $parsedRows = Slide::model()->parse($rows);
+        $parsedRows = array_values($parsedRows);
+        CommonFn::requestAjax(true,'',$parsedRows);
+    }
+
+
+
+    //积分规则
+    public function actionScoreRule(){
+        $score_rule = Yii::app()->params['score_rule'];
+        $data = array();
+        foreach ($score_rule as $value) {
+            $data[] = $value;
+        }
+        CommonFn::requestAjax(true,'',$data);
+    }
+
+    //发帖选择圈子接口
+    public function actionTopicGroupList(){
+        $user_id = Yii::app()->request->getParam('user_id');
+        if(!CommonFn::isMongoId($user_id)){
+            CommonFn::requestAjax(false,CommonFn::getMessage('message','params_illegal'));
+        }
+        $user = RUser::get(new MongoId($user_id));
+        if(!$user){
+            CommonFn::requestAjax(false,CommonFn::getMessage('message','params_illegal'));
+        }
+        $follow_groups = $user->groups;
+        $criteria = new EMongoCriteria();
+        $criteria->can_topic('==',1);
+        $criteria->status('==',1);
+        $criteria->sort('order', EMongoCriteria::SORT_DESC);
+        $cursor = Group::model()->findAll($criteria);
+        $first_section = array();
+        $second_section = array();
+        foreach ($cursor as $key => $value) {
+            if(in_array((string)$value->_id,$follow_groups)){
+                $first_section[] = array('id'=>(string)$value->_id,'name'=>(string)$value->name,'avatar'=>$value->avatar);
+            }elseif(!isset($value->city_info['city']) || empty($value->city_info['city']) || (isset($user->city_info['city']) && $value->city_info['city'] == $user->city_info['city'])){
+                $second_section[] = array('id'=>(string)$value->_id,'name'=>(string)$value->name,'avatar'=>$value->avatar);
+            }
+        }
+        $group_list = array_merge($first_section,$second_section);
+        CommonFn::requestAjax(true,'success',array('group_list'=>$group_list));
+    }
+
+    //客户端手动更新
+    public function actionUpdateApp(){
+        $version = Yii::app()->request->getParam('app_version');
+        $app_client_id = Yii::app()->request->getParam('app_client_id');
+        $channel = Yii::app()->request->getParam('channel','');
+        $network_type = Yii::app()->request->getParam('network_type','');
+        if(empty($version)||empty($app_client_id)){
+            CommonFn::requestAjax(false,CommonFn::getMessage('message','request_illegal'));
+        }
+        if($app_client_id == 2){
+            $leatest_version = Service::factory('VariableService')->getVariable('android_new_version');
+        }elseif($app_client_id == 1){
+            $leatest_version = Service::factory('VariableService')->getVariable('ios_new_version');
+        }else{
+            CommonFn::requestAjax(false,CommonFn::getMessage('message','request_illegal'));
+        }
+        if($network_type == 'wifi' && CommonFn::compareVersion($leatest_version,Yii::app()->request->getParam('app_version',''))){
+            if($app_client_id == 2){
+                $channel_apk = Yii::app()->params['channel_apk'];
+                if(isset($channel_apk[$channel])){
+                    $download_url = $channel_apk[$channel];
+                }else{
+                    $download_url = $channel_apk['guanwang'];
+                }
+                $info = array('new_version'=>$leatest_version,'size' => '34M','download'=>$download_url,'message'=>'新爪爪出来咯,快来找我玩≧△≦');
+            }else{
+                $info = array('new_version'=>$leatest_version,'message'=>'新爪爪出来咯,快来找我玩≧△≦');
+            }
+            CommonFn::requestAjax(true,CommonFn::getMessage('message', 'have_newer'),$info);
+        }else{
+            CommonFn::requestAjax(false,'');
+        }
+    }
+
+    //获取全部的城市信息
+    public function actionGetAllCity(){
+        $criteria = new EMongoCriteria();
+        $criteria->sort('parent_province_id', EMongoCriteria::SORT_ASC);
+        $criteria->sort('parent_city_id', EMongoCriteria::SORT_ASC);
+        $cursor = CityLib::model()->findAll($criteria);
+        $res = CommonFn::getRowsFromCursor($cursor);
+        $province = array();
+        $city = array();
+        $area = array();
+        $keyMap = array();
+        foreach ($res as $item) {
+            $keyMap[$item['_id']] = $item['name'];
+        }
+        foreach ($res as $item) {
+            $parent = $item['parent_area_id'];
+            $level = 4;
+            if ($parent == 0) {
+                $parent = $item['parent_city_id'];
+                $level = 3;
+            }
+            if ($parent == 0) {
+                $parent = $item['parent_province_id'];
+                $level = 2;
+            }
+            if ($parent == 0) {
+                $level = 1;
+            }
+            if ($level == 1) {
+                $province[] = $item['name'];
+            } else if ($level == 2) {
+                $city[$keyMap[$item['parent_province_id']]][] = $item['name'];
+            } else if ($level == 3) {
+                $area[$keyMap[$item['parent_city_id']]][] = $item['name'];
+            }
+        }
+        $data = array('p' => $province, 'c' => $city, 'a' => $area);
+
+        CommonFn::requestAjax(true, CommonFn::getMessage('message', 'operation_success'), $data, 200);
+    }
+
+    //获取城市级联信息
+    public function actionGetSubCity(){
+        $address_info =  json_decode(Yii::app()->request->getParam('address_info'),true);
+        if(!isset($address_info['province']) || $address_info['province'] == '未知'){
+            $address_info = array();
+        }
+        $province = array();
+        $city = array();
+        $area = array();
+        $z_citylib = new ZCityLib();
+        if(isset($address_info['province'])&&$address_info['province']){
+            $province = $z_citylib->getSubCity(1);
+            foreach ($province as $key => $value) {
+                if($value['name'] == $address_info['province']){
+                    $province[$key]['is_selected'] = 1;
+                    $city = $z_citylib->getSubCity($value['city_code']);
+                    foreach ($city as $sub_key => $sub_value) {
+                        if(isset($address_info['city']) && $sub_value['name'] == $address_info['city']){
+                            $have_selected = true;
+                            $city[$sub_key]['is_selected'] = 1;
+                            $area = $z_citylib->getSubCity($sub_value['city_code']);
+                            foreach ($area as $grand_key => $grand_value) {
+                                if($grand_value['name'] == $address_info['area']){
+                                    $area[$grand_key]['is_selected'] = 1;
+                                }else{
+                                    $area[$grand_key]['is_selected'] = 0; 
+                                }
+                            }
+                        }else{
+                            $city[$sub_key]['is_selected'] = 0;
+                        }
+                    }
+                    if(!isset($have_selected)){
+                        $city[0]['is_selected'] = 1;
+                        $area = $z_citylib->getSubCity($city[0]['city_code']);
+                        foreach ($area as $grand_key => $grand_value) {
+                            if($grand_key == 0){
+                                $area[$grand_key]['is_selected'] = 1;
+                            }else{
+                                $area[$grand_key]['is_selected'] = 0; 
+                            }
+                        }
+                    }
+                }else{
+                    $province[$key]['is_selected'] = 0;
+                }
+            }
+        }else{
+            $province = $z_citylib->getSubCity(1);
+            foreach ($province as $key => $value) {
+                if($value['name'] == '上海市'){
+                    $province[$key]['is_selected'] = 1;
+                }else{
+                    $province[$key]['is_selected'] = 0;
+                }
+            }
+            foreach ($province as $key => $value) {
+                if($value['name'] == '上海市'){
+                    $city = $z_citylib->getSubCity($value['city_code']);
+                    foreach ($city as $sub_key => $sub_value) {
+                        if($sub_value['name'] == '上海市'){
+                            $city[$sub_key]['is_selected'] = 1;
+                        }else{
+                            $city[$sub_key]['is_selected'] = 0;
+                        }
+                    }
+                    $area = $z_citylib->getSubCity($city[0]['city_code']);
+                    foreach ($area as $sub_key => $sub_value) {
+                        if($sub_value['name'] == '上海市'){
+                            $area[$sub_key]['is_selected'] = 1;
+                        }else{
+                            $area[$sub_key]['is_selected'] = 0;
+                        }
+                    }
+                }
+            }
+        }
+        //容错处理,防止客户端上传错误城市
+        if(empty($province)){
+            $province = $z_citylib->getSubCity(1);
+            foreach ($province as $key => $value) {
+                if($value['name'] == '上海市'){
+                    $province[$key]['is_selected'] = 1;
+                }else{
+                    $province[$key]['is_selected'] = 0;
+                }
+            }
+        }
+        if(empty($city)){
+            foreach ($province as $key => $value) {
+                if($value['is_selected'] == 1){
+                    $temp_code = $value['city_code'];
+                }
+            }
+            $city = $z_citylib->getSubCity($temp_code);
+            if(empty($city)){
+                $temp['name'] = ''; 
+                $city[] = $temp;
+            }
+            $city[0]['is_selected'] = 1;
+        }
+        if(empty($area)){
+            foreach ($city as $key => $value) {
+                if($value['is_selected'] == 1){
+                    $temp_code = $value['city_code'];
+                }
+            }
+            $area = $z_citylib->getSubCity($temp_code);
+            if(empty($area)){
+                $temp['name'] = ''; 
+                $area[] = $temp;
+            }
+            $area[0]['is_selected'] = 1;
+        }
+        foreach ($province as $key => $value) {
+            unset($province[$key]['city_code']);
+        }
+        foreach ($city as $key => $value) {
+            unset($city[$key]['city_code']);
+        }
+        foreach ($area as $key => $value) {
+            unset($area[$key]['city_code']);
+        }
+        $data['provinces'] = $province;
+        $data['citys'] = $city;
+        $data['areas'] = $area;      
+        CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data,200);
+    }
+
+    public function actionPay(){
+        $pay_channel = Yii::app()->getRequest()->getParam("pay_channel");
+        $order_id = Yii::app()->getRequest()->getParam("order_id");
+        $callback = Yii::app()->getRequest()->getParam("callback");
+        $amount = 1;
+        $result = Service::factory('PayService')->Pay($pay_channel,$amount);
+        if($callback){
+            echo $callback."($result)";
+            die();
+        }
+        echo $result;
+    }
+
+    public function actionRetrieve(){
+        $charge_id = Yii::app()->getRequest()->getParam("charge_id");
+        $result = Service::factory('PayService')->retrieve($charge_id);
+        echo $result;
+    }
+
+    public function actionInit(){
+        $cache = new ARedisCache();
+        $key = 'data_cache_common_init';
+        $data_cache = $cache->get($key);
+        $data = array();
+        if($data_cache){
+            $data = unserialize($data_cache);
+        }else{
+            $host = ENVIRONMENT=='product'?'www.wozhua.mobi':'wwwtest.wozhua.mobi';
+            $hot_keys = trim(Service::factory('VariableService')->getVariable('hot_keywords'));
+            $hot_keys = explode("\n",$hot_keys);
+            $criteria = new EMongoCriteria();
+            $criteria->time('<=',time());
+            $criteria->limit(1);
+            $criteria->sort('time',EMongoCriteria::SORT_DESC);
+            $r_card = RecommendCard::model()->findAll($criteria);
+            $new_card_time = 0;
+            foreach ($r_card as $key => $value) {
+                $new_card_time = $value->time;
+                break;
+            }
+            $subject = new Subject();
+            $criteria = new EMongoCriteria();
+            $criteria->is_recommend('==', 1);
+            $criteria->sort('rank',EMongoCriteria::SORT_DESC);
+            $criteria->status('==', 1);
+            $criteria->limit(8);
+            $res = $subject->findAll($criteria);
+            $data['recommend_subject'] = array_values($subject->parse($res));
+            $data['limit_conf'] = Yii::app()->params['limit_conf'];
+            $data['new_user_coupons_value'] = Yii::app()->params['new_user_coupons_value']?Yii::app()->params['new_user_coupons_value']:0;
+            $data['app_video_conf'] = Yii::app()->params['app_video_conf'];
+            $data['new_card_time'] = $new_card_time;
+            $data['hot_keywords'] = $hot_keys;
+            $data['report_reason'] = Yii::app()->params['report_reason'];
+            $data['certify_url'] = isset(Yii::app()->params['certify_url'])?Yii::app()->params['certify_url']:'';
+            $data['tool_box_url'] = 'http://www.wozhua.mobi/webapp/pet';
+            $data['deal_url'] = 'http://'.$host.'/o2o/web/index/deal?need_header=0';
+            $pic_edit = Service::factory('VariableService')->getVariable('pic_edit');
+            $data['pic_edit'] = intval($pic_edit);
+            $data['topic_report_reason'] = Yii::app()->params['topic_report_reason'];
+            $data['user_report_reason'] = Yii::app()->params['user_report_reason'];
+            $data['kefu_user'] = Yii::app()->params['kefu_user'];
+            $data['enable_clear_cache'] = 0;
+            $updata_message = array('title'=>'有新版本发布了','content' => CommonFn::getMessage('message','have_newer'));
+            $data['updata_message'] = $updata_message;
+            $cache->set($key,serialize($data),300);
+        }
+        $close_versions = explode(',',Service::factory('VariableService')->getVariable('close_versions'));
+        if( in_array(Yii::app()->request->getParam('app_version',''),$close_versions)){
+            $data['foreign_link_open'] = 0;
+            $data['lottery_open'] = 0;
+        }else{
+            $data['lottery_open'] = 1;
+            $data['foreign_link_open'] = 1;
+        }
+        $data['enable_clear_cache'] = 1;
+        $data['certify_type'] = Yii::app()->params['new_certify_type'];
+        //最新版本
+        $app_client_id = Yii::app()->request->getParam('app_client_id');
+        $leatest_version = '';
+        if($app_client_id == 2){
+            $leatest_version = Service::factory('VariableService')->getVariable('android_new_version');
+        }elseif($app_client_id == 1){
+            $leatest_version = Service::factory('VariableService')->getVariable('ios_new_version');
+        }
+        $data['new_app_version'] = $leatest_version;
+        CommonFn::requestAjax(true,'',$data);
+    }
+
+    public function actionGetUrl(){
+        $url_id = Yii::app()->getRequest()->getParam("url_id");
+        $data['url'] = Service::factory('VariableService')->getVariable($url_id);
+        $success = empty($data) ? false : true;
+        $message = $success ? '' : 'URL不存在';
+        CommonFn::requestAjax($success, $message, $data);
+    }
+
+    public function actionReport() {
+        $user   = Yii::app()->request->getParam('user_id', '');
+        $reason = Yii::app()->request->getParam('reason', '');
+        $time   = time();
+
+        $to_user_id  = Yii::app()->request->getParam('to_user_id', '');
+        $topic_id    = Yii::app()->request->getParam('topic_id', '');
+
+        if ((empty($to_user_id) && empty($topic_id))                // 举报对象
+            || empty($user) || empty($reason)) {                    // 举报用户和理由
+            CommonFn::requestAjax(false, '参数不全', array());
+        }
+
+        $type      = empty($to_user_id) ? 'topic' : 'user';
+        $object    = empty($to_user_id) ? $topic_id : $to_user_id;
+        $object_id = new MongoId($object);
+        $user_id   = new MongoId($user);
+        $reports   = Report::getByUser($user_id, $object_id);
+        if ($reports != false) {
+            $reports->next();
+            $report = $reports->current();
+            if ($report->status == 0) {
+                CommonFn::requestAjax(false, '已经举报过了哦', array());
+            }
+        }
+
+        $report = new Report();
+        $report->type   = $type;
+        $report->object = $object_id;
+        $report->user   = $user_id;
+        $report->reason = $reason;
+        $report->time   = $time;
+
+        $success = $report->insert();
+        $message = $success ? '举报成功' : '举报失败';
+        CommonFn::requestAjax($success, $message, array());
+    }
+
+    public function actionCustomeParam() {
+        $user_id   = Yii::app()->request->getParam('user_id', '');
+        $device_id = Yii::app()->request->getParam('device_id');
+        $data['new_user_coupons_value'] = Yii::app()->params['new_user_coupons_value']?Yii::app()->params['new_user_coupons_value']:0;
+        if($user_id){
+            $cache = new ARedisCache();
+            $key = 'new_user_coupons_check'.$user_id;
+            $new_user_coupons_check = $cache->get($key);
+            if(!$new_user_coupons_check){
+                if(CommonFn::isMongoId($user_id)){
+                    $user_id = new MongoId($user_id);
+                    $criteria = new EMongoCriteria();
+                    $criteria->user('==',$user_id);
+                    $coupons = UserCoupon::model()->count($criteria);
+                    if($coupons<1){
+                        $data['get_user_coupons'] = 1;
+                    }else{
+                        $data['get_user_coupons'] = 0;
+                    }
+                }else{
+                    $data['get_user_coupons'] = 0;
+                }
+            }else{
+                $data['get_user_coupons'] = 0;
+            }
+        }elseif ($device_id) {
+            $cache = new ARedisCache();
+            $key = 'new_user_coupons_check'.$device_id;
+            $new_user_coupons_check = $cache->get($key);
+            if(!$new_user_coupons_check){
+                $criteria = new EMongoCriteria();
+                $criteria->user_device_id('==',$device_id);
+                $coupons = UserCoupon::model()->count($criteria);
+                if($coupons<1){
+                    $data['get_user_coupons'] = 1;
+                }else{
+                    $data['get_user_coupons'] = 0;
+                }
+            }
+        }else{
+            $data['get_user_coupons'] = 0;
+        }
+        CommonFn::requestAjax(true,'success', $data);
+    }
+
+    public function actionStaticSource() {
+        $key = Yii::app()->request->getParam('key');
+        $static = StaticSource::getByKey($key);
+        if (!$static) {
+            CommonFn::requestAjax(false, '资源不存在', []);
+        } else {
+            CommonFn::requestAjax(true, '', [
+                'id' => (string)$static->_id,
+                'key' => $static->key,
+                'title' => $static->title? $static->title : '',
+                'content' => $static->content,
+            ]);
+        }
+    }
+}

+ 361 - 0
www/protected/modules/api/controllers/IndexController.php

@@ -0,0 +1,361 @@
+<?php
+/**
+ * 应用首页接口,后面可能根据不同版本独立
+ */
+class IndexController extends ApiBaseController {
+
+    public function beforeAction($action){
+        // $weixin_use = array('staticSource');
+        // if(Yii::app()->getRequest()->getParam("request_from") == 'weixin' && in_array($action->id,$weixin_use)){
+        //     return true;
+        // }
+
+        //todo user first login
+        return $this->verify();
+    }
+
+    public function actionV3(){
+        //根据自定义参数生成缓存key
+        $user_id = Yii::app()->request->getParam('user_id','');
+        $device_id = Yii::app()->request->getParam('device_id','0');
+        $city_info =  json_decode(Yii::app()->request->getParam('city_info'),true);
+        $province = isset($city_info['province'])?$city_info['province']:'';
+        $position_city_info =  json_decode(Yii::app()->request->getParam('position_city_info'),true);
+        $position_province = isset($position_city_info['province'])?$position_city_info['province']:'';
+        $get_new = Yii::app()->request->getParam('get_new',0);
+        $z_User = new ZUser();
+        $host = ENVIRONMENT=='product'?'www.wozhua.mobi':'wwwtest.wozhua.mobi';
+        $f_host = ENVIRONMENT=='product'?'f.wozhua.mobi':'ftest.wozhua.mobi';
+        $user = $z_User->idExist($user_id);
+        //$new_user_coupons = 0;
+        $no_recommond_groups = Yii::app()->params['no_recommond_groups'];
+        //登陆用户根据上次访问时间,关注圈子,页数,当前时间生成唯一key
+        if($user){
+            $add_score = $this->today_first_login($user_id);
+            $last_visit_hours = CommonFn::get_user_last_visit_hours($user['last_visit_time']);
+            $group_ids = $user['groups'];
+            $sort_group = array();
+            foreach ($group_ids as $key => $value) {
+                $sort_group[] = (string)$value;
+            }
+            sort($sort_group);
+            $stamp = '3';
+            foreach ($sort_group as $key => $value) {
+                $stamp.=$value;
+            }
+            $cache_key = md5($stamp.$last_visit_hours.$get_new);
+        //未登录用户根据页数,默认获取推荐关注圈子七天内帖子
+        }elseif($device_id){
+            $cache = new ARedisCache();
+            $key = 'guest_last_visit_time_'.$device_id;
+            $guest_last_visit_time = $cache->get($key);
+            if($guest_last_visit_time){
+                $last_visit_hours = CommonFn::get_user_last_visit_hours($guest_last_visit_time);
+            }else{
+                $last_visit_hours = 168;
+            }
+            $cache->set($key,time());
+            //未登录用户获取获取推荐的圈子
+            $default_follow_group = Service::factory('VariableService')->getVariable('default_follow_group');
+            $groups =  explode(',',trim($default_follow_group,','));
+            if(isset($city_info['province'])){
+                $criteria = new EMongoCriteria();
+                $criteria->status('==',1);
+                $criteria->addCond('city_info.province','==',$city_info['province']);
+                $cursor = Group::model()->findAll($criteria);
+                foreach ($cursor as $value) {
+                    $groups[] = (string)$value->_id;
+                }
+            }
+            $stamp = '3';
+            foreach ($groups as $key => $value) {
+                if(!CommonFn::isMongoId($value)){
+                    unset($groups[$key]);
+                    continue;
+                }
+                $groups[$key] = new MongoId($value);
+                $stamp.=$value;
+            }
+            $group_ids = array_values($groups);
+            $cache_key = md5($stamp.$last_visit_hours.$get_new);
+        }else{
+            $default_follow_group = Service::factory('VariableService')->getVariable('default_follow_group');
+            $groups =  explode(',',trim($default_follow_group,','));
+            $stamp = '3';
+            foreach ($groups as $key => $value) {
+                if(!CommonFn::isMongoId($value)){
+                    unset($groups[$key]);
+                    continue;
+                }
+                $groups[$key] = new MongoId($value);
+                $stamp.=$value;
+            }
+            $group_ids = array_values($groups);
+            $last_visit_hours = 168;
+            $cache_key = md5($stamp.$last_visit_hours.$get_new);
+        }
+        foreach ($group_ids as $key => $value) {
+            if(in_array((string)$value,$no_recommond_groups)){
+                unset($group_ids[$key]);
+            }
+        }
+        $group_ids = array_values($group_ids);
+        $cache = new ARedisCache();
+        $cache_data = $cache->get($cache_key);
+        if($cache_data && !YII_DEBUG){
+            $cache_res = unserialize($cache_data);
+            $data = $cache_res['data'];
+        }else{
+            //按钮链接
+            $link_button[] = array(
+                    'title'=>'买宠物',
+                    'link_text'=>'有保障/大礼包',
+                    'icon_url'=>'http://7oxep6.com1.z0.glb.clouddn.com/huotijiaoyi.png',
+                    'link'=>'http://'.$host.'/o2o/web/index/deal?need_header=0'
+                );
+            $link_button[] = array(
+                    'title'=>'问专家',
+                    'link_text'=>'看病/训犬/养护',
+                    'icon_url'=>'http://7oxep6.com1.z0.glb.clouddn.com/doctorhij.png',
+                    'link'=>'http://'.$host.'/group/54a0fa1f0eb9fb17308b47a6'
+                );
+            $data['link_button'] = $link_button;
+
+            //活体交易部分
+            $deal['type'] = 'deal';
+            $deal['title'] = '放心、有保障的宠物交易';
+            $deal['more'] = 'http://'.$host.'/o2o/web/index/deal?need_header=0';
+            //todo pettype
+            $new_pets = DealPet::getNewPet();
+            foreach ($new_pets as $key => $value) {
+                $new_pets[$key]['url'] = 'http://'.$host.'/o2o/web/index/deal?need_header=0/#!/detail/'.$value['id'];
+            }
+            $deal['pets'] = $new_pets;
+            $data['modules'][] = $deal;
+
+            $res_topics = array();
+            $conditions = array(    
+                                    'group'=>array('in',$group_ids),
+                                    'status'=>array('==',1),
+                                    'time'=>array('>=',time()-3600*$last_visit_hours)
+                                );
+            //最新最热帖排序规则
+            $order = $get_new?['_id'=>'desc']:['like_count'=>'desc'];
+            $model = new Topic();
+            $pagedata = CommonFn::getPagedata($model,1,20,$conditions,$order,false);
+            $topics = $pagedata['res'];
+            foreach($topics as $topic){
+                $_topic = $model->parseRow($topic,array('id','content','city_info','city_info_str','city_topic_str','time','time_str','group','visit_count','reply_count','fav_count','like_count','user','pics','voice','video','last_post_time','last_post_time_str'));
+                if($user){
+                    $z_like = new ZLike();
+                    $like = $z_like->getLikeByLikeObj((string)$user['_id'],$_topic['id']);
+                    if(empty($like)){
+                        $_topic['is_liked'] = false;
+                    }else{
+                        $_topic['is_liked'] = true;
+                    }
+                }else{
+                    $_topic['is_liked'] = false;
+                }
+                $res_topics[] = $_topic;
+            }
+            $data['topics'] = $res_topics;
+            $cache_data = array();
+            $cache_data['data'] = $data;
+            $cache->set($cache_key,serialize($cache_data),3600);
+        }
+        //首页轮播图
+        $province_tag = isset($city_info['province'])?$city_info['province']:'no';
+        $slide = Slide::getIndexSlide($province_tag);
+        $data['slide'] = $slide;
+        if(isset($add_score['status'])){
+            $score_info['score_change'] = $add_score['score'];
+            $score_info['current_score'] = $add_score['current_score'];
+            $score_info['score_type'] = '签到';
+            CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data,303,$score_info);
+        }else{
+            CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data,200,array('last_visit_hours' =>$last_visit_hours));
+        }
+    }
+
+    public function actionV4(){
+        //根据自定义参数生成缓存key
+        $user_id = Yii::app()->request->getParam('user_id','');
+        $device_id = Yii::app()->request->getParam('device_id','0');
+        $page = intval(Yii::app()->request->getParam('page',1));
+        $city_info =  json_decode(Yii::app()->request->getParam('city_info'),true);
+        $province = isset($city_info['province'])?$city_info['province']:'';
+        $position_city_info =  json_decode(Yii::app()->request->getParam('position_city_info'),true);
+        $position_province = isset($position_city_info['province'])?$position_city_info['province']:'';
+        $get_new = Yii::app()->request->getParam('get_new',0);
+        $z_User = new ZUser();
+        $host = ENVIRONMENT=='product'?'www.wozhua.mobi':'wwwtest.wozhua.mobi';
+        $f_host = ENVIRONMENT=='product'?'f.wozhua.mobi':'ftest.wozhua.mobi';
+        $user = $z_User->idExist($user_id);
+        //$new_user_coupons = 0;
+        $no_recommond_groups = Yii::app()->params['no_recommond_groups'];
+        //登陆用户根据上次访问时间,关注圈子,页数,当前时间生成唯一key
+        if($user){
+            $add_score = $this->today_first_login($user_id);
+            $last_visit_hours = CommonFn::get_user_last_visit_hours($user['last_visit_time']);
+            $group_ids = $user['groups'];
+            $sort_group = array();
+            foreach ($group_ids as $key => $value) {
+                $sort_group[] = (string)$value;
+            }
+            sort($sort_group);
+            $stamp = '3';
+            foreach ($sort_group as $key => $value) {
+                $stamp.=$value;
+            }
+            $cache_key = md5($stamp.$last_visit_hours.$get_new);
+        //未登录用户根据页数,默认获取推荐关注圈子七天内帖子
+        }elseif($device_id){
+            $cache = new ARedisCache();
+            $key = 'guest_last_visit_time_'.$device_id;
+            $guest_last_visit_time = $cache->get($key);
+            if($guest_last_visit_time){
+                $last_visit_hours = CommonFn::get_user_last_visit_hours($guest_last_visit_time);
+            }else{
+                $last_visit_hours = 168;
+            }
+            $cache->set($key,time());
+            //未登录用户获取获取推荐的圈子
+            $default_follow_group = Service::factory('VariableService')->getVariable('default_follow_group');
+            $groups =  explode(',',trim($default_follow_group,','));
+            if(isset($city_info['province'])){
+                $criteria = new EMongoCriteria();
+                $criteria->status('==',1);
+                $criteria->addCond('city_info.province','==',$city_info['province']);
+                $cursor = Group::model()->findAll($criteria);
+                foreach ($cursor as $value) {
+                    $groups[] = (string)$value->_id;
+                }
+            }
+            $stamp = '3';
+            foreach ($groups as $key => $value) {
+                if(!CommonFn::isMongoId($value)){
+                    unset($groups[$key]);
+                    continue;
+                }
+                $groups[$key] = new MongoId($value);
+                $stamp.=$value;
+            }
+            $group_ids = array_values($groups);
+            $cache_key = md5($stamp.$last_visit_hours.$get_new);
+        }else{
+            $default_follow_group = Service::factory('VariableService')->getVariable('default_follow_group');
+            $groups =  explode(',',trim($default_follow_group,','));
+            $stamp = '3';
+            foreach ($groups as $key => $value) {
+                if(!CommonFn::isMongoId($value)){
+                    unset($groups[$key]);
+                    continue;
+                }
+                $groups[$key] = new MongoId($value);
+                $stamp.=$value;
+            }
+            $group_ids = array_values($groups);
+            $last_visit_hours = 168;
+            $cache_key = md5($stamp.$last_visit_hours.$get_new);
+        }
+        foreach ($group_ids as $key => $value) {
+            if(in_array((string)$value,$no_recommond_groups)){
+                unset($group_ids[$key]);
+            }
+        }
+        $group_ids = array_values($group_ids);
+        $cache = new ARedisCache();
+        $cache_data = $cache->get($cache_key.'v4');
+        if($cache_data && !YII_DEBUG){
+            $cache_res = unserialize($cache_data);
+            $data = $cache_res['data'];
+        }else{
+            
+            //按钮链接
+            $link_button[] = array(
+                    'title'=>'买宠物',
+                    'link_text'=>'有保障/大礼包',
+                    'icon_url'=>'http://7oxep6.com1.z0.glb.clouddn.com/huotijiaoyi.png',
+                    'link'=>'http://'.$host.'/o2o/web/index/deal?need_header=0'
+                );
+            $link_button[] = array(
+                    'title'=>'问专家',
+                    'link_text'=>'看病/训犬/养护',
+                    'icon_url'=>'http://7oxep6.com1.z0.glb.clouddn.com/doctorhij.png',
+                    'link'=>'http://'.$host.'/group/54a0fa1f0eb9fb17308b47a6'
+                );
+            $data['link_button'] = $link_button;
+
+            //活体交易部分
+            $deal['type'] = 'deal';
+            $deal['title'] = '放心、有保障的宠物交易';
+            $deal['more'] = 'http://'.$host.'/o2o/web/index/deal?need_header=0';
+            //todo pettype
+            $new_pets = DealPet::getNewPet();
+            foreach ($new_pets as $key => $value) {
+                $new_pets[$key]['url'] = 'http://'.$host.'/o2o/web/index/deal?need_header=0/#!/detail/'.$value['id'];
+            }
+            $deal['pets'] = $new_pets;
+            $data['modules'][] = $deal;
+
+            $res_topics = array();
+            $conditions = array(    
+                                    'group'=>array('in',$group_ids),
+                                    'status'=>array('==',1),
+                                    'time'=>array('>=',time()-3600*$last_visit_hours)
+                                );
+            //最新最热帖排序规则
+            $order = $get_new?['_id'=>'desc']:['like_count'=>'desc'];
+            $model = new Topic();
+            $pagedata = CommonFn::getPagedata($model,1,200,$conditions,$order,false);
+            $topics = $pagedata['res'];
+            foreach($topics as $topic){
+                $res_topics[] = $topic['_id'];
+            }
+            $data['topics'] = $res_topics;
+            $cache_data = array();
+            $cache_data['data'] = $data;
+            $cache->set($cache_key.'v4',serialize($cache_data),3600);
+        }
+        $res_topics = array();
+        $topics = $data['topics'];
+        $skip = 20*$page-20;
+        if($skip+20 >= count($topics)){
+            $has_more = 0;
+        }else{
+            $has_more = 1;
+        }
+        $topics_ids = array_slice($topics,$skip,20);
+        $model = new Topic();
+        foreach ($topics_ids as $key => $topic_id) {
+            $_topic = $model->parseRow(Topic::get(new MongoId($topic_id)),array('id','content','city_info','city_info_str','city_topic_str','time','time_str','group','visit_count','reply_count','fav_count','like_count','user','pics','voice','video','last_post_time','last_post_time_str'));
+            if($user){
+                $z_like = new ZLike();
+                $like = $z_like->getLikeByLikeObj((string)$user['_id'],$_topic['id']);
+                if(empty($like)){
+                    $_topic['is_liked'] = false;
+                }else{
+                    $_topic['is_liked'] = true;
+                }
+            }else{
+                $_topic['is_liked'] = false;
+            }
+            $res_topics[] = $_topic;
+        }
+        $data['topics'] = $res_topics;
+        //首页轮播图
+        $province_tag = isset($city_info['province'])?$city_info['province']:'no';
+        $slide = Slide::getIndexSlide($province_tag);
+        $data['slide'] = $slide;
+        if(isset($add_score['status'])){
+            $score_info['score_change'] = $add_score['score'];
+            $score_info['current_score'] = $add_score['current_score'];
+            $score_info['score_type'] = '签到';
+            CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data,303,$score_info);
+        }else{
+            CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data,200,array('has_more'=>$has_more,'last_visit_hours' =>$last_visit_hours));
+        }
+    }
+
+}

+ 1010 - 0
www/protected/modules/api/controllers/UserController.php

@@ -0,0 +1,1010 @@
+<?php
+/**
+ * UserController 用户相关api接口
+ */
+class UserController extends ApiBaseController{
+    public function beforeAction($action){
+        $weixin_use = array('info');
+        if(Yii::app()->getRequest()->getParam("request_from") == 'weixin' && in_array($action->id,$weixin_use)){
+            return true;
+        }
+        return $this->verify();
+    }
+    //用户邮箱注册
+    public function actionRegister(){
+        $userAr  = new RUser();
+        $data = array();
+        $data['user_name'] = trim(Yii::app()->request->getParam('user_name',''));
+        $data['password'] = Yii::app()->request->getParam('password');
+        $data['email'] = Yii::app()->request->getParam('email','');
+        $data['avatar'] = Yii::app()->request->getParam('avatar','');
+        $data['city_info'] =  json_decode(Yii::app()->request->getParam('city_info'),true);
+        $position = json_decode(Yii::app()->request->getParam('position'),true);
+        $data['position'][0] = isset($position['lng'])?floatval($position['lng']):0;
+        $data['position'][1] = isset($position['lat'])?floatval($position['lat']):0;
+        //防止city_info出现非法数据
+        if(!isset($data['city_info']['province'])){
+            $data['city_info']['province'] = '';
+            $data['city_info']['city'] = '';
+            $data['city_info']['area'] = '';
+        }elseif(!isset($data['city_info']['city'])){
+            $data['city_info']['city'] = '';
+            $data['city_info']['area'] = '';
+        }elseif(!isset($data['city_info']['area'])){
+            $data['city_info']['area'] = '';
+        }
+
+        $data['app_client_id'] = intval(Yii::app()->request->getParam('app_client_id'));
+        $data['device_id'] = Yii::app()->request->getParam('device_id');
+        $data['channel'] = Yii::app()->request->getParam('channel');
+        $data['openid'] = Yii::app()->request->getParam('openid');
+        $data['phone_type'] = Yii::app()->request->getParam('phone_type');
+        $data['os_version'] = Yii::app()->request->getParam('os_version');
+        $data['register_time'] = time();
+        $data['last_visit_time'] = time();
+
+        if(!preg_match(Yii::app()->params['emailReg'], $data['email'])){
+            CommonFn::requestAjax(false,CommonFn::getMessage('user','email_Illegal'));
+        }
+        $z_user = new ZUser();
+        $z_user->validate_user_name($data['user_name']);
+        if(strlen($data['password'])<6 || strlen($data['password'])>20){
+            CommonFn::requestAjax(false, CommonFn::getMessage('user','password_length_6_20'));
+        }
+        $userAr->attributes = $data;
+        $criteria = new EMongoCriteria();
+        $criteria->email('==',$userAr->email);
+        $olduser = RUser::model()->find($criteria);
+        if($olduser){
+            CommonFn::requestAjax(false,CommonFn::getMessage('user','email_already_registered'));
+        }
+        $criteria = new EMongoCriteria();
+        $criteria->user_name('==',$userAr->user_name);
+        $olduser = RUser::model()->find($criteria);
+        if($olduser){
+            CommonFn::requestAjax(false,CommonFn::getMessage('user','username_already_registered'));
+        }
+        $userAr->password = md5($userAr->password);
+        //用户注册后默认关注几个圈子
+        $z_group = new ZGroup();
+        $userAr->groups = $z_group->get_default_fllow_group();
+        if($userAr->save()){
+            $data = RUser::model()->parseRow($userAr->attributes);
+            CommonFn::requestAjax(true,CommonFn::getMessage('user','register_success'),$data);
+        }else{
+            CommonFn::requestAjax(false,CommonFn::getMessage('user','register_faild'));
+        }
+    }
+
+    //微信用户的登录
+    public function actionWeixinLogin(){
+        $data = array();
+        $data['user_name'] = mb_strtolower(Yii::app()->request->getParam('user_name',''));
+        $data['avatar'] = Yii::app()->request->getParam('avatar','');
+        $data['city_info'] =  json_decode(Yii::app()->request->getParam('city_info'),true);
+        $position = json_decode(Yii::app()->request->getParam('position'),true);
+
+        //防止city_info出现非法数据
+        if(!isset($data['city_info']['province']) || $data['city_info']['province'] == '未知'){
+            $data['city_info']['province'] = '';
+            $data['city_info']['city'] = '';
+            $data['city_info']['area'] = '';
+        }elseif(!isset($data['city_info']['city'])){
+            $data['city_info']['city'] = '';
+            $data['city_info']['area'] = '';
+        }elseif(!isset($data['city_info']['area'])){
+            $data['city_info']['area'] = '';
+        }
+
+        $data['position'][0] = isset($position['lng'])?floatval($position['lng']):0;
+        $data['position'][1] = isset($position['lat'])?floatval($position['lat']):0;
+
+        $data['app_client_id'] = intval(Yii::app()->request->getParam('app_client_id'));
+        $data['device_id'] = Yii::app()->request->getParam('device_id');
+        $data['channel'] = Yii::app()->request->getParam('channel');
+        $data['phone_type'] = Yii::app()->request->getParam('phone_type');
+        if($data['channel'] == 'appstore'){
+            $data['phone_type'] = Yii::app()->request->getParam('device_model');
+        }
+        $data['app_version'] = Yii::app()->request->getParam('app_version');
+
+        $data['os_version'] = Yii::app()->request->getParam('os_version');
+
+        $data['openid'] = Yii::app()->request->getParam('openid','');
+        $data['unionid'] = Yii::app()->request->getParam('unionid','');
+
+        $data['sex'] = intval(Yii::app()->request->getParam('sex'));
+
+        $data['register_time'] = time();
+        $data['last_visit_time'] = time();
+
+        
+
+        if ($data['openid'] == ''){
+            CommonFn::requestAjax(false, CommonFn::getMessage('user','weixin_login_faild'));
+        }
+
+        $criteria = new EMongoCriteria();
+        if(isset($data['unionid']) && !empty($data['unionid'])){
+            $criteria->unionid('==',$data['unionid']);//unionid保证账号统一
+        }else{
+            $criteria->openid('==',$data['openid']);
+        }
+        $user = RUser::model()->find($criteria);
+        if($user){
+            $user->os_version = $data['os_version'];
+            $user->device_id = $data['device_id'];
+            $user->app_client_id = $data['app_client_id'];
+            $paraArr = array('os_version','device_id','app_client_id');
+            if(!empty($data['position'])&&!empty($data['position'][0])&&!empty($data['position'][1])){
+                $user->position = $data['position'];
+                $paraArr[] = 'position';
+            }
+            if(!empty($data['city_info']['province'])){
+                $user->city_info = $data['city_info'];
+                $paraArr[] = 'city_info';
+            }
+            $user->update($paraArr,true);
+            $data = RUser::model()->parseRow($user->attributes);
+            $z_action_cat = new ZActionCat();
+            $news_count = $z_action_cat->getUnReadNews($user->_id);
+            $data['news'] = $news_count;
+            CommonFn::requestAjax(true,CommonFn::getMessage('user','login_success'),$data);
+        }else{
+            $z_user = new ZUser();
+            $z_user->validate_user_name($data['user_name']);
+            $userAr  = new RUser();
+            $userAr->user_name = $data['user_name'];
+            $userAr->avatar = $data['avatar'];
+            $userAr->city_info = $data['city_info'];
+            $userAr->position = $data['position'];
+            $userAr->app_client_id = $data['app_client_id'];
+            $userAr->device_id = $data['device_id'];
+            $userAr->phone_type = $data['phone_type'];
+            $userAr->app_version = $data['app_version'];
+            $userAr->os_version = $data['os_version'];
+            $userAr->channel = $data['channel'];
+            $userAr->openid = $data['openid'];
+            $userAr->unionid = $data['unionid'];
+            $userAr->sex = $data['sex']?$data['sex']:3;
+            $userAr->register_time = $data['register_time'];
+            $userAr->last_visit_time = $data['last_visit_time'];
+            try {
+                $saveResult = $userAr->save();
+            }catch(Exception $e){
+                $userAr->user_name = 'wz_'.dechex(time());
+                $saveResult = $userAr->save();
+            }
+
+            if($saveResult){
+                $z_group = new ZGroup();
+                $default_groups = $z_group->get_default_fllow_group();
+                $userAr->groups = $default_groups;
+                $userAr->update(array('groups'),true);
+                $list = new ARedisList('after_user_reg');
+                $user_id = (string)$userAr->_id;
+                $list->push($user_id);
+                $data = RUser::model()->parseRow($userAr->attributes);
+                $news = [
+                    'like'=>0,
+                    'message'=>0,
+                    'reply'=>0,
+                    'notice'=>0,
+                    'order'=>0,
+                    'follow'=>0,
+                    'new_topic'=>0,
+                    'new_card'=>0,
+                    'total'=>0
+                ];
+                $data['news'] = $news;
+                CommonFn::requestAjax(true,CommonFn::getMessage('user','register_success'),$data,200,array('is_new'=>1));
+            }else{
+                CommonFn::requestAjax(false,CommonFn::getMessage('user','register_faild'));
+            }
+        }
+    }
+
+    //用户登陆
+    public function actionLogin(){
+        $password = md5(Yii::app()->request->getParam('password'),'');
+        $email = preg_replace('/\0/','',Yii::app()->request->getParam('email',''));
+        $email = str_replace(' ','',$email);
+        if($password&&$email){
+            $criteria = new EMongoCriteria();
+            $criteria->email = new MongoRegex('/' . $email . '/i');
+
+            try {
+                $userAr = RUser::model()->find($criteria);
+            } catch (Exception $e) {
+                CommonFn::requestAjax(false,CommonFn::getMessage('user','id_not_exist'));
+            }
+            if(!$userAr){
+                CommonFn::requestAjax(false,CommonFn::getMessage('user','id_not_exist'));
+            }
+            if($password == $userAr->password){
+                $userAr->last_visit_time = time();
+                $userAr->update(array('last_visit_time'),true);
+                $z_action_cat = new ZActionCat();
+                $news_count = $z_action_cat->getUnReadNews($userAr->_id);
+                $data = RUser::model()->parseRow($userAr->attributes);
+                $data['news'] = $news_count;
+                CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data);
+            }else{
+                CommonFn::requestAjax(false,CommonFn::getMessage('user','username_or_password_error'));
+            }
+        }else{
+            CommonFn::requestAjax(false,CommonFn::getMessage('message','params_miss'));
+        }
+    }
+
+    //用户登陆前验证
+    public function actionValidate(){
+        $email = Yii::app()->request->getParam('email');
+        if(!$email){
+            CommonFn::requestAjax(false,CommonFn::getMessage('message','params_miss'));
+        }
+        $criteria = new EMongoCriteria();
+        if(preg_match(Yii::app()->params['emailReg'], $email)){
+            $criteria->email('==',$email);
+        }else{
+            $criteria->user_name('==',$email);
+        }
+        $userAr = RUser::model()->find($criteria);
+        if($userAr){
+            CommonFn::requestAjax(false,CommonFn::getMessage('user','email_already_registered'));
+        }else{
+            CommonFn::requestAjax(true,'');
+        }
+    }
+
+
+    //用户信息
+    public function actionInfo(){
+        if(Yii::app()->request->getParam('app_client_id') == 2){
+            $this->check_version();
+        }
+        $user_id = Yii::app()->getRequest()->getParam("user_id");
+        $uid = Yii::app()->getRequest()->getParam("to_user_id");
+        $user_name = Yii::app()->getRequest()->getParam("user_name");
+        if($user_name){
+            $criteria = new EMongoCriteria();
+            $criteria->user_name('==',$user_name);
+            $res = RUser::model()->find($criteria);
+            if(!$res){
+                CommonFn::requestAjax(false,CommonFn::getMessage('user','user_not_exist'),204);
+            }else{
+                $uid = $res->_id;
+            }
+        }
+        $page = intval(Yii::app()->getRequest()->getParam("page",1));
+        if(empty($page)){
+            $page = 1;
+        }
+        $notopic = Yii::app()->getRequest()->getParam("notopic");
+        if(empty($user_id) && empty($uid)){
+            CommonFn::requestAjax(false,CommonFn::getMessage('user','id_not_empty'),201);
+        }
+        $add_score = $this->today_first_login($user_id);
+        if($user_id){
+            $id = $user_id;
+        }
+        $model = new RUser();
+        if($uid){
+            if($user_id){
+                $user_node = new UserNodeRecord($user_id);
+                $relation = $user_node->relation($uid);
+            }
+            $id = $uid;
+        }
+        $user = CommonFn::apigetObJ($id,"ZUser",CommonFn::getMessage('user','id_not_exist'),201);
+        $user_data = $model->parseRow($user->attributes,array(),true);
+
+        $user_data['relation'] = isset($relation)?$relation:0;
+        $criteria = new EMongoCriteria();
+        $criteria->user('==',$user->_id);
+        $criteria->status("==",1);
+        $criteria->limit(3)->sort('time',EMongoCriteria::SORT_DESC);
+        $model = new Topic();
+        $cursor = $model->findAll($criteria);
+        $rows = CommonFn::getRows($cursor);
+        $topics = $model->parse($rows);
+        $feed = array();
+        if($topics){
+            $feed['pics'] = array();
+            foreach ($topics as $topic) {
+                $feed['pics'] = array_merge($feed['pics'],$topic['pics']);
+                $feed['pics'] = array_slice($feed['pics'],0,3);
+            }
+            if($feed['pics']){
+                $feed['type'] = 'pics';
+                $user_data['feed'] = $feed;
+            }elseif($topics[0]['content']){
+                $feed['type'] = 'text';
+                $feed['content'] = $topics[0]['content'];
+                $user_data['feed'] = $feed;
+            }else{
+                $feed['type'] = 'text';
+                $feed['content'] = '';
+                $user_data['feed'] = $feed;
+            }
+        }else{
+            $feed['type'] = 'text';
+            $feed['content'] = '';
+            $user_data['feed'] = $feed;
+        }
+        $z_action_cat = new ZActionCat();
+        $news_count = $z_action_cat->getUnReadNews($user->_id);
+        $user_data['news'] = $news_count;
+        $data['user'] = $user_data;
+        if(empty($notopic)){
+            $conditions = array(
+                'user'=>array('==',$user->_id),
+                'status'=>array('==',1)
+            );
+            $order = array(
+                'time'=>'desc',
+            );
+            $model = new Topic();
+            $pagedata = CommonFn::getPagedata($model,$page,20,$conditions,$order);
+            $user_topics = $pagedata['res'];
+            if(!empty($user_id)){
+                foreach ($user_topics as $key => $topic) {
+                    $z_like = new ZLike();
+                    $like = $z_like->getLikeByLikeObj($user_id,$topic['id']);
+                    if(empty($like)){
+                        $user_topics[$key]['is_liked'] = false;
+                    }else{
+                        $user_topics[$key]['is_liked'] = true;
+                    }
+                }
+                if(Yii::app()->getRequest()->getParam("page_size",0)==1){
+                    if(isset($user_topics[0]['pics'])&&count($user_topics[0]['pics'])<3){
+                        $criteria = new EMongoCriteria();
+                        $criteria->user('==',$user->_id);
+                        $criteria->status("==",1);
+                        $criteria->limit(2)->sort('time',EMongoCriteria::SORT_DESC)->offset(1);
+                        $model = new Topic();
+                        $cursor = $model->findAll($criteria);
+                        $rows = CommonFn::getRows($cursor);
+                        $topics = $model->parse($rows);
+                        foreach ($topics as $topic) {
+                            $user_topics[0]['pics'] = array_merge($user_topics[0]['pics'],$topic['pics']);
+                            $user_topics[0]['pics'] = array_slice($user_topics[0]['pics'],0,3);
+                        }
+                    }
+                }
+            }
+            $data['topic_list'] = $user_topics;
+        }
+        if($add_score['status']){
+            $score_info['score_change'] = $add_score['score'];
+            $score_info['current_score'] = $add_score['current_score'];
+            $score_info['score_type'] = '签到';
+            if(isset($pagedata)){
+                CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data,303,array_merge($score_info,array('sum_count' => $pagedata['sum_count'],'sum_page'=>$pagedata['sum_page'],'page_size'=>$pagedata['page_size'],'current_page'=>$pagedata['current_page'])));
+            }else{
+                CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data,303,$score_info);
+            }
+        }else{
+            if(isset($pagedata)){
+                CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data,200,array('sum_count' => $pagedata['sum_count'],'sum_page'=>$pagedata['sum_page'],'page_size'=>$pagedata['page_size'],'current_page'=>$pagedata['current_page']));
+            }else{
+                CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data);
+            }
+        }
+    }
+
+    /**
+     * 按照时间线展现帖子列表
+     * 当前日期的帖子没有显示完后,会追加当天剩余帖子数.并传递实际数据偏移量给前端
+     */
+    public function actionInfoByTimeline(){
+        $user_id = Yii::app()->getRequest()->getParam("user_id");
+        $uid = Yii::app()->getRequest()->getParam("to_user_id");
+        $user_name = Yii::app()->getRequest()->getParam("user_name");
+        if($user_name){
+            $criteria = new EMongoCriteria();
+            $criteria->user_name('==',$user_name);
+            $res = RUser::model()->find($criteria);
+            if(!$res){
+                CommonFn::requestAjax(false,CommonFn::getMessage('user','user_not_exist'),array(),204);
+            }else{
+                $uid = $res->_id;
+            }
+        }
+        $page = intval(Yii::app()->getRequest()->getParam("page",1));
+        if(empty($page)){
+            $page = 1;
+        }
+        $offset = Yii::app()->getRequest()->getParam('offset',0);
+        if(empty($user_id) && empty($uid)){
+            CommonFn::requestAjax(false,CommonFn::getMessage('user','id_not_empty'),201);
+        }
+        if($uid){
+            if($user_id){
+                $user_node = new UserNodeRecord($user_id);
+                $relation = $user_node->relation($uid);
+            }
+        }
+        if($user_id){
+            $id = $user_id;
+        }
+        if($uid){
+            $id = $uid;
+        }
+        $model = new RUser();
+        $user_obj = CommonFn::apigetObJ($id,"ZUser",CommonFn::getMessage('user','id_not_exist'),201);
+        $user_data = $model->parseRow($user_obj->attributes);
+        $user_data['relation'] = isset($relation)?$relation:0;
+        //获取用户帖子信息
+        $topic_model = new ZTopic();
+        $user_topics = array();
+        $pagesize = 20;
+        $page_offset = ($page - 1) * $pagesize;
+        if(!$offset){
+            $offset = $offset > 0 && $page_offset < $offset ? $offset : $page_offset;
+        }
+        $criteria = new EMongoCriteria();
+        $criteria->user('==',$user_obj->_id);
+        $criteria->status("==",1);
+        $criteria->limit($pagesize)->sort('time',EMongoCriteria::SORT_DESC)->offset($offset);
+        $model = new Topic();
+        $cursor = $model->findAll($criteria);
+        $rows = CommonFn::getRows($cursor);
+        $rows = $model->parse($rows);
+        //获取有追加数据
+        if(count($rows)<1){
+            $data = array(
+                'user' => $user_data,
+                'topic_list' => array(),
+                'offset' => $offset,
+            );
+            CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data,200,array('is_more'=>0));
+        }
+        $last_topic = $rows[count($rows)-1];
+        $append_data = $topic_model->getAppendDateByDate($uid,$last_topic['last_post_time']);
+        if($append_data){
+            $rows = array_merge($rows,$append_data);
+        }
+        //按时间顺序排列
+        foreach($rows as $row ){
+            $user_topics[$row['date']]['time'] = $row['date'];
+            $user_topics[$row['date']]['data'][] = $row;
+        }
+        $user_topics = array_values($user_topics);
+
+        $current_offset = count($rows)+$offset;     //当前实际数据偏移值
+        if(count($rows)<20){
+            $is_more = 0;
+        }else{
+            $is_more = 1;
+        }
+        //追加到用户数据中
+        $data = array(
+            'user' => $user_data,
+            'topic_list' => $user_topics,
+            'offset' => $current_offset
+        );
+        CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data,200,array('is_more'=>$is_more));
+    }
+
+    //用户收藏信息接口
+    public function actionFavList(){
+        $user_id = Yii::app()->getRequest()->getParam("user_id");
+        $page = intval(Yii::app()->getRequest()->getParam("page",1));
+        if(empty($page)){
+            $page = 1;
+        }
+        //获取用户收藏信息
+        $user = CommonFn::apigetObJ($user_id,'ZUser',CommonFn::getMessage('user','id_not_exist'),201);
+        $pagesize = Yii::app()->params['userFavsPageSize'];
+        $conditions = array(
+            'user'=>array('==',$user->_id)
+        );
+        $order = array(
+            'time'=>'desc',
+        );
+        $model = new Fav();
+        $pagedata = CommonFn::getPagedata($model,$page,$pagesize,$conditions,$order);
+        $user_favs = $pagedata['res'];
+        if(!empty($user_favs)){
+            foreach ($user_favs as $key => $value) {
+                if($value['fav_obj']['status']!=1){
+                    unset($user_favs[$key]);
+                }
+            }
+        }
+        $data = array();
+        foreach($user_favs as $fav){
+            $z_like = new ZLike();
+            $like = $z_like->getLikeByLikeObj($user_id,$fav['fav_obj']['id']);
+            if(empty($like)){
+                $fav['fav_obj']['is_liked'] = false;
+            }else{
+                $fav['fav_obj']['is_liked'] = true;
+            }
+            $data[] = $fav['fav_obj'];
+        }
+        CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data,200,array('sum_count' => $pagedata['sum_count'],'sum_page'=>$pagedata['sum_page'],'page_size'=>$pagedata['page_size'],'current_page'=>$pagedata['current_page']));
+    }
+
+    //用户帖子列表页面
+    public function actionTopicList(){
+        $user_id = Yii::app()->getRequest()->getParam("user_id");
+        $uid = Yii::app()->getRequest()->getParam("to_user_id");
+        $page = intval(Yii::app()->getRequest()->getParam("page",1));
+        if(empty($page)){
+            $page = 1;
+        }
+        $offset = Yii::app()->getRequest()->getParam('offset',0);
+
+        if(empty($user_id) && empty($uid)){
+            CommonFn::requestAjax(false,CommonFn::getMessage('user','id_not_empty'),201);
+        }
+        if($user_id){
+            $id = $user_id;
+            $time_list_flag = true;
+        }
+        if($uid){
+            $id = $uid;
+            $time_list_flag = false;
+        }
+
+        //获取用户帖子列表
+        $topic_model = new ZTopic();
+        $user_topics = array();
+        $rows = $topic_model->getUserTopic($id,$page,$offset);
+        if(count($rows)<1){
+            $data = array(
+                'topic_list' => array(),
+                'offset' => $offset,
+            );
+            CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data);
+        }
+
+        if($time_list_flag){
+            //获取有追加数据
+            $last_topic = $rows[count($rows)-1];
+            $append_data = $topic_model->getAppendDateByDate($id,$last_topic['last_post_time']);
+            if($append_data){
+                $rows = array_merge($rows,$append_data);
+            }
+
+            //按时间顺序排列
+            foreach($rows as $row ){
+                $user_topics[$row['date']]['time'] = $row['date'];
+                $user_topics[$row['date']]['data'][] = $row;
+            }
+            $user_topics = array_values($user_topics);
+
+        }else{
+            $user_topics = $rows;
+        }
+        $current_offset = count($rows);     //当前实际数据偏移值
+
+        $data = array(
+            'topic_list' => $user_topics,
+            'offset' => $current_offset,
+        );
+        CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data);
+    }
+
+    //修改用户资料
+    public function actionEdit(){
+        $data['_id'] = Yii::app()->getRequest()->getParam('user_id');
+        if(!CommonFn::isMongoId($data['_id'])){
+            CommonFn::requestAjax(false,CommonFn::getMessage('user','id_not_exist'),201);
+        }
+        $model = new RUser();
+        $user = CommonFn::apigetObJ($data['_id'],"ZUser",CommonFn::getMessage('user','id_not_exist'),201);
+
+        //需要进行修改的数据内容
+        $data['avatar'] = Yii::app()->getRequest()->getParam('avatar','');
+        $data['mobile'] = Yii::app()->getRequest()->getParam('mobile','');
+        $data['sex'] =  intval(Yii::app()->getRequest()->getParam('sex'));
+        $data['user_name']= Yii::app()->getRequest()->getParam('user_name','');
+        $data['city_info'] =  json_decode(Yii::app()->request->getParam('city_info'),true);
+        //防止city_info出现非法数据
+        if(!isset($data['city_info']['province'])){
+            $data['city_info']['province'] = '';
+            $data['city_info']['city'] = '';
+            $data['city_info']['area'] = '';
+        }elseif(!isset($data['city_info']['city'])){
+            $data['city_info']['city'] = '';
+            $data['city_info']['area'] = '';
+        }elseif(!isset($data['city_info']['area'])){
+            $data['city_info']['area'] = '';
+        }
+        if($data['avatar']){
+            if(!CommonFn::checkPicFormat($data['avatar'])){
+                CommonFn::requestAjax(false,CommonFn::getMessage('user','user_avatar_illegal'));
+            }
+        }
+        if($user->certify_status == 1 && $data['user_name'] &&  $user->user_name != $data['user_name']){
+            CommonFn::requestAjax(false,'你已通过认证,不允许修改昵称');
+        }
+        //过滤user_id ,检测本接口所需参数是否完整
+        $item_count = 0;
+        unset($data['_id']);
+        //用户名检测
+        if(isset($data['user_name']) && $data['user_name']){
+            if(mb_strlen($data['user_name'],'utf-8')<2||mb_strlen($data['user_name'],'utf-8')>16){
+                CommonFn::requestAjax(false,CommonFn::getMessage('user','username_length_illegal'));
+            }
+            $z_user = new ZUser();
+            $z_user->validate_user_name($data['user_name']);
+            $u_criteria = new EMongoCriteria();
+            $u_criteria->user_name('==',$data['user_name']);
+            $olduser = RUser::model()->find($u_criteria);
+            if($olduser&&$olduser->_id!=$user->_id){
+                CommonFn::requestAjax(false,CommonFn::getMessage('user','username_already_registered'));
+            }
+        }elseif(empty($data['user_name'])){
+            $data['user_name'] = $user->user_name;
+        }
+        foreach($data as $key => $val){
+            if(!empty($val)){
+                if($key=='city_info' && empty($val['province'])){
+                    continue;
+                }
+                $item_count++;
+                $user->{$key} = $val;
+            }
+        }
+        //更新数据
+        if($item_count){
+            if($user->save(true)){
+                $data = $user->parseRow($user->attributes,array(),true);
+                CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$data);
+            }else{
+                CommonFn::requestAjax(false,CommonFn::getMessage('message','operation_faild'));
+            }
+        }else{
+            CommonFn::requestAjax(false,CommonFn::getMessage('message','params_illegal'));
+        }
+    }
+
+    //用户爪币记录
+    public function actionScoreLog(){
+        $user_id = Yii::app()->getRequest()->getParam("user_id");
+        $page = intval(Yii::app()->getRequest()->getParam("page",1));
+        if(empty($page)){
+            $page = 1;
+        }
+        if(empty($user_id) ){
+            CommonFn::requestAjax(false,CommonFn::getMessage('user','id_not_exist'),201);
+        }
+        if($user_id){
+            $id = $user_id;
+        }
+        $deviceid =  Yii::app()->request->getParam('device_id');
+        //设置首次访问时间,保证一次浏览的回复列表不变
+        $actiontime = CommonFn::getFirstTime(ActionTimeRedis::TYPE_GET_SCORELOG,$deviceid,$page);
+        $pagesize = Yii::app()->params['userScoreLogPageSize'];
+        $conditions = array(
+            'user'=>array('==',$id),
+            'time'=>array('<=',$actiontime)
+        );
+        $order = array(
+            'time'=>'desc',
+        );
+        $model = new UserScoreLog();
+        $pagedata = CommonFn::getPagedata($model,$page,$pagesize,$conditions,$order);
+        $logs = $pagedata['res'];
+        CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$logs,200,array('sum_count' => $pagedata['sum_count'],'sum_page'=>$pagedata['sum_page'],'page_size'=>$pagedata['page_size'],'current_page'=>$pagedata['current_page']));
+    }
+
+    //用户拒绝接受推送
+    public function actionSetPush(){
+        $user_id = Yii::app()->getRequest()->getParam("user_id");
+        $user = CommonFn::apigetObJ($user_id,"ZUser",CommonFn::getMessage('user','id_not_exist'),201);
+        if($user->receive_push == 0){
+            $user->receive_push = 1;
+            if($user->update(array('receive_push'),true)){
+                CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),array('op'=>'receive'));
+            }
+        }else{
+            $user->receive_push = 0;
+            if($user->update(array('receive_push'),true)){
+                CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),array('op'=>'unreceive'));
+            }
+        }
+    }
+
+    //用户分享成功后增加爪币
+    public function actionShareSuccess(){
+        $user_id = Yii::app()->getRequest()->getParam("user_id");
+        $user = CommonFn::apigetObJ($user_id,"ZUser",CommonFn::getMessage('user','id_not_exist'),201);
+        $add_score = $this->addScore($user_id,'score_share');
+        $result = array();
+        if($add_score['status']){
+            $add_score['score_change'] = $add_score['score'];
+            $add_score['current_score'] = $add_score['current_score'];
+            $add_score['score_type'] = '分享成功';
+            CommonFn::requestAjax(true,'分享增加爪币成功',array(),301,$add_score);
+        }else{
+            CommonFn::requestAjax(false,'分享增加爪币失败');
+        }
+    }
+
+    //用户申请认证接口
+    public function actionApplyCertify(){
+        $data = array();
+        $data['content'] = '您好,目前握爪仅开放认证宠物医生、营养师、训犬师、美容师,认证需要您相关的资格证书或学校就读证书照片及您与证书合影的照片,直接在私信里发给爪爪就好了。';
+        $data['from_user'] = Yii::app()->params['kefu_user'];
+        $data['to_user'] = Yii::app()->request->getParam('user_id','');
+        $date = date('Ymd');
+        $Key = HelperKey::generateUserActionKey('applycertify',$date,$data['to_user']);
+        $status = UserActionRedis::get($Key);
+        if($status){
+            CommonFn::requestAjax(false,'你今天已提交过认证申请,请不要重复申请');
+        }else{
+            UserActionRedis::set($Key,true);
+        }
+        $data['voice'] = json_decode(Yii::app()->request->getParam('voice'),true);
+        $data['video'] = json_decode(Yii::app()->request->getParam('video'),true);
+        $data['pics'] =  json_decode(Yii::app()->request->getParam('pics'),true);
+        $z_message = new ZMessage();
+        $result =  $z_message->addMessage($data);
+        if($result['status']){
+            CommonFn::requestAjax(true,'已提交认证申请');
+        }else{
+            CommonFn::requestAjax(false,'提交申请失败,请重试');
+        }
+    }
+
+    //用户加与取消关注接口
+    public function actionFollow(){
+        $user_id = Yii::app()->getRequest()->getParam("user_id");
+        $user = CommonFn::apigetObJ($user_id,"ZUser",CommonFn::getMessage('user','id_not_exist'),201);
+        $f_id = Yii::app()->getRequest()->getParam("to_user_id");
+        $f_id_list = json_decode(Yii::app()->getRequest()->getParam("to_user_list"),true);
+        if(!$f_id_list && !CommonFn::isMongoId($f_id)){
+            CommonFn::requestAjax(false,CommonFn::getMessage('message','params_illegal'));
+        }
+        $user_node = new UserNodeRecord($user->_id);
+        //批量关注
+        if(is_array($f_id_list) && !empty($f_id_list)){
+            foreach ($f_id_list as $value) {
+                $user_node->follow($value);
+            }
+            CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),array('op'=>'follow','follow_count'=>$user_node->follow_count(),'fans_count'=>$user_node->follower_count()));
+        }
+        if($user_node->is_following($f_id)){
+            $user_node->unfollow($f_id);
+            $op = 'unfollow';
+            $message = '取消关注成功';
+        }else{
+            $user_node->follow($f_id);
+            $message = '关注成功';
+            $op = 'follow';
+        }
+        CommonFn::requestAjax(true,$message,array('op'=>$op,'follow_count'=>$user_node->follow_count(),'fans_count'=>$user_node->follower_count()));
+    }
+
+    //好友帖子列表
+    public function actionFriendsTopicList(){
+        $last_obj_id = Yii::app()->getRequest()->getParam("last_object_id",'');
+        $user_id = Yii::app()->getRequest()->getParam("user_id");
+        $user = CommonFn::apigetObJ($user_id,"ZUser",CommonFn::getMessage('user','id_not_exist'),201);
+        if(CommonFn::isMongoId($last_obj_id)){
+            $last_topic_obj = Topic::get(new MongoId($last_obj_id));
+            if($last_topic_obj){
+                $last_obj_time = $last_topic_obj->time;
+            }
+        }else{
+            $last_obj_time = time();
+        }
+        if(!isset($last_obj_time)){
+            CommonFn::requestAjax(false,CommonFn::getMessage('message','params_illegal'));
+        }
+        //设置小红点
+        // $cache = new ARedisCache();
+        // $cache->set('friend_topic_'.$user_id,0);
+        $user_node = new UserNodeRecord($user_id);
+        $follow_list = $user_node->following();
+        $f_ids = array();
+        foreach ($follow_list as $key => $value) {
+            $f_ids[] = new MongoId($value);
+        }
+        $conditions = array(
+            'user'=>array('in',$f_ids),
+            'status'=>array('==',1),
+            'time'=>array('<',$last_obj_time)
+        );
+        $order = array(
+            '_id'=>'desc',
+        );
+        $model = new Topic();
+        $pagedata = CommonFn::getPagedataById($model,20,$conditions,$order);
+        $topics = $pagedata['res'];
+        foreach ($topics as $key=>$value) {
+            if($user){
+                //判断用户是否收藏过该帖子
+                $z_fav = new ZFav();
+                $fav = $z_fav->getFavByFavObj($user_id,$value['id']);
+                if(empty($fav)){
+                    $value['is_faved'] = false;
+                }else{
+                    $value['is_faved'] = true;
+                }
+
+                //判断用户是否喜欢过该帖子
+                $z_like = new ZLike();
+                $like = $z_like->getLikeByLikeObj($user_id,$value['id']);
+                if(empty($like)){
+                    $value['is_liked'] = false;
+                }else{
+                    $value['is_liked'] = true;
+                }
+            }else{
+                $value['is_faved'] = false;
+                $value['is_liked'] = false;
+            }
+            $topics[$key] = $value;
+        }
+        $data['topic_list'] = $topics;
+        CommonFn::requestAjax(true,'',$data,200,array('has_more' => $pagedata['has_more'],'page_size'=>$pagedata['page_size']));
+    }
+
+    //我的关注接口
+    public function actionFollowList(){
+        $user_id = Yii::app()->getRequest()->getParam("user_id");
+        $to_user = Yii::app()->getRequest()->getParam("to_user_id");
+        $page = Yii::app()->getRequest()->getParam("page");
+        $page_size = Yii::app()->getRequest()->getParam("page_size",20);
+        if($to_user){
+            $uid = $to_user;
+            $user_node = new UserNodeRecord($to_user);
+            $current_user_node = new UserNodeRecord($user_id);
+            $need_refresh = true;
+        }else{
+            $uid = $user_id;
+            $user_node = new UserNodeRecord($user_id);
+        }
+        $follow_list = $user_node->following();
+        $sum = count($follow_list);
+        $follow_list = array_slice($follow_list,$page_size*($page-1),$page_size*$page);
+        $user_model = new RUser();
+        foreach ($follow_list as $key => $f_user) {
+            $follow_list[$key] =  $user_model->parseRow(RUser::get(new MongoId($f_user)),array('id','user_name','sex','avatar','level','city_info','pets','certify_status','certify_info','can_access'));
+            if(isset($need_refresh)){
+                $follow_list[$key]['relation'] = $current_user_node->relation($f_user);
+            }else{
+                $follow_list[$key]['relation'] = $user_node->relation($f_user);
+            }
+        }
+        CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$follow_list,200,array('sum_count' => $sum ,'sum_page'=> ceil($sum/$page_size),'page_size'=>$page_size,'current_page'=>$page));
+    }
+
+    //粉丝列表
+    public function actionFansList(){
+        $user_id = Yii::app()->getRequest()->getParam("user_id");
+        $to_user = Yii::app()->getRequest()->getParam("to_user_id");
+        $page = Yii::app()->getRequest()->getParam("page");
+        $page_size = Yii::app()->getRequest()->getParam("page_size",20);
+        if($to_user){
+            $uid = $to_user;
+            $user_node = new UserNodeRecord($to_user);
+            $current_user_node = new UserNodeRecord($user_id);
+            $need_refresh = true;
+        }else{
+            $uid = $user_id;
+            $user_node = new UserNodeRecord($user_id);
+        }
+        $followed_by = $user_node->followed_by();
+        $sum = count($followed_by);
+        $followed_by = array_slice($followed_by,$page_size*($page-1),$page_size*$page);
+        $user_model = new RUser();
+        foreach ($followed_by as $key => $f_user) {
+            $followed_by[$key] =  $user_model->parseRow(RUser::get(new MongoId($f_user)),array('id','user_name','sex','avatar','level','city_info','pets','certify_status','certify_info','can_access'));
+            if(isset($need_refresh)){
+                $followed_by[$key]['relation'] = $current_user_node->relation($f_user);
+            }else{
+                $followed_by[$key]['relation'] = $user_node->relation($f_user);
+            }
+        }
+        CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),$followed_by,200,array('sum_count' => $sum ,'sum_page'=> ceil($sum/$page_size),'page_size'=>$page_size,'current_page'=>$page));
+    }
+
+    //推荐关注用户
+    public function actionRecommendUsers(){
+        $user_id = Yii::app()->getRequest()->getParam("user_id");
+        $city_info = Yii::app()->getRequest()->getParam("city_info");
+        $city_info = json_decode($city_info,true);
+        $user_obj = CommonFn::apigetObJ($user_id,"ZUser",CommonFn::getMessage('user','id_not_exist'),201);
+
+        $user_node = new UserNodeRecord($user_obj->_id);
+        $follow_list = $user_node->following();
+        $follow_users = array();
+        foreach ($follow_list as $key => $value) {
+            $follow_users[] = new MongoId($value);
+        }
+
+        $follow_users[] = $user_obj->_id;
+        $criteria = new EMongoCriteria;
+        $criteria->certify_status('==',1);
+        $criteria->_id('notin',$follow_users);
+        $criteria->is_fake_user('!=',1);
+        $criteria->sort('last_visit_time',EMongoCriteria::SORT_DESC);
+        $criteria->limit(5);
+        $cursor = RUser::model()->findAll($criteria);
+        $rows = RUser::model()->parse($cursor,true,array('id','user_name','sex','avatar','level','city_info','certify_status','certify_info','can_access'));
+        $certify_users = array();
+        foreach ($rows as $value) {
+            $value['recommend_reason'] = $value['certify_info'];
+            $certify_users[] = $value;
+        }
+
+        $criteria = new EMongoCriteria;
+        if(isset($city_info['province']) && $city_info['province']){
+            $criteria->city_info->province('==',$city_info['province']);
+        }else{
+            $criteria->city_info->province('==','上海市');
+        }
+        $criteria->_id('notin',$follow_users);
+        $criteria->is_fake_user('!=',1);
+        $criteria->certify_status('!=',1);
+        $criteria->sort('last_visit_time',EMongoCriteria::SORT_DESC);
+        $criteria->limit(10);
+        $cursor = RUser::model()->findAll($criteria);
+        $rows = RUser::model()->parse($cursor,true,array('id','user_name','sex','avatar','level','city_info','certify_status','certify_info','can_access'));
+        $local_user = array();
+        foreach ($rows as $value) {
+            $value['recommend_reason'] = '同城用户';
+            $local_user[] = $value;
+        }
+
+        $criteria = new EMongoCriteria;
+        if(isset($city_info['province']) && $city_info['province']){
+            $criteria->city_info->province('!=',$city_info['province']);
+        }else{
+            $criteria->city_info->province('!=','上海市');
+        }
+        $criteria->_id('notin',$follow_users);
+        $criteria->is_fake_user('!=',1);
+        $criteria->certify_status('!=',1);
+        $criteria->sort('posts_count',EMongoCriteria::SORT_DESC);
+        $criteria->sort('last_visit_time',EMongoCriteria::SORT_DESC);
+        $criteria->limit(5);
+        $cursor = RUser::model()->findAll($criteria);
+        $rows = RUser::model()->parse($cursor,true,array('id','user_name','sex','avatar','level','city_info','certify_status','certify_info','can_access'));
+        $hot_users = array();
+        foreach ($rows as $value) {
+            $value['recommend_reason'] = '活跃用户';
+            $hot_users[] = $value;
+        }
+
+        $result = array_merge($certify_users,$local_user,$hot_users);
+        shuffle($result);
+        foreach ($result as $key => $user) {
+            $result[$key]['relation'] = $user_node->relation($user['id']);
+        }
+        CommonFn::requestAjax(true,CommonFn::getMessage('message','operation_success'),array('recommend_list'=>$result));
+    }
+
+    //用户登出接口
+    public function actionLogout(){
+        $user_id = Yii::app()->getRequest()->getParam("user_id");
+        $xinge_token = Yii::app()->getRequest()->getParam("xinge_token");
+        $app_client_id = Yii::app()->getRequest()->getParam("app_client_id");
+        require_once(APP_PATH."/protected/vendors/tencent/XingeApp.php");
+        if($app_client_id == '2'){
+            $xinge_config = Yii::app()->params['xingeConfig']['android'];
+            $push = new XingeApp($xinge_config['accessId'],$xinge_config['secretKey']);
+            $ret = $push->DeleteTokenOfAccount($user_id,$xinge_token);
+            CommonFn::requestAjax(true,'注销成功');
+        }elseif($app_client_id == '1'){
+            $xinge_ios_config = Yii::app()->params['xingeConfig']['ios'];
+            $push = new  XingeApp($xinge_ios_config['accessId'],$xinge_ios_config['secretKey']);
+            $ret = $push->DeleteTokenOfAccount($user_id,$xinge_token);
+            CommonFn::requestAjax(true,'注销成功');
+        }else{
+            CommonFn::requestAjax(false,'操作失败');
+        }
+
+
+    }
+
+
+}

+ 0 - 0
www/protected/modules/api/views/error/index.php