<?php

/**
 * 本类放置与客户端通信的内容
 * 格式为XML
 * @author 杨金球
 */
class ApiAction extends Action {

    /**
     * 本类含有两个参数
     * @param action  表示执行条件 (这里太乱了。自己看吧)
     * @param page    表示当前页面。默认为1
     */
    public function softimf() {
        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        $action = isset($_POST['action']) ? $_POST['action'] : '';

        switch ($action) {
            case 'good':    //精品推荐
                $map['status'] = 1;
                $map['recommend'] = 1;
                $order = 'recommend_order ASC';
                $this->software('good', $page, $map, $order);
                break;
            case 'newest':      //最新上架
                $map['status'] = 1;
                $map['jumpurl'] = 0;
                $order = C('DB_PREFIX') . 'software.time DESC';
                $this->software('newest', $page, $map, $order);
                break;
            case 'show':       //头部推荐
                $map['status'] = 1;
                $map['apk_show'] = 1;
                $map['jumpurl'] = 0;
                $order = 'AVG(' . C('DB_PREFIX') . 'comment.score) DESC';
                $this->software('good', $page, $map, $order);
                break;
            case 'discovernum' : //返回”探索发现”中应用排行的数据列表
                $map['menu_id'] = C('HOME_APPLY_ID');
                $map[C('DB_PREFIX') . 'software.status'] = 1;
                $this->typeDownload($page, $map);
                break;
            case 'discovergame' : //返回”探索发现”中游戏排行的数据列表
                $map['menu_id'] = C('HOME_GAMEACTION_ID');
                $map[C('DB_PREFIX') . 'software.status'] = 1;
                $this->typeDownload($page, $map);
                break;
            case 'discover_down' : //返回大家正在下载数据列表(1小时)
                //$map = 'bpi_software.status = 1 AND bpi_download.time > DATE_SUB(DATE_FORMAT(NOW(),"%Y-%m-%d %H:%i:%s"),INTERVAL 1 HOUR)'; //大于当前时间减去1小时
                $map = C('DB_PREFIX') . 'software.status = 1';
                $order = C('DB_PREFIX') . 'download.time DESC';
                $this->hotDown('discover_down', $page, $map, $order);
                break;
            case 'discovernew' : //返回上升最快数据列表(一个星期)
                $map = C('DB_PREFIX') . 'software.status = 1 AND ' . C('DB_PREFIX') . 'download.time > DATE_SUB(DATE_FORMAT(NOW(),"%Y-%m-%d %H:%i:%s"),INTERVAL 7 DAY)'; //下载时间大于当前时间减去7天
                $order = 'count(' . C('DB_PREFIX') . 'download.soft_id) DESC';
                $this->hotDown('discovernew', $page, $map, $order);
                break;
            case 'share_new' : //返回最新推荐信息
                $map[C('DB_PREFIX') . 'software.status'] = 1;
                $order = C('DB_PREFIX') . 'recommend.time DESC';
                $this->shareNew($page, $map, $order);
                break;
            case 'share_popolarity' :  //返回人气推荐信息
                // $map = 'bpi_download.time > DATE_SUB(DATE_FORMAT(NOW(),"%Y-%m-%d %H:%i:%s"),INTERVAL 7 DAY)'; //下载时间大于当前时间减去7天
                $map = 1;
                $order = 'count(' . C('DB_PREFIX') . 'download.soft_id) DESC';
                $this->sharePopolarity($page, $map, $order);
                break;
        }
    }

    /**
     * 在softimf方法中实例化software中的方法调用
     * @param type $action  操作
     * @param type $page    当前页数
     * @param type $map     搜索条件    
     * @param type $order   排列规则
     * 目前调用有精品推荐 和 最新上架
     */
    public function software($action, $page, $map, $order) {
        $limit = C('LIMIT');    //每页显示数量
        $firstRows = ($page - 1) * $limit; //当前页第一条索引

        $software = M('software');

        $software_list = $software->field(C('DB_PREFIX') . 'software.id, name, mobile_name, version, icon, ROUND(AVG(' . C('DB_PREFIX') . 'comment.score),1) AS score, language')
                        ->join(C('DB_PREFIX') . 'comment ON ' . C('DB_PREFIX') . 'software.id = ' . C('DB_PREFIX') . 'comment.soft_id')
                        ->where($map)->group(C('DB_PREFIX') . 'software.id')->order($order)->limit($firstRows . ',' . $limit)->select();

        $dom = new DOMDocument('1.0', 'utf-8');
        if ($action == 'good') {     //根据不同的action创建不同的XML父元素
            $response = $dom->createElement('SpecialRecommendation');
        } else if ($action == 'newest') {
            $response = $dom->createElement('shelve');
        }
        $dom->appendChild($response);

        $count = count($software_list);
        for ($i = 0; $i < $count; $i++) {
            $soft = $dom->createElement('soft'); //创建单类别父元素
            $response->appendChild($soft);

            $id = $dom->createElement('id');
            $soft->appendChild($id);
            $id->appendChild($dom->createTextNode($software_list[$i]['id']));

            $name = $dom->createElement('name');
            $soft->appendChild($name);
            $name->appendChild($dom->createTextNode($software_list[$i]['name']));

            $authorname = $dom->createElement('authorname');
            $soft->appendChild($authorname);
            $authorname->appendChild($dom->createTextNode($software_list[$i]['mobile_name']));

            $starlevel = $dom->createElement('starlevel');
            $soft->appendChild($starlevel);
            $starlevel->appendChild($dom->createTextNode(empty($software_list[$i]['score']) ? 0 : $software_list[$i]['score']));

            $version = $dom->createElement('version');
            $soft->appendChild($version);
            $version->appendChild($dom->createTextNode($software_list[$i]['version']));

            $language = $dom->createElement('language');
            $soft->appendChild($language);
            $language->appendChild($dom->createTextNode($software_list[$i]['language'] == '中文' ? 1 : 0));

            $icon = $dom->createElement('icon');
            $soft->appendChild($icon);
            $icon->appendChild($dom->createTextNode('/Public/Upload/soft_icon/' . $software_list[$i]['icon']));
        }
        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 返回各类别中下载量排行
     * @param type $page 当前页数
     * @param type $map  搜索条件
     */
    public function typeDownload($page, $map) {
        $order = 'download DESC';
        $limit = C('LIMIT');    //每页显示数量
        $firstRows = ($page - 1) * $limit; //当前页第一条索引

        $soft = M('soft_belong');

        $soft_list = $soft->field(C('DB_PREFIX') . 'soft_belong.soft_id as id, name, mobile_name, version, icon, COUNT(' . C('DB_PREFIX') . 'download.soft_id) AS download, language')
                        ->join(C('DB_PREFIX') . 'software ON ' . C('DB_PREFIX') . 'software.id = ' . C('DB_PREFIX') . 'soft_belong.soft_id')
                        ->join(C('DB_PREFIX') . 'download ON ' . C('DB_PREFIX') . 'download.soft_id = ' . C('DB_PREFIX') . 'soft_belong.soft_id')
                        ->where($map)->group(C('DB_PREFIX') . 'soft_belong.soft_id')->order($order)->limit($firstRows . ',' . $limit)->select();

        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('Discover');
        $dom->appendChild($response);

        for ($i = 0; $i < count($soft_list); $i++) { //创建节点
            $soft = $dom->createElement('soft');
            $response->appendChild($soft);

            $id = $dom->createElement('id');
            $soft->appendChild($id);
            $id->appendChild($dom->createTextNode($soft_list[$i]['id']));

            $name = $dom->createElement('name');
            $soft->appendChild($name);
            $name->appendChild($dom->createTextNode($soft_list[$i]['name']));

            $authorname = $dom->createElement('authorname');
            $soft->appendChild($authorname);
            $authorname->appendChild($dom->createTextNode($soft_list[$i]['mobile_name']));

            $starlevel = $dom->createElement('starlevel');
            $soft->appendChild($starlevel);
            $starlevel->appendChild($dom->createTextNode(isset($soft_list[$i]['score']) ? $soft_list[$i]['score'] : 0));

            $version = $dom->createElement('version');
            $soft->appendChild($version);
            $version->appendChild($dom->createTextNode($soft_list[$i]['version']));

            $language = $dom->createElement('language');
            $soft->appendChild($language);
            $language->appendChild($dom->createTextNode($soft_list[$i]['language'] == '中文' ? 1 : 0));

            $icon = $dom->createElement('icon');
            $soft->appendChild($icon);
            $icon->appendChild($dom->createTextNode('/Public/Upload/soft_icon/' . $soft_list[$i]['icon']));
        }

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 返回‘大家正在下载’,‘上升最快’数据
     * @param type $action  标志属于哪个方法
     * @param type $page    当前分页
     * @param type $map     搜索条件
     * @param type $order   排序规则
     */
    public function hotDown($action, $page, $map, $order) {
        $limit = C('LIMIT');    //每页显示数量
        $firstRows = ($page - 1) * $limit; //当前页第一条索引

        $download = M('download');

        if ($action == 'discover_down') {
            $download_list = $download->field(C('DB_PREFIX') . 'download.soft_id AS id, name, version, mobile_name, icon, ROUND(AVG(' . C('DB_PREFIX') . 'comment.score), 1) AS score, language')
                            ->join(C('DB_PREFIX') . 'software ON ' . C('DB_PREFIX') . 'software.id = ' . C('DB_PREFIX') . 'download.soft_id')
                            ->join(C('DB_PREFIX') . 'comment ON ' . C('DB_PREFIX') . 'comment.soft_id = ' . C('DB_PREFIX') . 'download.soft_id')
                            ->where($map)->group(C('DB_PREFIX') . 'download.id')->order($order)->limit($firstRows . ',' . $limit)->select();
        } else if ($action == 'discovernew') {
            $download_list = $download->field(C('DB_PREFIX') . 'download.soft_id AS id, name, mobile_name, version,icon, count(' . C('DB_PREFIX') . 'download.soft_id) AS download, TMP.score, language')
                            ->join(C('DB_PREFIX') . 'software ON ' . C('DB_PREFIX') . 'software.id = ' . C('DB_PREFIX') . 'download.soft_id')
                            ->join('(SELECT soft_id, ROUND(AVG(score), 1) AS score FROM `' . C('DB_PREFIX') . 'comment` GROUP BY soft_id) AS TMP ON TMP.soft_id = ' . C('DB_PREFIX') . 'download.soft_id')
                            ->where($map)->group(C('DB_PREFIX') . 'download.soft_id')->order($order)->limit($firstRows . ',' . $limit)->select();
        }
        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('Discover');
        $dom->appendChild($response);

        for ($i = 0; $i < count($download_list); $i++) { //创建节点
            $soft = $dom->createElement('soft');
            $response->appendChild($soft);

            $id = $dom->createElement('id');
            $soft->appendChild($id);
            $id->appendChild($dom->createTextNode($download_list[$i]['id']));

            $name = $dom->createElement('name');
            $soft->appendChild($name);
            $name->appendChild($dom->createTextNode($download_list[$i]['name']));

            $authorname = $dom->createElement('authorname');
            $soft->appendChild($authorname);
            $authorname->appendChild($dom->createTextNode($download_list[$i]['mobile_name']));

            $starlevel = $dom->createElement('starlevel');
            $soft->appendChild($starlevel);
            $starlevel->appendChild($dom->createTextNode(empty($download_list[$i]['score']) ? 0 : $download_list[$i]['score']));

            $version = $dom->createElement('version');
            $soft->appendChild($version);
            $version->appendChild($dom->createTextNode($download_list[$i]['version']));

            $language = $dom->createElement('language');
            $soft->appendChild($language);
            $language->appendChild($dom->createTextNode($download_list[$i]['language'] == '中文' ? 1 : 0));

            $icon = $dom->createElement('icon');
            $soft->appendChild($icon);
            $icon->appendChild($dom->createTextNode('/Public/Upload/soft_icon/' . $download_list[$i]['icon']));
        }

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 返回‘发现。分享 中最新推荐’数据列表
     * @param type $page    当前分页
     * @param type $map     搜索条件
     * @param type $order   排序规则
     */
    public function shareNew($page, $map, $order) {
        $limit = C('LIMIT');    //每页显示数量
        $firstRows = ($page - 1) * $limit; //当前页第一条索引

        $recommend = M('recommend');
        //搜索当前最新推荐信息列表
        $recommend_list = $recommend->field(C('DB_PREFIX') . 'recommend.user_id, ' . C('DB_PREFIX') . 'user.name AS username, ' . C('DB_PREFIX') . 'user.bbs_id, 
                                              soft_id, ' . C('DB_PREFIX') . 'software.name, ' . C('DB_PREFIX') . 'software.mobile_name, icon, TMP.count AS recommend_num, language')
                        ->join(C('DB_PREFIX') . 'user ON ' . C('DB_PREFIX') . 'user.id = ' . C('DB_PREFIX') . 'recommend.user_id')
                        ->join(C('DB_PREFIX') . 'software ON ' . C('DB_PREFIX') . 'software.id = ' . C('DB_PREFIX') . 'recommend.soft_id')
                        ->join('(SELECT user_id, COUNT(user_id) AS count FROM ' . C('DB_PREFIX') . 'recommend GROUP BY user_id) AS TMP ON TMP.user_id = ' . C('DB_PREFIX') . 'recommend.user_id')
                        ->where($map)->order($order)->limit($firstRows . ',' . $limit)->select();

        $recommend_list_count = count($recommend_list);

        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('Share');
        $dom->appendChild($response);

        for ($i = 0; $i < $recommend_list_count; $i++) {
            $soft = $dom->createElement('soft');
            $response->appendChild($soft);

            $id = $dom->createElement('id');
            $soft->appendChild($id);
            $id->appendChild($dom->createTextNode($recommend_list[$i]['user_id']));

            $sharename = $dom->createElement('sharename');
            $soft->appendChild($sharename);
            $sharename->appendChild($dom->createTextNode($recommend_list[$i]['username']));

            $sharenum = $dom->createElement('sharenum');
            $soft->appendChild($sharenum);
            $sharenum->appendChild($dom->createTextNode($recommend_list[$i]['recommend_num']));

            $softname = $dom->createElement('softname');
            $soft->appendChild($softname);
            $softname->appendChild($dom->createTextNode($recommend_list[$i]['name']));

            $authorname = $dom->createElement('authorname');
            $soft->appendChild($authorname);
            $authorname->appendChild($dom->createTextNode($recommend_list[$i]['mobile_name']));

            $shareicon = $dom->createElement('shareicon');
            $soft->appendChild($shareicon);
            $shareicon->appendChild($dom->createTextNode(('/User/images/id=' . $recommend_list[$i]['user_id'] . '&uid=' . $recommend_list[$i]['bbs_id'])));

            $language = $dom->createElement('language');
            $soft->appendChild($language);
            $language->appendChild($dom->createTextNode($recommend_list[$i]['language'] == '中文' ? 1 : 0));

            $softicon = $dom->createElement('softicon');
            $soft->appendChild($softicon);
            $softicon->appendChild($dom->createTextNode('/Public/Upload/soft_icon/' . $recommend_list[$i]['icon']));
        }

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        // $this->display('index');
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 这是个蛋疼的设计，我觉得我得花点时间讲讲这个设计
     * 根据每个用户推荐的不同软件，搜索出当前这个用户所推荐的软件总下载量（一个星期中）进行排序
     * 并搜索出该用户最新推荐的一款软件
     * @param type $page    当前分页
     * @param type $map     搜索条件
     * @param type $order   排序规则
     */
    public function sharePopolarity($page, $map, $order) {
        $limit = C('LIMIT');    //每页显示数量
        $firstRows = ($page - 1) * $limit; //当前页第一条索引

        $model = new Model();
        $recommend_rank = $model->query('SELECT ' . C('DB_PREFIX') . 'recommend.user_id, count(' . C('DB_PREFIX') . 'download.soft_id) AS download, ' . C('DB_PREFIX') . 'user.name AS username, ' . C('DB_PREFIX') . 'user.bbs_id, 
                                        TEMP.software_id, TEMP.software_time, TEMP.name, TEMP.mobile_name, TEMP.recommend_num, TEMP.icon
                                        FROM ' . C('DB_PREFIX') . 'recommend
                                        LEFT JOIN ' . C('DB_PREFIX') . 'download ON ' . C('DB_PREFIX') . 'download.soft_id = ' . C('DB_PREFIX') . 'recommend.soft_id
                                        LEFT JOIN ' . C('DB_PREFIX') . 'user ON ' . C('DB_PREFIX') . 'user.id = ' . C('DB_PREFIX') . 'recommend.user_id
                                        LEFT JOIN (SELECT user_id, TMP.soft_id AS software_id, TMP.time AS software_time, name, mobile_name, icon, count(user_id) AS recommend_num
                                                   FROM (SELECT * FROM ' . C('DB_PREFIX') . 'recommend ORDER BY time DESC) as TMP
                                                   LEFT JOIN ' . C('DB_PREFIX') . 'software ON ' . C('DB_PREFIX') . 'software.id = TMP.soft_id
                                                   GROUP BY user_id
                                        ) AS TEMP ON TEMP.user_id = ' . C('DB_PREFIX') . 'recommend.user_id
                                        WHERE ' . $map . ' 
                                        GROUP BY ' . C('DB_PREFIX') . 'recommend.user_id
                                        ORDER BY ' . $order . ' LIMIT ' . $firstRows . ',' . $limit);
        //dump($recommend_rank);

        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('Share');
        $dom->appendChild($response);

        $recommend_rank_count = count($recommend_rank);
        for ($i = 0; $i < $recommend_rank_count; $i++) {
            $soft = $dom->createElement('soft');
            $response->appendChild($soft);

            $id = $dom->createElement('id');
            $soft->appendChild($id);
            $id->appendChild($dom->createTextNode($recommend_rank[$i]['user_id']));

            $sharename = $dom->createElement('sharename');
            $soft->appendChild($sharename);
            $sharename->appendChild($dom->createTextNode($recommend_rank[$i]['username']));

            $sharenum = $dom->createElement('sharenum');
            $soft->appendChild($sharenum);
            $sharenum->appendChild($dom->createTextNode($recommend_rank[$i]['recommend_num']));

            $softname = $dom->createElement('softname');
            $soft->appendChild($softname);
            $softname->appendChild($dom->createTextNode($recommend_rank[$i]['name']));

            $authorname = $dom->createElement('authorname');
            $soft->appendChild($authorname);
            $authorname->appendChild($dom->createTextNode($recommend_rank[$i]['mobile_name']));

            $shareicon = $dom->createElement('shareicon');
            $soft->appendChild($shareicon);
            $shareicon->appendChild($dom->createTextNode('/User/images/id=' . $recommend_rank[$i]['user_id'] . '&uid=' . $recommend_rank[$i]['bbs_id']));

            $softicon = $dom->createElement('softicon');
            $soft->appendChild($softicon);
            $softicon->appendChild($dom->createTextNode('/Public/Upload/soft_icon/' . $recommend_rank[$i]['icon']));
        }

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        //$this->display('index');
        $this->display('index', 'utf-8', 'text/xml');
    }

    //返回应用类别数据
    public function apptype() {
        $this->type(C('HOME_APPLY_ID'));
    }

    //返回游戏类别数据
    public function gametype() {
        $this->type(C('HOME_GAMEACTION_ID'));
    }

    //返回专题类别数据
    public function subject() {
        $this->type(C('HOME_CUSTOMACTION_ID'));
    }

    //(apptype), (gametype), (subject)统一调用方法
    public function type($id) {
        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        $limit = C('LIMIT');    //每页显示数量
        $firstRows = ($page - 1) * $limit; //当前页第一条索引

        $map['pid'] = $id;
        $map['status'] = 1;
        $map['extend'] = 0;

        $menu = M('menu');

        $menu_list = $menu->field('id, name, `explain`, icon')->where($map)->limit($firstRows . ',' . $limit)->select();

        $dom = new DOMDocument('1.0', 'utf-8');
        if ($id == C('HOME_APPLY_ID')) {
            $response = $dom->createElement('AppType');
        } else if ($id == C('HOME_GAMEACTION_ID')) {
            $response = $dom->createElement('GameType');
        } else if ($id == C('HOME_CUSTOMACTION_ID')) {
            $response = $dom->createElement('SpecialSubject');
        }
        $dom->appendChild($response);

        $count = count($menu_list);
        for ($i = 0; $i < $count; $i++) {
            $node = $dom->createElement('type');
            $response->appendChild($node);

            $pid = $dom->createElement('typeid');
            $node->appendChild($pid);
            $pid->appendChild($dom->createTextNode($menu_list[$i]['id']));

            $name = $dom->createElement('typename');
            $node->appendChild($name);
            $name->appendChild($dom->createTextNode($menu_list[$i]['name']));

            $icon = $dom->createElement('typeicon');
            $node->appendChild($icon);
            $icon->appendChild($dom->createTextNode('/Public/Upload/category/' . $menu_list[$i]['icon']));

            $explain = $dom->createElement('typeIntroductions');
            $node->appendChild($explain);
            $explain->appendChild($dom->createTextNode($menu_list[$i]['explain']));
        }

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 主要用于查看各分类下的(今日热门),(用户评级),(最新上架)
     * @param type $map   查询条件
     * @param type $order 排序规则
     * @param type $page  当前页数
     */
    public function typelist() {
        if (!isset($_POST['id'])) {
            exit();
        }

        if ($_POST['action'] == 'hot') {
            $order = 'down DESC';
        } else if ($_POST['action'] == 'level') {
            $order = 'score DESC';
        } else if ($_POST['action'] == 'new') {
            $order = 'time DESC';
        } else {    //默认
            $order = 'down DESC';
        }

        $map['menu_child_id'] = $_POST['id'];
        $map['status'] = 1;
        $map['jumpurl'] = 0;

        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        $limit = C('LIMIT');    //每页显示数量
        $firstRows = ($page - 1) * $limit; //当前页第一条索引

        $soft = M('soft_belong');

        $soft_list = $soft->field(C('DB_PREFIX') . 'soft_belong.soft_id, name, mobile_name, version, icon, ' . C('DB_PREFIX') . 'software.time, COUNT(' . C('DB_PREFIX') . 'download.soft_id) AS down ,TMP.score, language')
                        ->join(C('DB_PREFIX') . 'software ON ' . C('DB_PREFIX') . 'software.id = ' . C('DB_PREFIX') . 'soft_belong.soft_id')
                        ->join(C('DB_PREFIX') . 'download ON ' . C('DB_PREFIX') . 'soft_belong.soft_id = ' . C('DB_PREFIX') . 'download.soft_id')
                        ->join('LEFT JOIN (SELECT soft_id, ROUND(AVG(score),1) AS score FROM `' . C('DB_PREFIX') . 'comment` GROUP BY soft_id) AS TMP ON ' . C('DB_PREFIX') . 'soft_belong.soft_id = TMP.soft_id')
                        ->where($map)->group(C('DB_PREFIX') . 'soft_belong.soft_id')->order($order)->limit($firstRows . ',' . $limit)->select();
        //dump($soft_list);
        $count = count($soft_list);

        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('TypeList');
        $dom->appendChild($response);

        for ($i = 0; $i < $count; $i++) {
            $s = $dom->createElement('soft');
            $response->appendChild($s);

            $id = $dom->createElement('id');
            $s->appendChild($id);
            $id->appendChild($dom->createTextNode($soft_list[$i]['soft_id']));

            $name = $dom->createElement('name');
            $s->appendChild($name);
            $name->appendChild($dom->createTextNode($soft_list[$i]['name']));

            $mobile_name = $dom->createElement('authorname');
            $s->appendChild($mobile_name);
            $mobile_name->appendChild($dom->createTextNode($soft_list[$i]['mobile_name']));

            $score = $dom->createElement('starlevel');
            $s->appendChild($score);
            $score->appendChild($dom->createTextNode(empty($soft_list[$i]['score']) ? '0' : $soft_list[$i]['score']));

            $version = $dom->createElement('version');
            $s->appendChild($version);
            $version->appendChild($dom->createTextNode($soft_list[$i]['version']));

            $language = $dom->createElement('language');
            $s->appendChild($language);
            $language->appendChild($dom->createTextNode($soft_list[$i]['language'] == '中文' ? 1 : 0));

            $icon = $dom->createElement('icon');
            $s->appendChild($icon);
            $icon->appendChild($dom->createTextNode('/Public/Upload/soft_icon/' . $soft_list[$i]['icon']));
        }

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        // $this->display('index');
        $this->display('index', 'utf-8', 'text/xml');
    }

    //搜索推荐关键字
    public function searchkeyword() {
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $keyword = array();
        $keyword[1] = array('QQ', '聊天', '播放器', '团购', '淘宝', '360', '安全', '微博', '音乐', '视频', '支付宝', 'UC浏览器', '地图');
        $keyword[2] = array('赛车', '泡泡', '愤怒', '向前冲', '塔防', '水果', '捕鱼', '农场', '足球', '篮球', '斗地主', '极品飞车', '僵尸');
        $keyword[3] = array('植物', '急转弯', '输入法', '有道', '土豆', '视频', '影音', '阅读', '天气', '美食', '衣服', '万年历', '闹钟');

        $count = count($keyword[$page]);

        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('Search');
        $dom->appendChild($response);

        $group = $dom->createElement('group');
        $response->appendChild($group);

        for ($i = 0; $i < $count; $i++) {
            $tip = $dom->createElement('tip');
            $group->appendChild($tip);
            $tipText = $dom->createTextNode($keyword[$page][$i]);
            $tip->appendChild($tipText);
        }

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    //搜索
    public function searchimf() {
        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        $limit = C('LIMIT');    //每页显示数量
        $firstRows = ($page - 1) * $limit; //当前页第一条索引

        switch ($_POST['category']) {
            case 'name':
                $map['name'] = array('LIKE', '%' . $_POST['action'] . '%');
                break;
            case 'introduce':
                $map['explain'] = array('LIKE', '%' . $_POST['action'] . '%');
                break;
            case 'author':
                $map['mobile_name'] = array('LIKE', '%' . $_POST['action'] . '%');
                break;
            case 'bag' :
                break;
        }
        $map['status'] = 1;
        $map['jumpurl'] = 0;

        $soft = M('software');

        $soft_list = $soft->field(C('DB_PREFIX') . 'software.id, name, mobile_name, size, version, icon, ROUND(AVG(' . C('DB_PREFIX') . 'comment.score)) AS score, language, url')
                        ->join(C('DB_PREFIX') . 'comment ON ' . C('DB_PREFIX') . 'comment.soft_id = ' . C('DB_PREFIX') . 'software.id')
                        ->where($map)->group(C('DB_PREFIX') . 'software.id')->order('score DESC')->limit($firstRows . ',' . $limit)->select();
        $count = count($soft_list);

        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('Search');
        $dom->appendChild($response);

        for ($i = 0; $i < $count; $i++) {
            $s = $dom->createElement('soft');
            $response->appendChild($s);

            $id = $dom->createElement('id');
            $s->appendChild($id);
            $id->appendChild($dom->createTextNode($soft_list[$i]['id']));

            $name = $dom->createElement('name');
            $s->appendChild($name);
            $name->appendChild($dom->createTextNode($soft_list[$i]['name']));

            $mobile_name = $dom->createElement('authorname');
            $s->appendChild($mobile_name);
            $mobile_name->appendChild($dom->createTextNode($soft_list[$i]['mobile_name']));

            $score = $dom->createElement('starlevel');
            $s->appendChild($score);
            $score->appendChild($dom->createTextNode(empty($soft_list[$i]['score']) ? '0' : $soft_list[$i]['score']));

            $version = $dom->createElement('version');
            $s->appendChild($version);
            $version->appendChild($dom->createTextNode($soft_list[$i]['version']));

            $size = $dom->createElement('size');
            $s->appendChild($size);
            $size->appendChild($dom->createTextNode($soft_list[$i]['size']));

            $language = $dom->createElement('language');
            $s->appendChild($language);
            $language->appendChild($dom->createTextNode($soft_list[$i]['language'] == '中文' ? 1 : 0));

            $icon = $dom->createElement('icon');
            $s->appendChild($icon);
            $icon->appendChild($dom->createTextNode('/Public/Upload/soft_icon/' . $soft_list[$i]['icon']));

            $url = $dom->createElement('url');
            $s->appendChild($url);
            $url->appendChild($dom->createTextNode('/Public/Upload/soft/' . $soft_list[$i]['url']));
        }

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /*
     * 根据软件ID，返回软件详细信息
     */

    public function detailimf() {
        if (!isset($_REQUEST['id'])) {
            exit();
        }
        $map[C('DB_PREFIX') . 'software.id'] = $_REQUEST['id'];
        $map['jumpurl'] = 0;

        $dom = new DOMDocument('1.0', 'utf-8');
        $s = $dom->createElement('soft');
        $dom->appendChild($s);

        $soft = M('software');
        $download = M('download');
        //软件信息  

        $soft_msg = $soft->field(C('DB_PREFIX') . 'software.id, name, mobile_name, charge, version, size, icon, language, ' . C('DB_PREFIX') . 'software.time, `explain`, url, picture,
                                ROUND(AVG(' . C('DB_PREFIX') . 'comment.score), 1)AS score, COUNT(' . C('DB_PREFIX') . 'comment.soft_id) AS comment')
                        ->join(C('DB_PREFIX') . 'comment ON ' . C('DB_PREFIX') . 'comment.soft_id = ' . C('DB_PREFIX') . 'software.id')->where($map)->group(C('DB_PREFIX') . 'software.id')->find();

        //下载数
        $down = $download->field('COUNT(soft_id) AS download')->where('soft_id =' . $map[C('DB_PREFIX') . 'software.id'])->count();
		$soft_msg['time'] = date("Y-m-d",$soft_msg['time']); 

        $id = $dom->createElement('id');
        $s->appendChild($id);
        $id->appendChild($dom->createTextNode($soft_msg['id']));

        $name = $dom->createElement('name');
        $s->appendChild($name);
        $name->appendChild($dom->createTextNode($soft_msg['name']));

        $mobile_name = $dom->createElement('authorname');
        $s->appendChild($mobile_name);
        $mobile_name->appendChild($dom->createTextNode($soft_msg['mobile_name']));

        $score = $dom->createElement('starlevel');
        $s->appendChild($score);
        $score->appendChild($dom->createTextNode(empty($soft_msg['score']) ? '0' : $soft_msg['score']));

        $charge = $dom->createElement('free');
        $s->appendChild($charge);
        $charge->appendChild($dom->createTextNode($soft_msg['charge']));

        $version = $dom->createElement('version');
        $s->appendChild($version);
        $version->appendChild($dom->createTextNode($soft_msg['version']));

        $size = $dom->createElement('size');
        $s->appendChild($size);
        $size->appendChild($dom->createTextNode($soft_msg['size']));

        $icon = $dom->createElement('icon');
        $s->appendChild($icon);
        $icon->appendChild($dom->createTextNode('/Public/Upload/soft_icon/' . $soft_msg['icon']));

        $language = $dom->createElement('language');
        $s->appendChild($language);
        $language->appendChild($dom->createTextNode($soft_msg['language']));

        $downnum = $dom->createElement('downnum');
        $s->appendChild($downnum);
        $downnum->appendChild($dom->createTextNode($down));

        $discussnum = $dom->createElement('discussnum');
        $s->appendChild($discussnum);
        $discussnum->appendChild($dom->createTextNode($soft_msg['comment']));

        $time = $dom->createElement('time');
        $s->appendChild($time);
        $time->appendChild($dom->createTextNode($soft_msg['time']));

        $explain = $dom->createElement('state');
        $s->appendChild($explain);
        $explain->appendChild($dom->createTextNode(strip_tags($soft_msg['explain'])));

        $pic = $dom->createElement('pic');
        $s->appendChild($pic);
        $pictures = explode(',', $soft_msg['picture'], 5);
        if (!empty($pictures[0])) {
            for ($i = 0; $i < count($pictures); $i++) {
                $picture = $dom->createElement('picture');
                $pic->appendChild($picture);
                $picture->appendChild($dom->createTextNode('/Public/Upload/soft_img/' . $pictures[$i]));
            }
        }

        $url = $dom->createElement('url');
        $s->appendChild($url);
        $url->appendChild($dom->createTextNode('/Public/Upload/soft/' . $soft_msg['url']));

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 根据软件ID,返回评论信息
     */
    public function comment() {
        if (!isset($_POST['id'])) {
            exit();
        }

        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        $limit = C('LIMIT');    //每页显示数量
        $firstRows = ($page - 1) * $limit; //当前页第一条索引

        $map[C('DB_PREFIX') . 'comment.soft_id'] = $_POST['id'];

        $dom = new DOMDocument('1.0', 'utf-8');
        $d = $dom->createElement('Discussion');
        $dom->appendChild($d);

        $comment = M('comment');
        $comment_list = $comment->field(C('DB_PREFIX') . 'comment.id, content, time, score, up, down, name, ' . C('DB_PREFIX') . 'soft_version.soft_version')
                        ->join(C('DB_PREFIX') . 'user ON ' . C('DB_PREFIX') . 'comment.user_id = ' . C('DB_PREFIX') . 'user.id')
                        ->join(C('DB_PREFIX') . 'soft_version ON ' . C('DB_PREFIX') . 'soft_version.id = ' . C('DB_PREFIX') . 'comment.soft_version')
                        ->where($map)
                        ->order('time DESC')->limit($firstRows . ',' . $limit)->select();

        $soft = M('software');
        $arg['id'] = $_POST['id'];
        $softVersion = $soft->field('version')->where($arg)->find();

        $count = count($comment_list);
        for ($i = 0; $i < $count; $i++) {
            $dis = $dom->createElement('discuss');
            $d->appendChild($dis);

            $dis_name = $dom->createElement('name');
            $dis->appendChild($dis_name);
            $dis_name->appendChild($dom->createTextNode($comment_list[$i]['name']));

            $dis_state = $dom->createElement('state');
            $dis->appendChild($dis_state);
            $dis_state->appendChild($dom->createTextNode($comment_list[$i]['content']));

            $comment_list[$i]['time'] = date("Y-m-d",$comment_list[$i]['time']); 
			$dis_time = $dom->createElement('time');
            $dis->appendChild($dis_time);
            $dis_time->appendChild($dom->createTextNode($comment_list[$i]['time']));

            $dis_up = $dom->createElement('up');
            $dis->appendChild($dis_up);
            $dis_up->appendChild($dom->createTextNode($comment_list[$i]['up']));

            $dis_down = $dom->createElement('down');
            $dis->appendChild($dis_down);
            $dis_down->appendChild($dom->createTextNode($comment_list[$i]['down']));

            $dis_score = $dom->createElement('starlevel');
            $dis->appendChild($dis_score);
            $dis_score->appendChild($dom->createTextNode($comment_list[$i]['score']));

            $dis_version = $dom->createElement('version');
            $dis->appendChild($dis_version);
            $dis_version->appendChild($dom->createTextNode($comment_list[$i]['soft_version'] == $softVersion['version'] ? '当前版本' : $comment_list[$i]['soft_version']));
        }

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     *  软件评论
     */
    public function commentapi() {
        $softVersion = M('soft_version');
        $map['soft_id'] = $_POST['id'];
        $softVersionId = $softVersion->field('MAX(id) AS id')->where($map)->find();

        $map['user_id'] = $_POST['user_id'];
        $map['soft_version'] = $softVersionId['id'];

        $comment = M('comment');

        /* $dom = new DOMDocument('1.0', 'utf-8');
          $r = $dom->createElement('comment');
          $dom->appendChild($r);

          $result = $dom->createElement('result');
          $r->appendChild($result);

          $reason = $dom->createElement('reason');
          $r->appendChild($reason); */

        if (!$comment->where($map)->find()) {
            $map['content'] = htmlspecialchars(trim($_POST['content']));
            $map['time'] = time();
            $map['score'] = $_POST['score'];

            if ($comment->add($map)) {
                /* $result->appendChild($dom->createTextNode(1));
                  $reason->appendChild($dom->createTextNode('评论成功')); */
                echo '评论成功';
            } else {
                /* $result->appendChild($dom->createTextNode(0));
                  $reason->appendChild($dom->createTextNode('评论失败，请稍后再试')); */
                echo '评论失败，请稍后再试';
            }
        } else {
            /* $result->appendChild($dom->createTextNode(0));
              $reason->appendChild($dom->createTextNode('已经对此版本软件做过评论')); */
            echo '已经对此版本软件做过评论';
        }
        /* $xmlString = $dom->saveXML();
          $this->assign('xml', $xmlString);
          $this->display('index', 'utf-8', 'text/xml'); */
    }

    /**
     * 根据软件ID，返回推荐软件
     */
    public function recommend() {
        if (!isset($_POST['id'])) {
            exit();
        }

        $soft_belong = M('soft_belong');

        $dom = new DOMDocument('1.0', 'utf-8');
        $r = $dom->createElement('Recomment');
        $dom->appendChild($r);

        //相关软件推荐
        //找出当前软件所在类别（子类别，不包含专题推荐中）
        $arg['soft_id'] = $_POST['id'];
        $arg['menu_id'] = array('IN', C('HOME_APPLY_ID') . ',' . C('HOME_GAMEACTION_ID')); //父类别
        $menu = $soft_belong->field('menu_child_id')->where($arg)->find();

        $menu[C('DB_PREFIX') . 'soft_belong.soft_id'] = array('neq', $arg['soft_id']); //去除当前相关推荐中包含本软件
        //获取相关推荐列表
        $recommend_list = $soft_belong->field(C('DB_PREFIX') . 'soft_belong.soft_id AS id, name, mobile_name, version, size, icon, ROUND(AVG(' . C('DB_PREFIX') . 'comment.score)) AS score, language')
                        ->join(C('DB_PREFIX') . 'software ON ' . C('DB_PREFIX') . 'software.id = ' . C('DB_PREFIX') . 'soft_belong.soft_id')
                        ->join(C('DB_PREFIX') . 'comment ON ' . C('DB_PREFIX') . 'comment.soft_id = ' . C('DB_PREFIX') . 'soft_belong.soft_id')
                        ->where($menu)->group(C('DB_PREFIX') . 'soft_belong.soft_id')->order('score DESC')->limit('0, 10')->select();

        $count = count($recommend_list);
        for ($i = 0; $i < $count; $i++) {
            $rec = $dom->createElement('soft');
            $r->appendChild($rec);

            $rec_id = $dom->createElement('id');
            $rec->appendChild($rec_id);
            $rec_id->appendChild($dom->createTextNode($recommend_list[$i]['id']));

            $rec_name = $dom->createElement('name');
            $rec->appendChild($rec_name);
            $rec_name->appendChild($dom->createTextNode($recommend_list[$i]['name']));

            $rec_mobile_name = $dom->createElement('authorname');
            $rec->appendChild($rec_mobile_name);
            $rec_mobile_name->appendChild($dom->createTextNode($recommend_list[$i]['mobile_name']));

            $rec_score = $dom->createElement('starlevel');
            $rec->appendChild($rec_score);
            $rec_score->appendChild($dom->createTextNode(empty($recommend_list[$i]['score']) ? 0 : $recommend_list[$i]['score']));

            $rec_size = $dom->createElement('size');
            $rec->appendChild($rec_size);
            $rec_size->appendChild($dom->createTextNode($recommend_list[$i]['size']));

            $rec_version = $dom->createElement('version');
            $rec->appendChild($rec_version);
            $rec_version->appendChild($dom->createTextNode($recommend_list[$i]['version']));

            $rec_lanuage = $dom->createElement('lanuage');
            $rec->appendChild($rec_lanuage);
            $rec_lanuage->appendChild($dom->createTextNode($recommend_list[$i]['lanuage'] == '中文' ? 1 : 0));

            $rec_icon = $dom->createElement('icon');
            $rec->appendChild($rec_icon);
            $rec_icon->appendChild($dom->createTextNode('/Public/Upload/soft_icon/' . $recommend_list[$i]['icon']));
        }


        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 下载接口
     */
    public function down() {
        $map['id'] = $_REQUEST['id'];
        $map['status'] = 1;

        $arg['soft_id'] = $_REQUEST['id'];
        $arg['user_id'] = isset($_POST['user_id']) ? $_POST['user_id'] : 0;
        $arg['time'] = time();

        $download = M('download');
        $download->add($arg);
		//统计点击次数
		$num = new Model();
		$num->query("UPDATE ".C('DB_PREFIX')."software SET hits=hits+1 WHERE id='$arg[soft_id]'");

        $software = M('software');
        $softMsg = $software->field('id, name, version, size, icon, url')->where($map)->find();

        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('soft');
        $dom->appendChild($response);

        $id = $dom->createElement('id');
        $response->appendChild($id);
        $id->appendChild($dom->createTextNode($softMsg['id']));

        $name = $dom->createElement('name');
        $response->appendChild($name);
        $name->appendChild($dom->createTextNode($softMsg['name']));

        $version = $dom->createElement('version');
        $response->appendChild($version);
        $version->appendChild($dom->createTextNode($softMsg['version']));

        $size = $dom->createElement('size');
        $response->appendChild($size);
        $size->appendChild($dom->createTextNode($softMsg['size']));

        $icon = $dom->createElement('icon');
        $response->appendChild($icon);
        $icon->appendChild($dom->createTextNode('/Public/Upload/soft_icon/' . $softMsg['icon']));

        $url = $dom->createElement('url');
        $response->appendChild($url);
        $url->appendChild($dom->createTextNode('/Public/Upload/soft/' . $softMsg['url']));

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 登录接口
     */
    public function login() {
        if (empty($_POST['name']) || empty($_POST['pwd'])) {
            exit();
        }

        Vendor('Ucenter.UcApi');  //载入UcApi扩展

        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('more');
        $dom->appendChild($response);

        $result = $dom->createElement('result');
        $response->appendChild($result);

        $reason = $dom->createElement('reason');
        $response->appendChild($reason);

        //解密密码
        $pwd = uc_authcode($_POST['pwd'], 'DECODE', C('KEY'));
        $cutName = substr($_POST['name'], 0, strpos($_POST['name'], "@")); //截取用户名
        $user = M('user');
        if (preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/', $_POST['name'])) {
            $map['name'] = $cutName;
        } else {
            $map['name'] = $_POST['name'];
        }
        $userMsg = $user->where($map)->find();
        // 没有绑定论坛
        if (!C('BIND_BBS')) {
            if ($userMsg['pwd'] == md5($pwd)) {
                $id = $dom->createElement('id');
                $response->appendChild($id);
                $id->appendChild($dom->createTextNode($userMsg['id']));

                $result->appendChild($dom->createTextNode(1));
                $reason->appendChild($dom->createTextNode('登录成功'));
            } else {
                $result->appendChild($dom->createTextNode(0));
                $reason->appendChild($dom->createTextNode('登录失败，请检查'));
            }
        } else {    //绑定论坛
            //判断是否邮箱登陆
            if (preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/', $_POST['name'])) {
                $UCuser = new Model();
                $UCuserdb = $UCuser->db('', "" . UC_CONNECT . "://" . UC_DBUSER . ":" . UC_DBPW . "@" . UC_DBHOST . "/" . UC_DBNAME . "")->query("SELECT username FROM `" . UC_PREFIX . "members` WHERE email = '$_POST[name]'");
                if (!$UCuserdb) {
                    $username = $cutName;
                } else {
                    $username = $UCuserdb['0']['username'];
                }
            } else {
                $username = $_POST['name'];
            }
            //$login = UcApi::login($_POST['name'], $pwd);
			$login = UcApi::login($username, $pwd);
            //  UCenter 登录成功
            if (is_array($login)) {
                $id = $dom->createElement('id');
                $response->appendChild($id);
                if ($userMsg) {   // 本地也存在用户
                    //检测本地密码是不是和UCenter密码一致,如不一致就修改本地密码
                    if ($userMsg['pwd'] != md5($pwd)) {
                        $map['pwd'] = md5($pwd);
                        $map['bbs_id'] = $login['uid']; //绑定论坛ID到本地用户表
                        $map['id'] = $userMsg['id'];
                        $user->save($map);
                    }
                    $id->appendChild($dom->createTextNode($userMsg['id']));
                } else {    //本地不存在用户
                    //自动激活
                    $map['pwd'] = md5($pwd);
                    $map['bbs_id'] = $login['uid']; //绑定论坛ID到本地用户表
                    $map['email'] = $_POST['name'];
                    $map['reg_date'] = time();
                    $userID = $user->add($map);
                    $id->appendChild($dom->createTextNode($userID));
                }
                $result->appendChild($dom->createTextNode(1));
                $reason->appendChild($dom->createTextNode('登录成功'));
            } else {
                if ($login == -1) {    //UCenter不存在此用户
                    if ($userMsg) {   //UCenter不存在用户，但是本地存在用户
                        if ($userMsg['pwd'] != md5($pwd)) {   //匹配本地密码不成功
                            $result->appendChild($dom->createTextNode(0));
                            $reason->appendChild($dom->createTextNode('登录失败，请检查'));
                        } else {    //匹配本地密码成功，自动向UCenter注册一个用户
                            if (preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/', $_POST['name'])) {
                                $UCname = $cutName;
                            } else {
                                $UCname = $_POST['name'];
                            }
                            $reg = UcApi::reg($UCname, $pwd, $userMsg['email']);
                            if ($reg > 0) {
                                $map['bbs_id'] = $reg; //绑定论坛ID到本地用户表
                                $map['id'] = $userMsg['id'];
                                $user->save($map);

                                $id = $dom->createElement('id');
                                $response->appendChild($id);
                                $id->appendChild($dom->createTextNode($userMsg['id']));
                                $result->appendChild($dom->createTextNode(1));
                                $reason->appendChild($dom->createTextNode('登录成功'));
                            }
                        }
                    } else {    //UCenter不存在用户，本地也不存在用户
                        $result->appendChild($dom->createTextNode(0));
                        $reason->appendChild($dom->createTextNode('用户名不存在'));
                    }
                } else if ($login == -2) {  //UCenter 密码错误
                    if ($userMsg) {     //本地存在用户
                        if ($userMsg['pwd'] == md5($pwd)) {
                            //本地密码匹配成功，更改UCenter密码
                            uc_user_edit($userMsg['name'], '', $pwd, '', 1);
                            $id = $dom->createElement('id');
                            $response->appendChild($id);
                            $id->appendChild($dom->createTextNode($userMsg['id']));
                            $result->appendChild($dom->createTextNode(1));
                            $reason->appendChild($dom->createTextNode('登录成功'));
                        } else {    //本地密码错误
                            $result->appendChild($dom->createTextNode(0));
                            $reason->appendChild($dom->createTextNode('登录失败，请检查'));
                        }
                    } else {    //本地不存在用户且UCenter登录密码错误
                        $result->appendChild($dom->createTextNode(0));
                        $reason->appendChild($dom->createTextNode('登录失败，请检查'));
                    }
                } else {
                    $result->appendChild($dom->createTextNode(0));
                    $reason->appendChild($dom->createTextNode('登录失败，请检查'));
                }
            }
        }
        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 注册接口
     */
    public function register() {
        if (empty($_POST['mail']) || empty($_POST['pwd'])) {
            exit();
        }

        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('more');
        $dom->appendChild($response);

        $result = $dom->createElement('result');
        $response->appendChild($result);

        $reason = $dom->createElement('reason');
        $response->appendChild($reason);

        if (!preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/', $_POST['mail'])) {    //通过正则验证用户名是否为邮箱格式
            $result->appendChild($dom->createTextNode(0));
            $reason->appendChild($dom->createTextNode('注册名错误，应为邮箱格式'));
        } else {
            $user = M('user');
            if (!C('BIND_BBS')) {   //没有绑定论坛，本地注册
                $map['name'] = substr($_POST['mail'], 0, strpos($_POST['mail'], "@")); //截取邮箱作为用户名
                if ($user->where($map)->find()) {
                    $result->appendChild($dom->createTextNode(0));
                    $reason->appendChild($dom->createTextNode('用户名已经被注册'));
                } else {
                    $map['pwd'] = md5($_POST['pwd']);
                    $map['email'] = $_POST['mail'];
                    $map['reg_date'] = time();
                    $userID = $user->add($map);
                    if (!$userID) {
                        $result->appendChild($dom->createTextNode(0));
                        $reason->appendChild($dom->createTextNode('注册失败，请稍后再试'));
                    } else {
                        $id = $dom->createElement('id');
                        $response->appendChild($id);
                        $id->appendChild($dom->createTextNode($userID));

                        $result->appendChild($dom->createTextNode(1));
                        $reason->appendChild($dom->createTextNode('注册成功'));
                    }
                }
            } else {    //绑定论坛，同步注册
                $UCname = substr($_POST['mail'], 0, strpos($_POST['mail'], "@"));
                $reg = UcApi::reg($UCname, $_POST['pwd'], $_POST['mail']);
                if ($reg <= 0) {
                    $result->appendChild($dom->createTextNode(0));
                    $reason->appendChild($dom->createTextNode(UcApi::getError()));
                } else {
                    $map['name'] = $UCname;
                    if (!$user->where($map)->find()) {
                        $map['pwd'] = md5($_POST['pwd']);
                        $map['email'] = $_POST['mail'];
                        $map['reg_date'] = time();
                        $map['bbs_id'] = $reg;
                        $userID = $user->add($map);
                        $id = $dom->createElement('id');
                        $response->appendChild($id);
                        $id->appendChild($dom->createTextNode($userID));

                        $result->appendChild($dom->createTextNode(1));
                        $reason->appendChild($dom->createTextNode('注册成功'));
                    } else {
                        $result->appendChild($dom->createTextNode(0));
                        $reason->appendChild($dom->createTextNode('用户名已经存在'));
                    }
                }
            }
        }

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 软件升级模块
     */
    public function updateSoft() {
        if (empty($_POST['soft_name']) || empty($_POST['version'])) {
            exit();
        }

        $map['name'] = $_POST['soft_name'];
        $map['jumpurl'] = 0;

        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('more');
        $dom->appendChild($response);


        $result = $dom->createElement('result');
        $response->appendChild($result);

        $reason = $dom->createElement('reason');
        $response->appendChild($reason);

        $software = M('software');
        if ($software->field('id, version')->where($map)->find()) {
            if ($software->version != $_POST['version']) {   //比较版本号
                $result->appendChild($dom->createTextNode(1));
                $reason->appendChild($dom->createTextNode(''));

                $id = $dom->createElement('soft_id');
                $response->appendChild($id);
                $id->appendChild($dom->createTextNode($software->id));
            } else {
                $result->appendChild($dom->createTextNode(0));
                $reason->appendChild($dom->createTextNode('无更新可选择'));
            }
        } else {
            $result->appendChild($dom->createTextNode(0));
            $reason->appendChild($dom->createTextNode('找不到该软件'));
        }

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 软件备份接口
     */
    public function backup() {
        if (empty($_POST['user_id']) || empty($_POST['soft_name']) || empty($_POST['soft_version'])) {
            exit();
        }

        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('more');
        $dom->appendChild($response);

        $result = $dom->createElement('result');
        $response->appendChild($result);

        $reason = $dom->createElement('reason');
        $response->appendChild($reason);

        $map['user_id'] = $_POST['user_id'];
        $map['soft_name'] = $_POST['soft_name'];
        $map['soft_version'] = $_POST['soft_version'];

        $backup = M('soft_backup');
        if (!$backup->where($map)->find()) {
            $software = M('software');
            $arg['name'] = $_POST['soft_name'];
            if ($software->field('id')->where($arg)->find()) {
                $map['soft_id'] = $software->id;
                if ($backup->add($map)) {
                    $result->appendChild($dom->createTextNode(1));
                    $reason->appendChild($dom->createTextNode('备份成功'));
                } else {
                    $result->appendChild($dom->createTextNode(0));
                    $reason->appendChild($dom->createTextNode('备份未完成'));
                }
            } else {
                $result->appendChild($dom->createTextNode(0));
                $reason->appendChild($dom->createTextNode('系统错误，请稍候再试'));
            }
        } else {
            $result->appendChild($dom->createTextNode(0));
            $reason->appendChild($dom->createTextNode('已经备份了此软件'));
        }

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 获取软件备份数据
     */
    public function getBackup() {
        if (!isset($_POST['user_id']) || empty($_POST['user_id'])) {
            exit();
        }

        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        $limit = C('LIMIT');    //每页显示数量
        $firstRows = ($page - 1) * $limit; //当前页第一条索引

        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('more');
        $dom->appendChild($response);

        $softBackup = M('soft_backup');

        $map['user_id'] = intval($_POST['user_id']);
        $map['status'] = 1;

        $softBackupList = $softBackup->field(C('DB_PREFIX') . 'soft_backup.id, ' . C('DB_PREFIX') . 'software.id AS soft_id, ' . C('DB_PREFIX') . 'software.name, icon, size, version ')
                        ->join(C('DB_PREFIX') . 'software ON ' . C('DB_PREFIX') . 'software.id = ' . C('DB_PREFIX') . 'soft_backup.soft_id')
                        ->where($map)->order(C('DB_PREFIX') . 'soft_backup.id DESC')->limit($firstRows . ',' . $limit)->select();
        $count = count($softBackupList);

        for ($i = 0; $i < $count; $i++) {
            $soft = $dom->createElement('soft');
            $response->appendChild($soft);

            $id = $dom->createElement('id');
            $soft->appendChild($id);
            $id->appendChild($dom->createTextNode($softBackupList[$i]['soft_id']));


            $back_id = $dom->createElement('state');
            $soft->appendChild($back_id);
            $back_id->appendChild($dom->createTextNode($softBackupList[$i]['id']));

            $name = $dom->createElement('name');
            $soft->appendChild($name);
            $name->appendChild($dom->createTextNode($softBackupList[$i]['name']));

            $icon = $dom->createElement('icon');
            $soft->appendChild($icon);
            $icon->appendChild($dom->createTextNode('/Public/Upload/soft_icon/' . $softBackupList[$i]['icon']));

            $size = $dom->createElement('size');
            $soft->appendChild($size);
            $size->appendChild($dom->createTextNode($softBackupList[$i]['size']));

            $version = $dom->createElement('version');
            $soft->appendChild($version);
            $version->appendChild($dom->createTextNode($softBackupList[$i]['version']));
        }

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 删除一条备份软件数据
     */
    public function deleteBackup() {
        if (empty($_POST['id']) || empty($_POST['user_id'])) {
            exit();
        }

        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('more');
        $dom->appendChild($response);

        $result = $dom->createElement('result');
        $response->appendChild($result);

        $reason = $dom->createElement('reason');
        $response->appendChild($reason);

        $softBackup = M('soft_backup');
        $map['id'] = intval($_POST['id']);
        $map['user_id'] = intval($_POST['user_id']);

        if ($softBackup->where($map)->delete()) {
            $result->appendChild($dom->createTextNode(1));
            $reason->appendChild($dom->createTextNode('删除成功'));
        } else {
            $result->appendChild($dom->createTextNode(0));
            $reason->appendChild($dom->createTextNode('删除失败，请稍后再试'));
        }
        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 收藏接口
     */
    public function favorites() {
        if (empty($_POST['user_id']) || empty($_POST['soft_id'])) {
            exit();
        }

//        $dom = new DOMDocument('1.0', 'utf-8');
//        $response = $dom->createElement('more');
//        $dom->appendChild($response);
//        $result = $dom->createElement('result');
//        $response->appendChild($result);
//
//        $reason = $dom->createElement('reason');
//        $response->appendChild($reason);


        $softFavorites = M('soft_favorites');
        $map['user_id'] = intval($_POST['user_id']);
        $map['soft_id'] = intval($_POST['soft_id']);

        if (!$softFavorites->where($map)->find()) {
            if ($softFavorites->add($map)) {
//                $result->appendChild($dom->createTextNode(1));
//                $reason->appendChild($dom->createTextNode(''));
                echo '收藏成功';
            } else {
//                $result->appendChild($dom->createTextNode(0));
//                $reason->appendChild($dom->createTextNode('收藏失败，请稍后再试'));
                echo '收藏失败，请稍后再试';
            }
        } else {
//            $result->appendChild($dom->createTextNode(0));
//            $reason->appendChild($dom->createTextNode('已经收藏了此软件'));
            echo '已经收藏了此软件';
        }

//        $xmlString = $dom->saveXML();
//        $this->assign('xml', $xmlString);
//        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 返回收藏数据
     */
    public function getFavorites() {
        if (empty($_POST['user_id'])) {
            exit();
        }
        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        $limit = C('LIMIT');    //每页显示数量
        $firstRows = ($page - 1) * $limit; //当前页第一条索引

        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('more');
        $dom->appendChild($response);

        $softFavorites = M('soft_favorites');
        $map[C('DB_PREFIX') . 'soft_favorites.user_id'] = intval($_POST['user_id']);

        $softFavoritesList = $softFavorites->field(C('DB_PREFIX') . 'soft_favorites.id AS favorites_id, ' . C('DB_PREFIX') . 'software.id, name, mobile_name, 
                                                    icon, size, version , ROUND(AVG(' . C('DB_PREFIX') . 'comment.score),1) AS score, url')
                        ->join(C('DB_PREFIX') . 'software ON ' . C('DB_PREFIX') . 'soft_favorites.soft_id = ' . C('DB_PREFIX') . 'software.id')
                        ->join(C('DB_PREFIX') . 'comment ON ' . C('DB_PREFIX') . 'soft_favorites.soft_id = ' . C('DB_PREFIX') . 'comment.soft_id')
                        ->where($map)->group(C('DB_PREFIX') . 'software.id')->order(C('DB_PREFIX') . 'soft_favorites.id DESC')->limit($firstRows . ',' . $limit)->select();

        $count = count($softFavoritesList);
        for ($i = 0; $i < $count; $i++) {
            $soft = $dom->createElement('soft');
            $response->appendChild($soft);

            $favorites_id = $dom->createElement('state');
            $soft->appendChild($favorites_id);
            $favorites_id->appendChild($dom->createTextNode($softFavoritesList[$i]['favorites_id']));

            $id = $dom->createElement('id');
            $soft->appendChild($id);
            $id->appendChild($dom->createTextNode($softFavoritesList[$i]['id']));

            $name = $dom->createElement('name');
            $soft->appendChild($name);
            $name->appendChild($dom->createTextNode($softFavoritesList[$i]['name']));

            $score = $dom->createElement('starlevel');
            $soft->appendChild($score);
            $score->appendChild($dom->createTextNode(empty($softFavoritesList[$i]['score']) ? 0 : $softFavoritesList[$i]['score']));

            $mobile_name = $dom->createElement('mobile_name');
            $soft->appendChild($mobile_name);
            $mobile_name->appendChild($dom->createTextNode($softFavoritesList[$i]['authorname']));

            $icon = $dom->createElement('icon');
            $soft->appendChild($icon);
            $icon->appendChild($dom->createTextNode('/Public/Upload/soft_icon/' . $softFavoritesList[$i]['icon']));

            $size = $dom->createElement('size');
            $soft->appendChild($size);
            $size->appendChild($dom->createTextNode($softFavoritesList[$i]['size']));

            $version = $dom->createElement('version');
            $soft->appendChild($version);
            $version->appendChild($dom->createTextNode($softFavoritesList[$i]['version']));

            $url = $dom->createElement('url');
            $soft->appendChild($url);
            $url->appendChild($dom->createTextNode('/Public/Upload/soft/' . $softFavoritesList[$i]['url']));
        }

        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }

    /**
     * 删除一条收藏软件信息
     */
    public function deleteFavorites() {
        if (empty($_POST['id']) || empty($_POST['user_id'])) {
            exit();
        }
        $dom = new DOMDocument('1.0', 'utf-8');
        $response = $dom->createElement('more');
        $dom->appendChild($response);

        $result = $dom->createElement('result');
        $response->appendChild($result);

        $reason = $dom->createElement('reason');
        $response->appendChild($reason);


        $softFavorites = M('soft_favorites');
        $map['soft_id'] = intval($_POST['id']);
        $map['user_id'] = intval($_POST['user_id']);

        if ($softFavorites->where($map)->delete()) {
            $result->appendChild($dom->createTextNode(1));
            $reason->appendChild($dom->createTextNode('删除成功'));
        } else {
            $result->appendChild($dom->createTextNode(0));
            $reason->appendChild($dom->createTextNode('删除失败'));
        }
        $xmlString = $dom->saveXML();
        $this->assign('xml', $xmlString);
        $this->display('index', 'utf-8', 'text/xml');
    }
	
	/*增加下载次数*/
	public function getSoftDown(){
		$map['soft_id'] = intval($_REQUEST['soft_id']);
		$map['time'] = time();
		$map['user_id'] = 0;
		//dump($map);
		//统计点击次数
		$num = new Model();
		$num->query("UPDATE ".C('DB_PREFIX')."software SET hits=hits+1 WHERE id='".$map['soft_id']."'");
		$download = M('download');
		$download->add($map);
		$this->display('index');
	}
}

?>
