php调接口批量同步本地文件到cos或者oss

喜夏-厌秋 提交于 2019-12-12 02:54:07

代码:

<?php
namespace Main\Controller;

use Common\Library\Vendor\ElasticSearch;
use Common\Library\Vendor\Page;
use General\Classes\QcloudApi;
use General\Classes\AcloudApi;
use General\Constant\AppDownloadStatus;
use Role\Constant\RoleInfo;

function read_all_dir_and_file($dir) {
    $qcloud  = new AcloudApi();
    if (is_dir($dir)) {
        $dh = opendir($dir);
        while ( ($file = readdir($dh)) !== false ) {
            if (in_array($file, ['.', '..'])) {
                continue;
            }
            
            $file_path = $dir.'/'.$file;
            if ( is_dir($file_path) ) {
                read_all_dir_and_file($file_path);
            } else {
                //echo $file_path."\n";
                //$qcloud  = new QcloudApi();
                $body    = $file_path;
                $keys    = ltrim($body, '.');
                $results = $qcloud->uploadfile($keys, $body);
                echo $file_path . ' 上传成功<br>';
            }
        }    
        closedir($dir);
         echo '{$dir} 目录上传完毕<br>';
    } else {
        echo $dir;
    }
}

/**
 * 应用控制器
 */
class AppsController extends MainController
{

    private $listRows = 20;

    /**
     * 应用列表
     * @param string    null
     * @return array
     * @author 流川枫 <510268196@qq.com>
     */
    public function index()
    {
        $AppsModel         = D('Apps');
        $ViewAppOwnerModel = D('ViewAppOwner');
        $page              = I('page', 1, 'intval');
        if ($page < 1) {
            $page = 1;
        }

        $kwd   = I('kwd', '');
        $field = I('field', '');

        $where = array();
        if ($kwd && $field) {
            // 这里读视图表,不用使用前缀的,记得更新视图表
            $where[$field] = array('LIKE', '%' . $kwd . '%');
            // $_field = C('DB_PREFIX'). 'apps.' . $field;
        }
        // $where[$_field] = array('LIKE','%'.$kwd.'%');

        // 根据是否有mem_id来获取厂家信息 By Jepeng
        $is_vendor  = $this->role_info['role_id'] == RoleInfo::Vendor;
        $is_channel = $this->role_info['role_id'] == RoleInfo::Channel;

        $VendorModel  = D('Vendor');
        $ChannelModel = D('Channel');
        if ($this->mem_id && $is_vendor) {
            $channel = $ChannelModel->getVendorChannelList($this->mem_id);
            array_push($channel, $this->mem_id, 1);
            $where['mem_id'] = array('in', $channel);
        } elseif ($this->mem_id && $is_channel) {
            $vendor_id       = $ChannelModel->getAppChannelVendor($this->mem_id);
            $map             = array($vendor_id[0]['mem_id'], $this->mem_id, 1);
            $where['mem_id'] = array('in', $map);
        }

        if ($is_vendor || $is_channel) {
            $app_mem_id = $this->mem_id;
        } else {
            $app_mem_id = 1;
        }

        $_where = my_serialize($where); //搜索条件序列化,导出用

        $info   = $ViewAppOwnerModel->get_owner_list($where, $page, $this->listRows);
        $total  = $AppsModel->getCount($where);
        $p      = new Page($total, $this->listRows);
        $paging = $p->show();

        $this->assign(array(
            'kwd'        => $kwd,
            'field'      => $field,
            'paging'     => $paging,
            'info'       => $info,
            'app_mem_id' => $app_mem_id,
            '_where'     => $_where,
        ));
        $this->display('list');
    }

    /**
     * 添加应用
     * @param string  $data  收集的表单数据
     * @return int
     * @author 流川枫 <510268196@qq.com>
     */
    public function add()
    {
        //取出应用类型
        $AppCategoryModel = D('AppCategory');
        $category_info    = $AppCategoryModel->getTree();
        $this->assign('category_info', $category_info);
        $this->display('add');
    }

    /**
     * @desc 添加应用操作
     */
    public function addProc()
    {
        $AppsModel       = D('Apps');
        $AppVersionModel = D('AppVersion');

        $AppsModel->startTrans();

        $app_cate_id  = I('post.app_cate_id', '', 'trim');
        $name         = I('post.name', '', 'trim');
        $package      = I('post.package', '', 'trim');
        $size         = I('post.size', '', 'trim');
        $version      = I('post.version', '', 'trim');
        $developer    = I('post.developer', '', 'trim');
        $description  = I('post.description', '', 'trim');
        $image        = I('post.image', '', 'trim');
        $apk_path     = I('post.apk_path', '', 'trim');
        $download_url = I('post.download_url', '', 'trim');
        $status       = I('post.status', '0', intval);
        $push         = I('post.push', '0', intval);
        $remark       = I('post.remark', '', 'trim');
        $is_charge    = I('post.is_charge', '0', intval);
        $price        = I('post.price', '0.00', 'float');

        $app_exsit = false;
        $app_info  = $AppsModel->where(array('package' => $package, 'mem_id' => $this->mem_id))->find(); //getDataByPackage($package);
        if ($app_info) {
            //$this->error('此应用已存在');
            $app_exsit = true;
        }

        //添加app信息
        $data = array(
            'app_cate_id'  => $app_cate_id, //应用分类主键ID
            'name'         => $name,
            'package'      => $package,
            'size'         => $size,
            'version'      => $version,
            'developer'    => $developer,
            'description'  => $description,
            'image'        => $image,
            'apk_path'     => $apk_path,
            'download_url' => $download_url,
            'status'       => $status,
            'remark'       => $remark,
            'is_charge'    => $is_charge,
            'price'        => $price,
            'create_time'  => time(),
            'create_ip'    => get_client_ip(0, true),
        );

        // 添加mem_id BY JEPENG
        $is_vendor  = $this->role_info['role_id'] == RoleInfo::Vendor;
        $is_channel = $this->role_info['role_id'] == RoleInfo::Channel;

        // 数据是保存在拥有者的表
        if ($is_vendor || $is_channel) {
            $data['mem_id'] = $this->mem_id;
        } else {
            $data['mem_id'] = 1;
        }

        if (!$app_exsit) {
            $res = $AppsModel->tianJia($data);

            if ($res === false) {
                // 记录日志
                $logData = array('module' => '应用市场', 'action' => '添加应用', 'remark' => '添加应用失败', 'status' => 0);
                recordActionLog($logData);

                $AppsModel->rollback();
                $this->error('添加应用失败:' . $AppsModel->getError());
            }

            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '添加应用', 'remark' => '应用编号:' . $res, 'status' => 1);
            recordActionLog($logData);
        } else {
            //如果应用存在,则检测该应用的该版本是否存在
            $app_id       = $app_info['id'];
            $res          = $app_id;
            $version_info = $AppVersionModel->getVersion(array('app_id' => $app_id, 'version' => $version));

            $have_mem = $app_info['mem_id'];
            if ($have_mem != $data['mem_id']) {
                $res = $AppsModel->tianJia($data);

                if ($res === false) {
                    // 记录日志
                    $logData = array('module' => '应用市场', 'action' => '添加应用', 'remark' => '添加应用失败', 'status' => 0);
                    recordActionLog($logData);

                    $AppsModel->rollback();
                    $this->error('添加应用失败:' . $AppsModel->getError());
                }
            } elseif ($version_info) {
                // 如果版本号也存在,则提示为不能添加
                if (($have_mem > 0 || $have_mem == 0) && $have_mem == $data['mem_id']) {
                    $this->error('此版本的应用已存在,如果确实需要上传该应用,请保证包名或版本不重复');
                }

            } else {
                $res = $AppsModel->tianJia($data);

                if ($res === false) {
                    // 记录日志
                    $logData = array('module' => '应用市场', 'action' => '添加应用', 'remark' => '添加应用失败', 'status' => 0);
                    recordActionLog($logData);

                    $AppsModel->rollback();
                    $this->error('添加应用失败:' . $AppsModel->getError());
                }
            }
        }

        //添加app版本信息
        $info = array(
            'app_id'       => $res,
            'package'      => $package,
            'size'         => $size,
            'apk_path'     => $apk_path,
            'download_url' => $download_url,
            'remark'       => $remark,
            'version'      => $version,
            'status'       => $status,
            'push'         => $push,
        );

        $ver_id = $AppVersionModel->tianjia($info);

        //更新应用版本信息
        if (version_compare($version, $app_info['version'], '>')) {
            // 更新版本表的数据
            $update['version'] = $version;
            $res               = $AppsModel->where('id = ' . $res)->save($update);
        }
        if ($ver_id === false) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '添加应用版本信息', 'remark' => '添加应用版本信息失败', 'status' => 0);
            recordActionLog($logData);

            $AppsModel->rollback();
            $this->error('添加应用版本失败:' . $AppsModel->getError());
        }
        $AppsModel->commit();

        // 记录日志
        $logData = array('module' => '应用市场', 'action' => '添加应用版本信息', 'remark' => '应用版本编号:' . $ver_id, 'status' => 1);
        recordActionLog($logData);
        $this->success('添加成功!', U('/Main/Apps/index'));
    }

    /**
     * 更新应用
     * @param string  $id  需要更新记录的ID值
     * @param string  $data  根据ID取出的数据
     * @return bool
     * @author 流川枫 <510268196@qq.com>
     */
    public function edit()
    {
        $id          = I('id', 0);
        $app_cate_id = I('app_cate_id', '');
        $AppsModel   = D('Apps');
        //根据接收的ID取出对应的数据
        $data = $AppsModel->getData($id);
        //取出应用类型
        $AppCategoryModel = D('AppCategory');
        $category_info    = $AppCategoryModel->getTree();

        // 获取区域(省级)列表
        $AreaModel = D('Area');
        $where     = array('pid' => 0);
        $area      = $AreaModel->getList($where);

        //获取厂家信息
        $VendorModel = D('Vendor');
        $where       = array();
        if (!$this->is_super && $this->role != 'system' && $this->role != 'manager' && $this->role != 'operator') {
            //$where['is_default'] = 0;
        }
        $vendor_info = $VendorModel->getAll($where);

        $this->assign(array(
            'id'            => $id,
            'data'          => $data,
            'category_info' => $category_info,
            'app_cate_id'   => $app_cate_id,
            'area'          => $area,
            'vendor_info'   => $vendor_info,
        ));

        $this->display();
    }

    /**
     * @desc 修改应用操作
     */
    public function editProc()
    {
        $id = I('id', 0);

        $AppsModel    = D('Apps');
        $app_cate_id  = I('post.app_cate_id', '');
        $name         = I('post.name', '');
        $package      = I('post.package', '');
        $size         = I('post.size', '');
        $version      = I('post.version', '');
        $developer    = I('post.developer', '');
        $image        = I('post.edit_image', '');
        $apk_path     = I('post.apk_path', '');
        $download_url = I('post.download_url', '');
        $description  = I('post.description', '');
        $status       = I('post.status', '0', intval);
        $remark       = I('post.remark', '');
        $is_charge    = I('post.is_charge', '0', intval);
        $price        = I('post.price', '0.00', 'float');
        $data         = array(
            'app_cate_id'  => $app_cate_id, //应用分类主键ID
            'name'         => $name,
            'package'      => $package,
            'size'         => $size,
            'version'      => $version,
            'developer'    => $developer,
            'description'  => $description,
            'image'        => $image,
            'apk_path'     => $apk_path,
            'download_url' => $download_url,
            'status'       => $status,
            'remark'       => $remark,
            'is_charge'    => $is_charge,
            'price'        => $price,
            'create_time'  => time(),
            'create_ip'    => get_client_ip(0, true),
        );

        $AppsModel = D('Apps');
        if (!$id) {
            $this->error('获取应用ID失败');
        }

        //    if(!$name){
        //     $this->error('请输入应用名称');
        // }
        // if(!$app_cate_id){
        //     $this->error('请选择应用类型');
        // }

        $result = $AppsModel->update($id, $data);
        if ($result !== false) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '更新应用信息', 'remark' => '应用编号:' . $id, 'status' => 1);
            recordActionLog($logData);

            // 更新版本信息
            $AppVersionModel = D('AppVersion');
            $ver_info        = $AppVersionModel->getInfo($package, $version);
            if ($ver_info) {
// 更新
                $data = array(
                    'size'         => $size,
                    'apk_path'     => $apk_path,
                    'download_url' => $download_url,
                    'status'       => $status,
                );
                $where = array('package' => $package, 'version' => $version);
                $res   = $AppVersionModel->update2($where, $data);
            } else {
// 新增
                $data = array(
                    'app_id'       => $id,
                    'package'      => $package,
                    'version'      => $version,
                    'size'         => $size,
                    'apk_path'     => $apk_path,
                    'download_url' => $download_url,
                    'status'       => $status,
                );
                $res = $AppVersionModel->tianJia($data);
            }

            $this->success('修改应用成功!', U('/Main/Apps/index'));
        } else {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '更新应用信息', 'remark' => '更新应用信息失败,应用编号:' . $id, 'status' => 0);
            recordActionLog($logData);

            $this->error('修改应用失败:' . $AppsModel->getError());
        }
    }

    /**
     * @desc 启用/禁用
     */
    public function changeStatus()
    {
        $status = I('status', 0, 'intval');
        if ($status == 1) {
            $action = '启用';
        } else {
            $action = '禁用';
        }
        $id = I('id', '');
        if (!$id) {
            $this->error('请选择要' . $action . '的渠道商');
        }

        $AppsModel = D('Apps');
        $where     = array('id' => array('IN', $id));
        $res       = $AppsModel->where($where)->setField('status', $status);
        //修改对应的版本的状态
        $AppVersionModel = D('AppVersion');
        $res2            = $AppVersionModel->where(array(
            'app_id' => array('IN', $id),
        ))
            ->setField('status', $status);
        if ($res === false) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => $action . '应用', 'remark' => $action . '应用失败,应用编号:' . $id, 'status' => 0);
            recordActionLog($logData);

            $this->error($action . '失败:' . $AppsModel->getError());
        }

        // 记录日志
        $logData = array('module' => '应用市场', 'action' => $action . '应用', 'remark' => '应用编号:' . $id, 'status' => 1);
        recordActionLog($logData);

        $this->success($action . '成功');
    }

    /**
     * @desc 版本管理
     */
    public function versionManage()
    {
        $id   = I('id', '');
        $page = I('page', 1, 'intval');
        if ($page < 1) {
            $page = 1;
        }

        $AppVersionModel = D('AppVersion');
        $AppsModel       = D('Apps');
        $app_info        = $AppsModel->getData($id);

        // 获取发布记录信息
        $AppReleaseModel = D('AppRelease');
        $release_info    = $AppReleaseModel->getData($id);

        //获取对应版本信息
        $where    = array('app_id' => $id);
        $versions = $AppVersionModel->getList($where, $page, $this->listRows);
        $total    = $AppVersionModel->getCount($where);
        $p        = new Page($total, $this->listRows);
        $paging   = $p->show();

        $this->assign(array(
            'id'           => $id,
            'app_info'     => $app_info,
            'release_info' => $release_info,
            'versions'     => $versions,
            'paging'       => $paging,
        ));
        $this->display('version_manage');
    }

    /**
     * @desc 应用版本添加/修改逻辑
     */
    public function versionProc()
    {

        $AppsModel       = D('Apps');
        $AppVersionModel = D('AppVersion');
        $AppReleaseModel = D('AppRelease');

        $id     = I('post.id', ''); //应用版本ID
        $app_id = I('post.app_id', 0, 'intval');
        if (!$app_id) {
            $this->error('缺少应用编号');
        }

        $version      = I('post.version', '', 'trim');
        $package      = I('post.package', '', 'trim');
        $size         = I('post.size', 0, 'intval');
        $apk_path     = I('post.apk_path', '', 'trim');
        $download_url = I('post.download_url', '', 'trim');
        $remark       = I('post.remark', '', 'trim');
        $status       = I('post.status', 0, 'intval'); // 允许/禁止下载
        $push         = I('post.push', 0, 'intval'); // 主动推送

        if (!$version) {
            $this->error('缺少版本');
        }
        if (!$size) {
            $this->error('大小不能为0');
        }
        if (!$id) {
            if (!$package) {
                $this->error('缺少包名,请先上传APK');
            }
            if (!$apk_path || !$download_url) {
                $this->error('请先上传APK');
            }
        }

        $pattern = '/version\/(.+?)(\.html|\/)/i';
        $matches = array();
        $res     = preg_match($pattern, $download_url, $matches);
        if ($res && isset($matches[1])) {
            $download_url = str_replace('version/' . $matches[1], 'version/' . $version, $download_url);
        }

        // 获取应用信息
        $app_info = $AppsModel->getData($app_id);
        if (!$app_info) {
            $this->error('应用不存在');
        }

        $AppVersionModel->startTrans();

        if (!$id) {
            // 判断当前版本的包是否存在
            $ver_info = $AppVersionModel->getInfo($package, $version);

            if ($ver_info) {
                $this->error('当前版本应用已存在');
            }

            // 添加
            $data = array(
                'app_id'       => $app_id,
                'package'      => $package,
                'version'      => $version,
                'size'         => $size,
                'apk_path'     => $apk_path,
                'download_url' => $download_url,
                'download_cnt' => 0,
                'install_cnt'  => 0,
                'status'       => $status,
                'push'         => $push,
                'remark'       => $remark,
            );
            $res = $AppVersionModel->tianJia($data);

            if ($res === false) {
                $logData = array('module' => '应用市场', 'action' => '更新应用版本', 'remark' => '更新应用版本失败', 'status' => 0);
                recordActionLog($logData);

                $AppVersionModel->rollback();
                $this->error('应用版本更新失败');
            }

            if (version_compare($version, $app_info['version'], '>')) {
                // 更新`zh_apps`表
                $up_data = array(
                    'version'      => $version,
                    'size'         => $size,
                    'apk_path'     => $apk_path,
                    'download_url' => $download_url,
                );
                $res = $AppsModel->update($app_id, $up_data);

                if ($res === false) {
                    $logData = array('module' => '应用市场', 'action' => '添加应用版本', 'remark' => '更新应用信息失败', 'status' => 0);
                    recordActionLog($logData);

                    $AppVersionModel->rollback();
                    $this->error('更新应用信息失败');
                }
            }

            // 获取允许下载的版本个数
            $where = array('app_id' => $app_id, 'status' => 1);
            $cnt   = $AppVersionModel->getCount($where);

            // 更新允许下载的版本个数
            $where = array('app_id' => $app_id);
            $data  = array(
                'valid_cnt'   => $cnt,
                'update_time' => time(), //更新应用发布
            );
            $res = $AppReleaseModel->where($where)->save($data);
            // $res2 = $AppReleaseModel->where($where)->field('id')->select();
            //       $res3 = array();
            //       for ($i=0; $i < count($res2); $i++) {
            //           $res3[$i] = $res2[$i]['id'];
            //       }
            // $sphinx = new Sphinx();
            // $sphinx->setUpdated('app_releases',$res3);

            $logData = array('module' => '应用市场', 'action' => '添加应用版本', 'remark' => '添加应用版本成功', 'status' => 1);
            recordActionLog($logData);

            $AppVersionModel->commit();
            $this->success('添加应用版本成功');
        } else {
            //版本编辑
            $info = array(
                'app_id'       => $app_id,
                'version'      => $version,
                'download_url' => $download_url,
                'size'         => $size,
                'remark'       => $remark,
                'status'       => $status,
                'push'         => $push,
            );

            if (!$version) {
                $this->error('请输入应用版本号');
            }
            if (!$size) {
                $this->error('请输入应用版本大小');
            }

            // 判断当前版本的包是否存在
            $where = array('package' => $package, 'version' => $version, 'id' => array('NEQ', $id));
            $cnt   = $AppVersionModel->getCount($where);
            if ($cnt) {
                $this->error('当前版本应用已存在');
            }

            $res = $AppVersionModel->update($id, $info);
            if ($res === false) {
                // 记录日志
                $logData = array('module' => '应用市场', 'action' => '更新应用版本信息', 'remark' => '更新应用版本信息失败,版本编号:' . $id, 'status' => 0);
                recordActionLog($logData);

                $this->error('更新版本失败');
            }

            // 获取允许下载的版本个数
            $where = array('app_id' => $app_id, 'status' => 1);
            $cnt   = $AppVersionModel->getCount($where);

            // 更新允许下载的版本个数
            $where = array('app_id' => $app_id);
            $data  = array(
                'valid_cnt'   => $cnt,
                'update_time' => time(), //更新应用发布
            );
            $res = $AppReleaseModel->where($where)->save($data);
            // $res2 = $AppReleaseModel->where($where)->field('id')->select();
            //       $res3 = array();
            //       for ($i=0; $i < count($res2); $i++) {
            //           $res3[$i] = $res2[$i]['id'];
            //       }
            // $sphinx = new Sphinx();
            // $sphinx->setUpdated('app_releases',$res3);

            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '更新应用版本信息', 'remark' => '版本编号:' . $id, 'status' => 1);
            recordActionLog($logData);

            $AppVersionModel->commit();
            $this->success('更新成功');
        }

    }

    public function versionList()
    {
        $id   = I('id', '');
        $page = I('page', 1, 'intval');
        if ($page < 1) {
            $page = 1;
        }

        $AppVersionModel = D('AppVersion');
        // 获取发布记录信息
        $AppReleaseModel = D('AppRelease');
        $release_info    = $AppReleaseModel->getData($id);

        //获取对应版本信息
        $where    = array('app_id' => $id);
        $versions = $AppVersionModel->getList($where, $page, $this->listRows);
        $total    = $AppVersionModel->getCount($where);
        $p        = new Page($total, $this->listRows);
        $paging   = $p->show();

        $this->assign(array(
            'id'           => $id,
            'release_info' => $release_info,
            'versions'     => $versions,
            'paging'       => $paging,
        ));
        $this->display('version_list');
    }

    /**
     * @desc 禁止下载/允许下载
     */
    public function changeDownloadMode()
    {
        $status = I('status', 0, 'intval');
        if ($status == 1) {
            $action = '允许下载';
        } else {
            $action = '禁止下载';
        }
        $id = I('id', '');
        if (!$id) {
            $this->error('请选择要' . $action . '的版本');
        }

        $AppReleaseModel = D('AppRelease');
        $AppVersionModel = D('AppVersion');

        $AppVersionModel->startTrans();

        $where = array('id' => array('IN', $id));
        $res   = $AppVersionModel->where($where)->setField('status', $status);

        if (is_array($id)) {
            $_ids = implode(',', $id);
        } else {
            $_ids = $id;
        }
        if ($res === false) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '设为' . $action . '应用', 'remark' => '设为' . $action . '应用失败,应用版本编号:' . $_ids, 'status' => 0);
            recordActionLog($logData);

            $AppVersionModel->rollback();
            $this->error($action . '失败:' . $AppVersionModel->getError());
        }

        // 获取应用编号
        $app_id = $AppVersionModel->where(array('id' => array('IN', $_ids)))->getField('app_id');

        // 获取允许下载的版本个数
        $where = array('app_id' => $app_id, 'status' => 1);
        $cnt   = $AppVersionModel->getCount($where);

        // 更新允许下载的版本个数
        $data = array(
            'valid_cnt'   => $cnt,
            'update_time' => time(), //更新应用发布
        );
        $res = $AppReleaseModel->where(array('app_id' => $app_id))->save($data);
        //    $res2 = $AppReleaseModel->where(array('app_id' => $app_id))->field('id')->select();
        //       $res3 = array();
        //       for ($i=0; $i < count($res2); $i++) {
        //           $res3[$i] = $res2[$i]['id'];
        //       }
        // $sphinx = new Sphinx();
        // $sphinx->setUpdated('app_releases',$res3);

        // 记录日志
        $logData = array('module' => '应用市场', 'action' => '设为' . $action . '应用', 'remark' => '设为' . $action . '应用失败,应用版本编号:' . $_ids, 'status' => 1);
        recordActionLog($logData);

        $AppVersionModel->commit();
        $this->success($action . '成功');
    }

    /**
     * @desc AJAX上传图片
     */
    public function uploadImage()
    {
        $error           = '';
        $msg             = '';
        $file_url        = '';
        $id              = I('id', '');
        $fileElementName = 'image';
        if (!empty($_FILES[$fileElementName]['error'])) {
            switch ($_FILES[$fileElementName]['error']) {
                case '1':
                    $status = -1;
                    $error  = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                    break;
                case '2':
                    $status = -1;
                    $error  = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                    break;
                case '3':
                    $status = -1;
                    $error  = 'The uploaded file was only partially uploaded';
                    break;
                case '4':
                    $status = -1;
                    $error  = 'No file was uploaded.';
                    break;
                case '6':
                    $status = -1;
                    $error  = 'Missing a temporary folder';
                    break;
                case '7':
                    $status = -1;
                    $error  = 'Failed to write file to disk';
                    break;
                case '8':
                    $status = -1;
                    $error  = 'File upload stopped by extension';
                    break;
                case '999':
                default:
                    $status = -1;
                    $error  = 'No error code avaiable';
            }
        } else if (empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none') {
            $status = -1;
            $error  = 'No file was uploaded..';
        } else {
            $saveDir = './Uploads/app/img/' . date('Y') . '/' . date('m') . '/';
            if (!file_exists($saveDir)) {
                mkdir($saveDir, 0755, true);
            }

            $result = $this->uploadProc($saveDir);

            if ($result) {
                $file_name = $result['savename'];
                $file_path = ltrim($result['savepath'], '.');
                $file_url  = $file_path . $file_name;

                $schema   = isSsl() ? 'https' : 'http';
                $full_url = $schema . '://' . $_SERVER['HTTP_HOST'] . $file_url;

                $msg    = '上传成功';
                $status = 1;
            } else {
                $error  = '上传失败';
                $status = -1;
            }
        }
        $data   = array('image' => $full_url);
        $info   = $status == 1 ? $msg : $error;
        $return = array('data' => $data, 'info' => $info, 'status' => $status);
        echo json_encode($return);
    }

    public function uploadTest(){
        ignore_user_abort(true);                     //关闭浏览器也可以执行,只有断开apache httpd连接方可终止了
        set_time_limit(0);                           //可以让程序无限制的执行下去
        //$dir = "./Uploads/app/apk/2017";
        //read_all_dir_and_file($dir);
        //exit('全部上传完毕<br>');
        $dir = "./Uploads/app/apk/2019/06";
        if (is_dir($dir)) {
            $dh = opendir($dir);
            while ( ($file = readdir($dh)) !== false ) {
                if (in_array($file, ['.', '..'])) {
                    continue;
                }
                $file_path = $dir.'/'.$file;
                //echo $file_path."\n";

                $qcloud  = new QcloudApi(); 
                $body    = $file_path;
                $keys    = ltrim($body, '.');
                $results = $qcloud->uploadfile($keys, $body);
                echo $file_path . ' 上传成功<br>';

            }    
            closedir($dir);
            echo '全部上传完毕';
        }
    }

    /**
     * @desc AJAX上传APK
     */
    public function uploadApk()
    {
        $error           = '';
        $msg             = '';
        $file_url        = '';
        $apk_info        = array();
        $id              = I('id', '');
        $fileElementName = 'apk';
        if (!empty($_FILES[$fileElementName]['error'])) {
            switch ($_FILES[$fileElementName]['error']) {
                case '1':
                    $status = -1;
                    $error  = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                    break;
                case '2':
                    $status = -1;
                    $error  = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                    break;
                case '3':
                    $status = -1;
                    $error  = 'The uploaded file was only partially uploaded';
                    break;
                case '4':
                    $status = -1;
                    $error  = 'No file was uploaded.';
                    break;
                case '6':
                    $status = -1;
                    $error  = 'Missing a temporary folder';
                    break;
                case '7':
                    $status = -1;
                    $error  = 'Failed to write file to disk';
                    break;
                case '8':
                    $status = -1;
                    $error  = 'File upload stopped by extension';
                    break;
                case '999':
                default:
                    $status = -1;
                    $error  = 'No error code avaiable';
            }
        } else if (empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none') {
            $status = -1;
            $error  = 'No file was uploaded..';
        } else {

            //$saveDir = './Uploads/app/apk/' . date('Y') . '/' . date('m') . '/';
            $saveDir = './Uploads/app/apk/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';
            if (!file_exists($saveDir)) {
                mkdir($saveDir, 0755, true);
            }

            $result = $this->_uploadProc($saveDir);

            if ($result) {
                $file_name = $result['savename'];
                $savepath  = ltrim($result['savepath'], '.');
                $file_path = $savepath . $file_name;

                // 获取APK信息
                $apk_path = realpath($result['savepath'] . $result['savename']);
                $apk_info = getApkInfo($apk_path);

                $down_url = U('/Main/Apps/Download', array('package' => $apk_info['com'], 'version' => $apk_info['version']), true, true);
                if (isSsl()) {
                    $down_url = str_replace('http://', 'https://', $down_url);
                }

                $qcloud  = new QcloudApi(); //test
                $body    = $saveDir . $file_name;
                $keys    = ltrim($body, '.');
                $results = $qcloud->uploadfile($keys, $body);
                $msg     = '上传成功';
                $status  = 1;
            } else {
                $error  = '上传失败';
                $status = -1;
            }
        }

        $data = array('file' => $file_path, 'down_url' => $down_url, 'apk_info' => $apk_info);
        //检测这个包名是否存在
        if ($apk_info) {
            $packName  = $apk_info['com'];
            $appsModel = D('Apps');
            $package   = $appsModel->getDataByPackage($packName);
            if ($package) {
                $data['is_exsit']               = 1;
                $data['package']['name']        = $package['name'];
                $data['package']['image']       = $package['image'];
                $data['package']['developer']   = $package['developer'];
                $data['package']['app_cate_id'] = $package['app_cate_id'];
                $data['package']['description'] = $package['description'];
                $data['package']['status']      = $package['status'];
            }
        }
        $info   = $status == 1 ? $msg : $error;
        $return = array('data' => $data, 'info' => $info, 'status' => $status);
        echo json_encode($return);
    }

    private function uploadProc($savePath = './Uploads/')
    {
        vendor('UploadFile', COMMON_PATH . 'Library/Vendor', '.class.php');
        $upload = new \UploadFile();

        $upload->maxSize       = '-1'; //默认为-1,不限制上传大小
        $upload->savePath      = $savePath; //保存路径
        $upload->saveRule      = uniqid; //上传文件的文件名保存规则
        $upload->uploadReplace = true; //如果存在同名文件是否进行覆盖
        $upload->allowExts     = array('jpg', 'jpeg', 'png', 'gif'); //准许上传的文件类型
        if ($upload->upload()) {
            $info = $upload->getUploadFileInfo();
            return $info[0];
        } else {
            $_return = array('data' => '', 'info' => $upload->getErrorMsg(), 'status' => -1);
            echo json_encode($_return);
            exit;
        }
    }

    private function _uploadProc($savePath = './Uploads/')
    {
        vendor('UploadFile', COMMON_PATH . 'Library/Vendor', '.class.php');
        $upload = new \UploadFile();

        $upload->maxSize       = '-1'; //默认为-1,不限制上传大小
        $upload->savePath      = $savePath; //保存路径
        $upload->saveRule      = uniqid; //上传文件的文件名保存规则
        $upload->uploadReplace = true; //如果存在同名文件是否进行覆盖
        $upload->allowExts     = array('apk'); //准许上传的文件类型
        if ($upload->upload()) {
            $info = $upload->getUploadFileInfo();
            return $info[0];
        } else {
            $_return = array('data' => '', 'info' => $upload->getErrorMsg(), 'status' => -1);
            echo json_encode($_return);
            exit;
        }
    }

    public function release()
    {
        $app_id     = I('app_id', '0', 'intval');
        $version_id = I('version_id', '0', 'intval');
        $is_version = I('is_version', '1', 'intval');

        if (!$this->is_have_this_app($app_id)) {
            $this->error('您没有权限发布该应用!');
        }

        $is_channel = $this->role_info['role_id'] == RoleInfo::Channel;
        $is_vendor  = $this->role_info['role_id'] == RoleInfo::Vendor;
    //dump($is_channel);
    //dump($is_vendor);
    //die;
        //获取设备型号
        $devModelModel = D('DeviceModel');
        $deviceModel   = $devModelModel->getAll();
        $this->assign('deviceModel', $deviceModel);
        //获取所有省份
        $areaModel = D('Area');
        $province  = $areaModel->getList(array('pid' => 0));
        $this->assign('province', $province);

        // 判断应用是不是厂商和渠道商 BY jepeng
        // 获取所有厂家
        $vendorModel  = D('Vendor');
        $channelModel = D('Main/Channel');
        // 根据mem_id和角色区分发布的对象 By jepeng
        if ($is_vendor) {
            $vendor[0]['mem_id']         = $this->mem_id;
            $vendor[0]                   = $vendorModel->getAppVendor($this->mem_id);
            $vendor[0]['mem_info']['id'] = $this->mem_id;
            $channel                     = $channelModel->getAll(array('vendor_id' => $this->mem_id));
            $this->assign('field', 'vendor');
            $this->assign('channel', $channel);
        } elseif ($is_channel) {
            $vendor  = $channelModel->getAppChannelVendor($this->mem_id);
        //dump($vendor);die;
            $channel = $channelModel->getData($this->mem_id);
            $this->assign('field', 'channel');
            $this->assign('channel', $channel);
        } else {
            $appsModel = D('Main/Apps');
            $app_info  = $appsModel->getData($app_id);
            if ($app_info['mem_id']) {
                $memberModel = D('Member/Member');
                $role_id     = $memberModel->getRoleId($app_info['mem_id']);
                if ($role_id == RoleInfo::Vendor) {
                    $vendor[0]['mem_id']         = $app_info['mem_id'];
                    $vendor[0]                   = $vendorModel->getAppVendor($app_info['mem_id']);
                    $vendor[0]['mem_info']['id'] = $app_info['mem_id'];
                    $channel                     = $channelModel->getAll(array('vendor_id' => $app_info['mem_id']));
                    $this->assign('field', 'vendor');
                    $this->assign('channel', $channel);
                } elseif ($role_id == RoleInfo::Channel) {
                    $vendor  = $channelModel->getAppChannelVendor($app_info['mem_id']);
                    $channel = $channelModel->getData($app_info['mem_id']);
                    $this->assign('field', 'channel');
                    $this->assign('channel', $channel);
                }
            } else {
                $vendor = $vendorModel->getAll();
            }
        }
        $this->assign('vendor', $vendor);
    //dump($vendor);die;
        //获取该APP版本数据
        $appVersionModel = D('AppVersion');
        $appVersions     = $appVersionModel->getVersions($app_id);

        $this->assign('app_id', $app_id);
        if ($this->role_info['role_id'] == RoleInfo::Merchant) {
            $this->assign('is_channel', true);
        }
        $this->assign('version_id', $version_id);
        $this->assign('appVersions', $appVersions);
        //表明这是app专题页面读取的发布页面
        $this->assign('is_version', $is_version);
        $this->display('Apps/pieces/release_page');
    }

    /**
     * @desc 应用发布操作
     */
    public function releaseProc()
    {

        $AppVersionModel = D('Main/AppVersion');

        $mode       = I('post.mode', 0, 'intval');
        $version_id = I('post.version_id', 0, 'intval');
        $app_id     = I('post.app_id', 0, 'intval');
        $model_id   = I('post.model_id', 0, 'intval');
        $vendor_id  = I('post.vendor_id', 0, 'intval');
        $channel_id = I('post.channel_id', 0, 'intval');
        $province   = I('post.province', '', 'trim');
        $city       = I('post.city', '', 'trim');
    $lot_no     = I('post.lot_no', '', 'trim');
        $sn         = I('post.sn', '', 'trim');

        $release = I('post.release', 0, 'intval');
        $push    = I('post.push', 0, 'intval');

        $is_version = I('post.is_version');

        // 限制厂商渠道商发布应用 By jepeng
        if ($this->role_info['role_id'] == RoleInfo::Vendor) {
            $vendor_id = $this->mem_id;
        } elseif ($this->role_info['role_id'] == RoleInfo::Channel) {
            $channel_id = $this->mem_id;
            if ($channel_id) {
                $ChannelModel = D('Main/Channel');
                $vendor_id    = $ChannelModel->getOneField($channel_id, 'vendor_id');
            }
        }

        if (!$app_id) {
            $this->error('请选择要发布的应用');
        }

        $isSingle = false;
        if (!is_array($app_id)) {
            $isSingle   = true;
            $tmp_app_id = $app_id;
            $app_id     = array();
            $app_id[]   = $tmp_app_id;
        }

        foreach ($app_id as $id) {
            $insert_version_id = $version_id;
            //获取最新版本
            if ($version_id == 0) {
                $new_version       = $AppVersionModel->getData($id);
                $insert_version_id = $new_version['id'];
                if (!$insert_version_id) {
                    $this->error('该应用没有版本,请确认该应用是否完整再发布!');
                }
            }

            // 获取允许下载的版本个数
            $where = array('app_id' => $id, 'status' => 1);
            $cnt   = $AppVersionModel->getCount($where);

            $data = array(
                'version_id'   => $insert_version_id,
                'app_id'       => $id,
                'dev_model_id' => $model_id,
                'vendor_id'    => $vendor_id,
                'channel_id'   => $channel_id,
                'province'     => $province,
                'city'         => $city,
        'lot_no'       => $lot_no,
                'sn'           => $sn,
                'is_all'       => $mode,
                'status'       => $release,
                'push'         => $push,
                'valid_cnt'    => $cnt,
                'status'       => 1,
                'update_time'  => time(), //更新应用发布
                'create_time'  => NOW_TIME,
            );

            $this->_doAddRelease($data);
        }

        $jump = '';
        if ($is_version == 1 && $isSingle) {
            $jump = U('/Main/Apps/versionList', array('id' => $app_id[0]));
        } else {
            $jump = U('/Main/Apps');
        }
        $this->success('应用发布成功', $jump);
    }

    private function _doAddRelease($data)
    {
        $return          = false;
        $AppReleaseModel = D('Main/AppRelease');
        if ($data) {
            $where           = array();
            $where['app_id'] = $data['app_id'];

            if ($mode == 1) {
                $data['vendor_id']  = 0;
                $data['channel_id'] = 0;
                $data['province']   = '';
                $data['city']       = '';
                $data['sn']         = '';
            } else {
                $where['dev_model_id'] = $data['dev_model_id'];
                $where['vendor_id']    = $data['vendor_id'];
                $where['channel_id']   = $data['channel_id'];
                $where['province']     = $data['province'];
                $where['city']         = $data['city'];
                $where['sn']           = $data['sn'];
            }

            // 获取应用发布记录(如已存在对应的发布记录,则更新,否则新建)
            $release_info = $AppReleaseModel->getInfo($where);
            if ($release_info) {
                $res = $AppReleaseModel->update2($where, $data);
            } else {
                $res = $AppReleaseModel->tianJia($data);
            }
            //更新应用版本状态
            if ($data['status'] == 1) {
                $appVersionModel         = D('AppVersion');
                $versionUpdate['status'] = $data['status'];
                $res                     = $appVersionModel->update($data['version_id'], $versionUpdate);
            }

            if ($res === false) {
                // 记录日志
                $logData = array('module' => '应用市场', 'action' => '应用发布', 'remark' => '应用发布失败,应用编号:' . $data['app_id'], 'status' => 0);
                recordActionLog($logData);

                $return = false;
            }

            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '应用发布', 'remark' => '应用发布成功,应用编号:' . $data['app_id'], 'status' => 1);
            recordActionLog($logData);

            $return = true;
        }
        return $return;
    }

    // 批量发布应用
    public function releaseBatch()
    {
        $ids        = I('app_ids');
        $is_channel = $this->role_info['role_id'] == RoleInfo::Channel;
        $is_vendor  = $this->role_info['role_id'] == RoleInfo::Vendor;

        if ($ids) {
            $appsModel   = D('Apps');
            $where['id'] = array('in', $ids);
            $apps        = $appsModel->where($where)->select();
            $this->assign('apps', $apps);

            //获取设备型号
            $devModelModel = D('DeviceModel');
            $deviceModel   = $devModelModel->getAll();
            $this->assign('deviceModel', $deviceModel);
            //获取所有省份
            $areaModel = D('Area');
            $province  = $areaModel->getList(array('pid' => 0));
            $this->assign('province', $province);

            //获取所有厂家
            $vendorModel  = D('Vendor');
            $channelModel = D('Main/Channel');
            // 根据mem_id和角色区分发布的对象 By jepeng
            if ($is_vendor) {
                $vendor[0]['mem_id']         = $this->mem_id;
                $vendor[0]                   = $vendorModel->getAppVendor($this->mem_id);
                $vendor[0]['mem_info']['id'] = $this->mem_id;
                $channel                     = $channelModel->getAll(array('vendor_id' => $this->mem_id));
                $this->assign('field', 'vendor');
                $this->assign('channel', $channel);
            } elseif ($is_channel) {
                $vendor  = $channelModel->getAppChannelVendor($this->mem_id);
                $channel = $channelModel->getData($this->mem_id);
                $this->assign('field', 'channel');
                $this->assign('channel', $channel);
            } else {
                $vendor = $vendorModel->getAll();
            }
            // $vendor = $vendorModel->getAll();
            $this->assign('vendor', $vendor);

            $this->display('Apps/pieces/release_batch');
        } else {
            $this->error('请选择要发布的应用');
        }
    }

    /**
     * @desc 应用发布记录
     */
    public function releaseHistory()
    {
        $id         = I('id', 0, 'intval');
        $field      = I('field', '');
        $kwd        = I('kwd', '');
        $page       = I('page', 1, 'intval');
        $vendor_id  = I('vendor_id', ''); //厂家
        $channel_id = I('channel_id', ''); //渠道
        if ($page < 1) {
            $page = 1;
        }

        $is_channel = $this->role_info['role_id'] == RoleInfo::Channel;
        $is_vendor  = $this->role_info['role_id'] == RoleInfo::Vendor;

        //获取厂家列表 //获取渠道商列表
        $VendorModel  = D('Vendor');
        $ChannelModel = D('Channel');

        $channels    = array();
        $searchArray = array();
        $where       = array();

        if ($is_vendor) {
            $limit      = 'vendor';
            $vendors[0] = $VendorModel->getData($this->mem_id);
            $channels   = $ChannelModel->getAll(array('vendor_id' => $this->mem_id));

            $searchArray['vendor_id'] = $this->mem_id;
        } elseif ($is_channel) {
            $limit       = 'channel';
            $vendors     = $ChannelModel->getAppChannelVendor($this->mem_id);
            $channels[0] = $ChannelModel->getData($this->mem_id);

            $searchArray['vendor_id']  = $vendors[0]['mem_id'];
            $searchArray['channel_id'] = $this->mem_id;
        } else {
            $vendors = $VendorModel->getAll();
            if ($vendor_id) {

                $channels = $ChannelModel->where(array('vendor_id' => $vendor_id))->select();
            }
        }

        if ($id) {
            $searchArray['app_id'] = $id;
        }

        if ($kwd) {
            switch ($field) {
                case 'app_name':

                    $searchArray['app_name'] = array('like', "*$kwd*");
                    break;
                case 'sn':

                    $searchArray['sn'] = array('wildcard', "*$kwd*");
                    break;
            }
        }
// dump($searchArray);
        if (!($searchArray['vendor_id'] || $searchArray['channel_id']) && !($is_channel || $is_vendor)) {
            //厂家
            if ($vendor_id) {

                $searchArray['vendor_id'] = $vendor_id;
            }
            //渠道
            if ($vendor_id && $channel_id) {

                $searchArray['channel_id'] = $channel_id;
            }
        }

        $_searchArray = my_serialize($searchArray); //搜索条件序列化,导出用

        $searchArray['_from'] = ($page - 1) * $this->listRows;
        $searchArray['_size'] = $this->listRows;
        $searchArray['_sort'] = array('id' => 'desc');
        if (true) {
            $elastic = new ElasticSearch();
            if ($id) {

                $searchArray['app_id'] = $id;
            }

            $response = $elastic->search($searchArray, ElasticSearch::APP_RELEASES);
            if ($response) {
                $releaseHistory = $elastic->get_source_from_result($response['hits']);
                $total          = $response['total'];
            }
        } else {
            $AppReleaseModel = D('AppRelease');
            $releaseHistory  = $AppReleaseModel->getList($where, $page, $this->listRows);
            $total           = $AppReleaseModel->getCount($where);
        }
// dump($releaseHistory);die;
        $p      = new Page($total, $this->listRows);
        $paging = $p->show();

        $this->assign('field', $field);
        $this->assign('kwd', $kwd);
        $this->assign('release_history', $releaseHistory);

        $this->assign('paging', $paging);
        $this->assign('total', $total);
        $this->assign('vendors', $vendors);
        $this->assign('vendor_id', $vendor_id);
        $this->assign('channels', $channels);
        $this->assign('channel_id', $channel_id);
        $this->assign('limit', $limit);
        $this->assign('_searchArray', $_searchArray);

        $this->assign('id', $id);
        if ($id) {
            $this->display('app_release_history');
        } else {
            $this->display('release_history');
        }
    }

    /**
     * 利用elasticsearch 导出 搜索
     * @return array
     */
    public function getReleaseHistoryAll($searchArray = array())
    {
        $elastic  = new ElasticSearch();
        $response = $elastic->search($searchArray, ElasticSearch::APP_RELEASES);
        if ($response) {
            $info = $elastic->get_source_from_result($response['hits']);
        }
        return $info;
    }

    /**
     * @desc 发布详情
     */
    public function releaseDetail()
    {
        $id = I('id', 0, 'intval');
        if (!$id) {
            $this->error('缺少应用发布记录编号');
        }

        // 获取发布记录信息
        $AppReleaseModel = D('AppRelease');
        $release_info    = $AppReleaseModel->getData($id);

        // 获取应用信息
        $AppsModel = D('Apps');
        $app_info  = $AppsModel->getData($release_info['app_id']);

        $this->assign('release_info', $release_info);
        $this->assign('app_info', $app_info);
        $this->display('release_detail');
    }

    /**
     * @desc 修改发布状态
     */
    public function changeReleaseStatus()
    {
        $from   = I('post.from', 'release');
        $status = I('post.status', 0, 'intval');
        if ($status == 1) {
            $action = '发布';
        } else {
            $action = '取消发布';
        }

        $id     = I('post.id', '');
        $app_id = I('post.app_id', '');

        $AppReleaseModel = D('AppRelease');
        if ($from == 'app_list') {
            if (!$app_id) {
                $this->error('请选择要' . $action . '的应用');
            }
            $where = array('app_id' => $app_id);
            $res2  = $AppReleaseModel->where($where)->field('id')->select();
            $res3  = array();
            for ($i = 0; $i < count($res2); $i++) {
                $res3[$i] = $res2[$i]['id'];
            }
            $redirect = U('/Main/Apps');
        }
        if ($from == 'release') {
            if (!$id) {
                $this->error('请选择要' . $action . '的记录');
            }
            $where    = array('id' => array('IN', $id));
            $res3     = explode(",", $id);
            $redirect = U('/Main/Apps/releaseHistory');
        }

        $data = array(
            'status'      => $status,
            'update_time' => time(), //更新应用发布
        );
        $res = $AppReleaseModel->where($where)->save($data);
        // $sphinx = new Sphinx();
        // $sphinx->setUpdated('app_releases',$res3);

        if ($res === false) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => $action . '应用', 'remark' => $action . '应用失败,应用编号:' . $app_id, 'status' => 0);
            recordActionLog($logData);

            $this->error($action . '失败:' . $AppReleaseModel->getError());
        } else {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => $action . '应用', 'remark' => '应用编号:' . $app_id, 'status' => 1);
            recordActionLog($logData);

            $this->success($action . '成功', $redirect);
        }
    }

    /**
     * @desc 删除发布记录
     */
    public function delReleaseHistory()
    {
        $id = I('post.id', '');
        if (!$id) {
            $this->error('请选择要删除的记录');
        }

        $AppReleaseModel = D('AppRelease');
        $where           = array('id' => array('IN', $id));
        $res             = $AppReleaseModel->where($where)->delete();

        if ($res === false) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '删除发布记录', 'remark' => '删除发布记录失败,记录编号:' . $id, 'status' => 0);
            recordActionLog($logData);

            $this->error('删除失败:' . $AppReleaseModel->getError());
        } else {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '删除发布记录', 'remark' => '记录编号:' . $id, 'status' => 1);
            recordActionLog($logData);

            $this->success('删除成功', U('/Main/Apps/releaseHistory'));
        }
    }

    /**
     * @desc 下载历史 (sphinx)
     */
    // public function downloadHistory() {
    //     $id       = I('id', 0, 'intval');
    //     $type  = I('type', 'all'); // 默认显示全部 'all','today','yesterday','week','month','custom'
    //     $start = I('start', '');   // 查询起始时间
    //     $stop  = I('stop', '');    // 查询截止时间
    //     $field = I('field', '');
    //     $kwd   = I('kwd', '');
    //     $page  = I('page', 1, 'intval');
    //     if ($page < 1) $page = 1;

    //     $sphinx = (new Sphinx())->getInstance();
    //     $sphinx->setMatchMode(SPH_MATCH_EXTENDED2);
    //     $sphinx->setSortMode(SPH_SORT_EXTENDED, '@id DESC');
    //     $sphinx->setLimits($page - 1, $this->listRows, $this->sphinxMaxMatchCount);

    //     $is_search = false;
    //     $condition = '';
    //     $where = array();
    //     if ($kwd) {
    //         $is_search = true;
    //         switch ($field) {
    //             case 'app_name':
    //                 $condition = '@dev_app_name '.$kwd;
    //                 break;
    //             case 'vendor_name':
    //                 $condition = '@dev_vendor_name '.$kwd;
    //                 break;
    //             case 'channel_name':
    //                 $condition = '@dev_channel_name '.$kwd;
    //                 break;
    //             case 'sn':
    //                 $condition = '@dev_sn '.$kwd;
    //                 break;
    //             case 'merchant_name':
    //                 $condition = '@dev_merchant_name '.$kwd;
    //                 break;
    //             case 'model_name':
    //                 $condition = '@dev_model_name '.$kwd;
    //                 break;
    //             case 'device_name':
    //                 $condition = '@dev_device_name '.$kwd;
    //                 break;
    //         }
    //     }
    //     if ($type == 'custom' && !$start && !$stop) {
    //         $type = 'all';
    //     }
    //     switch ($type) {
    //         case 'all':
    //             $_start = '';
    //             $_stop  = '';
    //             break;
    //         case 'today':
    //             $_start = strtotime(date('Y-m-d 00:00:00'));
    //             $_stop  = strtotime(date('Y-m-d 23:59:59'));
    //             break;
    //         case 'yesterday':
    //             $_start = strtotime(date('Y-m-d 00:00:00', strtotime('-1 day')));
    //             $_stop  = strtotime(date('Y-m-d 23:59:59', strtotime('-1 day')));
    //             break;
    //         case 'week': //最近一周
    //             $_start = strtotime(date('Y-m-d 00:00:00', strtotime('-1 week + 1day')));
    //             $_stop  = time();
    //             break;
    //         case 'month': //最近一个月
    //             $_start = strtotime(date('Y-m-d 00:00:00', strtotime('-1 month + 1day')));
    //             $_stop  = time();
    //             break;
    //         case 'custom': //时间范围
    //             $_start = strtotime(date('Y-m-d 00:00:00', strtotime($start)));
    //             $_stop  = strtotime(date('Y-m-d 23:59:59', strtotime($stop)));
    //             if ($_start > $_stop) {
    //                 $_stop = $_start;
    //                 $stop  = date('Y-m-d', $_stop);
    //             }
    //             break;
    //     }
    //     if ($type != 'all') {
    //         $is_search = true;
    //         $sphinx->setFilterRange('down_time', $_start, $_stop);
    //     }
    //     $start = date('Y-m-d', $_start);
    //     $stop  = date('Y-m-d', $_stop);
    //     $is_search =1;
    //     if ($is_search) {
    //         //echo "1";
    //         // 通过SPHINX获取列表
    //         $result = $sphinx->query($condition, 'app_downloads');
    //         $error   = $sphinx->getLastError();
    //         $warning = $sphinx->getLastWarning();
    //         if ($error || $warning) {
    //             //$this->error($error ? $error : $warning);
    //         }
    //         $downHistory = $result['matches'];
    //         // if (is_null($downHistory)) {
    //         //     $is_search = true;
    //         // }

    //         $total = isset($result['total']) ? $result['total'] : 0;
    //     } else {
    //         //echo "2";
    //         $AppDownloadModel = D('Main/AppDownload');
    //         $downHistory = $AppDownloadModel->getList($where, $page, $this->listRows);
    //         // echo $AppDownloadModel->getlastSql();
    //         // echo "<br>";
    //         // dump($downHistory);
    //         // die();

    //         $total = $AppDownloadModel->getCount($where);
    //     }

    //      //dump($downHistory);die();

    //     $p = new Page($total, $this->listRows);
    //     $paging = $p->show();

    //     $this->assign('start', $start);
    //     $this->assign('stop', $stop);
    //     $this->assign('field', $field);
    //     $this->assign('kwd', $kwd);
    //     $this->assign('down_history', $downHistory);
    //     $this->assign('paging', $paging);
    //     $this->assign('total', $total);

    //     $this->assign('id', $id);
    //     if($id){
    //         $this->display('app_download_history');
    //     } else {
    //         $this->display('download_history');
    //     }
    // }

    /**
     * @desc 下载历史 (mysql和sphinx)
     */
    public function downloadHistory()
    {
        $id         = I('id', 0, 'intval');
        $start      = I('start', ''); // 查询起始时间
        $stop       = I('stop', ''); // 查询截止时间
        $field      = I('field', '');
        $kwd        = I('kwd', '');
        $vendor_id  = I('vendor_id', ''); //厂家
        $channel_id = I('channel_id', ''); //渠道
        $model_id   = I('model_id', ''); //设备型号
        $page       = I('page', 1, 'intval');
        if ($page < 1) {
            $page = 1;
        }

        $is_vendor  = $this->role_info['role_id'] == RoleInfo::Vendor;
        $is_channel = $this->role_info['role_id'] == RoleInfo::Channel;

        $ChannelModel = D('Channel');
        // 限制权限 By Jepeng
        if ($is_vendor) {
            $vendor_id = $this->mem_id;
            $limit     = "vendor";
        } elseif ($is_channel) {
            $channel_id = $this->mem_id;
            $vendor_id  = $ChannelModel->getOneField($channel_id, 'vendor_id');
            $limit      = "channel";
        }

        //判断是否搜索

        $is_search = true;
        //条件

        $searchArray = array();
        //mysql的搜索条件
        $where = array();

        //获取厂家列表
        $VendorModel = D('Vendor');

        if ($is_vendor) {
            $vendors[0] = $VendorModel->getData($vendor_id);
        } else {
            $vendors = $VendorModel->getAll();
        }

        //获取渠道商列表

        $channels = array();
        if ($vendor_id) {

            if ($is_channel) {
                $channels[0] = $ChannelModel->getData($channel_id);
            } else {
                $channels = $ChannelModel->where(array('vendor_id' => $vendor_id))->select();
            }

        }
        // 获取所有设备型号
        $DeviceModelModel = D('DeviceModel');
        $deviceModels     = $DeviceModelModel->getAll();

        $elastic = new ElasticSearch();
        //获取下拉框的厂商
        if ($vendor_id) {

            $searchArray['vendor_id'] = $vendor_id;
        }
        //获取下拉框的渠道商
        if ($channel_id) {

            $searchArray['channel_id'] = $channel_id;
        }
        //获取型号id
        if ($model_id) {

            $searchArray['model_id'] = $model_id;
        }
        //sn号和设备名的模糊搜索
        if ($kwd) {
            if ($field == 'app_name') {
                $searchArray['app_name'] = array('like', "*$kwd*");
            }
            if ($field == 'sn') {
                $searchArray['sn'] = array('wildcard', "*$kwd*");
            }
        }
        //获取下载的时间范围
        if ($start) {

            $_start = strtotime(date('Y-m-d 00:00:00', strtotime($start)));
            $_stop  = time();

            $searchArray['down_time'] = array('between', $_start, $_stop);
        }
        if ($stop) {

            $_start = '';
            $_stop  = strtotime(date('Y-m-d 23:59:59', strtotime($stop)));

            $searchArray['down_time'] = array('lte', $_stop);
        }
        if ($start && $stop) {

            $_start = strtotime(date('Y-m-d 00:00:00', strtotime($start)));
            $_stop  = strtotime(date('Y-m-d 23:59:59', strtotime($stop)));

            $searchArray['down_time'] = array('between', $_start, $_stop);
        }

        /*****************原生搜索条件开始**********************/
        //    if($id){
        //        $where['app_id'] = $id;
        //    }
        // //下拉框查询
        //    if ($vendor_id) {
        //        $where['vendor_id'] = array('EQ',$vendor_id);
        //    }
        //    if ($channel_id) {
        //        $where['channel_id'] = array('EQ',$channel_id);
        //    }
        //    if ($model_id) {
        //        $where['model_id'] = array('EQ',$model_id);
        //    }
        // //模糊查询
        //    if ($kwd) {
        //        switch ($field) {
        //            case 'app_name':
        //            $where['app_name'] = array('LIKE','%'.$kwd.'%');
        //            break;
        //            case 'sn':
        //            $where['sn'] = array('LIKE','%'.$kwd.'%');
        //            break;
        //         // case 'device_name':
        //         //     $where['device.name'] = array('LIKE','%'.$kwd.'%');
        //         //     break;
        //        }
        //    }
        // //日期搜索
        //    if ($start) {
        //        $_start = strtotime(date('Y-m-d 00:00:00', strtotime($start)));
        //        $where['down_time'] = array('GT',$_start);
        //    }
        //    if ($stop) {
        //        $_stop  = strtotime(date('Y-m-d 23:59:59', strtotime($stop)));
        //        $where['down_time'] = array('LT',$_stop);
        //    }
        //    if ($start && $stop) {
        //        $_start = strtotime(date('Y-m-d 00:00:00', strtotime($start)));
        //        $_stop  = strtotime(date('Y-m-d 23:59:59', strtotime($stop)));
        //        $where['down_time'] = array('BETWEEN',array($_start,$_stop));
        //    }
        /*****************原生搜索条件结束**********************/

        //app下载模型
        // $AppDownloadModel = D('Main/AppDownload');
        // $downHistory = $AppDownloadModel->getJoinList($where, $page, $this->listRows);
        // $total = $AppDownloadModel->getJoinCount($where);

        $_searchArray = my_serialize($searchArray); //搜索条件序列化,导出用

        $searchArray['_from'] = ($page - 1) * $this->listRows;
        $searchArray['_size'] = $this->listRows;
        $searchArray['_sort'] = array('id' => 'desc');
        if ($is_search) {
            $response = $elastic->search($searchArray, ElasticSearch::APP_DOWNLOADS);
            if ($response) {
                $downHistory = $elastic->get_source_from_result($response['hits']);
                $total       = $response['total'];
            }
        }
        //app下载视图模型
        else {
            $AppDownloadModel = D('Main/AppDownload');
            $downHistory      = $AppDownloadModel->getJoinList($where, $page, $this->listRows);
            $total            = $AppDownloadModel->getJoinCount($where);
        }

        $p      = new Page($total, $this->listRows);
        $paging = $p->show();
        //app下载状态
        $appStatus = AppDownloadStatus::$cn;
        $this->assign('appStatus', $appStatus);
        $this->assign('vendors', $vendors);
        $this->assign('vendor_id', $vendor_id);
        $this->assign('channels', $channels);
        $this->assign('channel_id', $channel_id);
        $this->assign('limit', $limit);
        $this->assign('deviceModels', $deviceModels);
        $this->assign('model_id', $model_id);
        $this->assign('start', $start);
        $this->assign('stop', $stop);
        $this->assign('field', $field);
        $this->assign('kwd', $kwd);
        $this->assign('down_history', $downHistory);
        $this->assign('paging', $paging);
        $this->assign('total', $total);
        $this->assign('_searchArray', $_searchArray);

        $this->assign('id', $id);
        if ($id) {
            $this->display('app_download_history');
        } else {
            $this->display('download_history');
        }
    }

    /**
     * 利用elasticsearch 导出 搜索
     * @return array
     */
    public function getDownloadHistoryAll($searchArray = array())
    {
        $elastic  = new ElasticSearch();
        $response = $elastic->search($searchArray, ElasticSearch::APP_DOWNLOADS);
        if ($response) {
            $info = $elastic->get_source_from_result($response['hits']);
        }
        return $info;
    }

    /**
     * @desc 下载历史状态弹框
     */
    public function historyDetail()
    {
        $infoId = I('id');

        $AppHistoryModel = D('AppHistory');
        $history         = $AppHistoryModel->where(array('info_id' => $infoId))->order('id desc')->select();
        foreach ($history as $key => $hi) {
            $history[$key]['status']      = AppDownloadStatus::$cn[$hi['status']];
            $history[$key]['create_time'] = date('Y-m-d H:i:s', $hi['create_time']);
        }

        $this->assign('history', $history);

        $this->display('history_detail');
    }

    /**
     * @desc 应用分类
     */
    public function category()
    {
        $AppCategoryModel = D('AppCategory');
        $cates            = $AppCategoryModel->getTree('', false);
        //dump($cates);exit;

        $this->assign('cates', $cates);
        $this->display('category_path_list');
    }

    /**
     * @desc 添加应用分类
     */
    public function addCate()
    {
        $Id = I('id', '0', 'intval');
        $this->assign('cata_id', $Id);

        //获取分类列表树数组
        $AppCategoryModel = D('AppCategory');
        $cates            = $AppCategoryModel->getTree('', false);
        $this->assign('cates', $cates);

        $this->display('Apps/pieces/add_category_page');
    }

    /**
     * @desc 编辑应用分类
     */
    public function editCate()
    {
        $id = I('id', '0', 'intval');
        $this->assign('id', $id);

        $pid = I('pid', '0', 'intval');
        $this->assign('pid', $pid);

        $sort_order = I('sort', '0', 'intval');
        $this->assign('sort_order', $sort_order);

        $name = I('name', '0', 'trim');
        $this->assign('name', $name);
        //获取分类列表树数组
        $AppCategoryModel = D('AppCategory');
        $where            = array();
        $where['id']      = array('NEQ', $id);
        $cates            = $AppCategoryModel->getTree($where, false);
        $this->assign('cates', $cates);

        $this->display('Apps/pieces/edit_category_page');
    }

    /**
     * @desc 添加/编辑分类操作
     */
    public function addCateProc()
    {
        $id         = I('post.id', 0, 'intval');
        $pid        = I('post.p_id', 0, 'intval');
        $name       = I('post.name', '', 'trim');
        $sort_order = I('post.sort_order', 0, 'intval');

        if (!$name) {
            $this->error('请输入分类名称');
        }

        $AppCategoryModel = D('AppCategory');

        $data = array(
            'pid'        => $pid,
            'name'       => $name,
            'sort_order' => $sort_order,
        );
        if ($id) {
            $data['id'] = $id;
            $act        = '修改';

            if ($data['pid'] == '0') {
                $data['path'] = '0';
            } else {
                //新父类
                $p_path = $AppCategoryModel->field('path')->where(array('id' => $data['pid']))->find();
                //新路径
                $data['path'] = $p_path['path'] . '-' . $data['pid'];
            }

            //获取子孙path
            $path    = $AppCategoryModel->field('path')->where(array('id' => $id))->find();
            $ch_path = $path['path'] . '-' . $id;

            //找到所有的子孙数组
            $where_c['path'] = array('LIKE', $ch_path . '%');
            $res_c           = $AppCategoryModel->where($where_c)->select();

            //将子孙的路径改成新路径
            if ($res_c) {
                for ($i = 0; $i < count($res_c); $i++) {
                    $replace_length = strlen($path['path']);
                    $new_child_path = substr_replace($res_c[$i]['path'], $data['path'], 0, $replace_length);
                    $update['path'] = $new_child_path;
                    $AppCategoryModel->where('id=' . $res_c[$i]['id'])->save($update);
                }
            }

            if ($AppCategoryModel->create($data)) {
                $res = $AppCategoryModel->save();
            }
        } else {
            $act = '添加';
            if ($AppCategoryModel->create($data)) {
                $res = $AppCategoryModel->add();
                $id  = $res;
            }
        }

        if ($res === false) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => $act . '应用分类', 'remark' => $act . '应用分类失败', 'status' => 0);
            recordActionLog($logData);

            $this->error('分类' . $act . '失败');
        }

        // 记录日志
        $logData = array('module' => '应用市场', 'action' => $act . '应用分类', 'remark' => '分类编号:' . $id, 'status' => 1);
        recordActionLog($logData);

        $this->success('分类' . $act . '成功');
    }

    /**
     * @desc AJAX上传分类图片
     */
    public function uploadCateImage()
    {
        $error    = '';
        $msg      = '';
        $file_url = '';
        $id       = I('id', '');
        if (!$id) {
            $msg    = '缺少分类ID';
            $status = -1;
            $return = array('data' => '', 'info' => $msg, 'status' => $status);
            echo json_encode($return);
            die;
        }
        $fileElementName = 'image';
        if (!empty($_FILES[$fileElementName]['error'])) {
            switch ($_FILES[$fileElementName]['error']) {
                case '1':
                    $status = -1;
                    $error  = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                    break;
                case '2':
                    $status = -1;
                    $error  = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                    break;
                case '3':
                    $status = -1;
                    $error  = 'The uploaded file was only partially uploaded';
                    break;
                case '4':
                    $status = -1;
                    $error  = 'No file was uploaded.';
                    break;
                case '6':
                    $status = -1;
                    $error  = 'Missing a temporary folder';
                    break;
                case '7':
                    $status = -1;
                    $error  = 'Failed to write file to disk';
                    break;
                case '8':
                    $status = -1;
                    $error  = 'File upload stopped by extension';
                    break;
                case '999':
                default:
                    $status = -1;
                    $error  = 'No error code avaiable';
            }
        } else if (empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none') {
            $status = -1;
            $error  = 'No file was uploaded..';
        } else {

            $result = uploadOne('image', 'Cate');
            if ($result['ok']) {
                $file_name = $result['images'][0]; //原图
                $file_path = C('IMG_URL');
                $file_url  = $file_path . $file_name;

                $schema   = isSsl() ? 'https' : 'http';
                $full_url = $schema . '://' . $_SERVER['HTTP_HOST'] . $file_url;

                $AppCategoryModel = D('AppCategory');
                //删掉旧的分类图片 不知为毛删不掉
                // $old_image = $AppCategoryModel->where(array('id'=>$id))->field('image')->find();
                // //dump($old_image);exit;
                // @unlink($old_image);

                //更新数据库地址目录
                $AppCategoryModel->where(array('id' => $id))->save(array('image' => $full_url));

                $msg    = '上传成功';
                $status = 1;
            } else {
                $error  = '上传失败';
                $status = -1;
            }
        }
        $data   = array('image' => $full_url);
        $info   = $status == 1 ? $msg : $error;
        $return = array('data' => $data, 'info' => $info, 'status' => $status);
        echo json_encode($return);
    }

    /**
     * @desc 删除分类
     */
    public function delCateProc()
    {
        $id  = I('post.id', 0, 'intval');
        $pid = I('post.pid', 0, 'intval');

        if (!$id) {
            $this->error('缺少分类编号');
        }

        $AppCategoryModel = D('AppCategory');

        //获取子孙path
        $path    = $AppCategoryModel->field('path')->where(array('id' => $id))->find();
        $ch_path = $path['path'] . '-' . $id;
        //dump($ch_path);exit;

        $where_c['path'] = array('LIKE', $ch_path . '%');
        $where['id']     = array('EQ', $id);

        $res_c = $AppCategoryModel->where($where_c)->delete();
        $res   = $AppCategoryModel->where($where)->delete();

        if ($res === false) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '删除应用分类', 'remark' => '删除应用分类失败,分类编号:' . $id, 'status' => 0);
            recordActionLog($logData);

            $this->error('分类删除失败');
        }

        // 记录日志
        $logData = array('module' => '应用市场', 'action' => '删除应用分类', 'remark' => '分类编号:' . $id, 'status' => 1);
        recordActionLog($logData);

        $this->success('分类删除成功');
    }

    /**
     * 删除应用
     * @param string  $id  需要删除记录的ID值
     * @return int
     * @author 流川枫 <510268196@qq.com>
     */
    public function del()
    {
        $id        = I('id', 0);
        $delFile   = I('delFile', 0);
        $AppsModel = D('Apps');

        $this_mem_id = ($this->role_info['role_id'] == RoleInfo::Channel || $this->role_info['role_id'] == RoleInfo::Vendor) ? $this->mem_id : 1;
        $del_data    = $AppsModel->getData($id);
        if ($del_data['mem_id'] != $this_mem_id) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '删除应用', 'remark' => '删除应用失败,应用编号:' . $id . '。原因:没有该应用的拥有权!', 'status' => 0);
            recordActionLog($logData);

            $this->error('您没有权限删除该应用!');
        }

        $data = $AppsModel->cutOff($id, $delFile);
        if ($data) {
            if($delFile){
                //删除云上app包
                $delurl = $del_data['apk_path'];
                $qcloud = new QcloudApi();
                $key    = ltrim($delurl, '.');
                $ret = $qcloud->delete($key);
            }
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '删除应用', 'remark' => '应用编号:' . $id, 'status' => 1);
            recordActionLog($logData);

            $this->success('删除应用成功!');
        } else {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '删除应用', 'remark' => '删除应用失败,应用编号:' . $id, 'status' => 0);
            recordActionLog($logData);

            $this->error('删除应用失败:' . $AppsModel->getError());
        }
    }

    /**
     * @desc 批量删除应用,支持删除多条和一个
     * 2016-10-24 修改:添加删除版本号 BY jepeng
     */
    public function delData()
    {
        $AppsModel       = D('Apps');
        $AppVersionModel = D('AppVersion');
        $id              = I('id', '');
        $flag            = 0;

        $ids = explode(',', $id);

        $this_mem_id = ($this->role_info['role_id'] == RoleInfo::Channel || $this->role_info['role_id'] == RoleInfo::Vendor) ? $this->mem_id : 0;

        if ($this_mem_id != 0) {
            $len = sizeof($ids);
            for ($i = 0; $i < $len; $i++) {
                $have_app = $AppsModel->getData($ids[$i]);
                if ($have_app['mem_id'] != $this_mem_id) {
                    unset($ids[$i]);
                    $flag = 1;
                }
            }
        }

        if (sizeof($ids)) {
            $where   = array('id' => array('IN', $ids));
            $res     = $AppsModel->where($where)->delete();
            $ver_res = $AppVersionModel->delData(array('app_id' => array('IN', $id)));
        } else {
            $this->error("请选择您拥有权限的应用进行删除!");
        }

        if ($res === false) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '批量删除应用', 'remark' => '批量删除应用失败,应用编号:' . $id, 'status' => 0);
            recordActionLog($logData);

            $this->error('删除应用失败!');
        }
        if ($ver_res === false) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '批量删除应用版本', 'remark' => '批量删除应用版本失败,应用编号:' . $id, 'status' => 0);
            recordActionLog($logData);

            $this->error('删除应用的版本失败!');
        }

        // 记录日志
        $logData = array('module' => '应用市场', 'action' => '批量删除应用', 'remark' => '应用编号:' . $id, 'status' => 1);
        recordActionLog($logData);
        $logData = array('module' => '应用市场', 'action' => '批量删除应用版本号', 'remark' => '应用编号:' . $id, 'status' => 1);
        recordActionLog($logData);

        if ($flag) {
            $this->success('您所要删除的应用已经自动过滤没有删除权限的应用!');
        } else {
            $this->success('删除应用成功!');
        }

    }

    /**
     * 删除应用版本
     * @param string  $id  需要删除记录的ID值
     * @return int
     * @author 流川枫 <510268196@qq.com>
     */
    public function delVersion()
    {
        $id = I('id', 0);

        $AppVersionModel = D('AppVersion');

        // 获取应用编号
        $app_id = $AppVersionModel->where(array('id' => $id))->getField('app_id');

        // 删除
        $data = $AppVersionModel->cutOff($id);
        if ($data !== false) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '删除应用版本', 'remark' => '版本编号:' . $id, 'status' => 1);
            recordActionLog($logData);

            // 获取允许下载的版本个数
            $where = array('app_id' => $app_id, 'status' => 1);
            $cnt   = $AppVersionModel->getCount($where);

            // 更新允许下载的版本个数
            $AppReleaseModel = D('AppRelease');
            $where           = array('app_id' => $app_id);
            $data            = array(
                'valid_cnt'   => $cnt,
                'update_time' => time(), //更新应用发布
            );
            $res = $AppReleaseModel->where($where)->save($data);
            //    $res2 = $AppReleaseModel->where($where)->field('id')->select();
            //       $res3 = array();
            //       for ($i=0; $i < count($res2); $i++) {
            //           $res3[$i] = $res2[$i]['id'];
            //       }
            // $sphinx = new Sphinx();
            // $sphinx->setUpdated('app_releases',$res3);

            $this->success('应用版本删除成功!');
        } else {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '删除应用版本', 'remark' => '删除应用版本失败,版本编号:' . $id, 'status' => 0);
            recordActionLog($logData);

            $this->error('应用版本删除失败:' . $AppVersionModel->getError());
        }
    }

    /**
     * @desc批量删除应用版本
     *     支持删除多条和一个
     */
    public function delVersions()
    {
        $AppVersionModel = D('AppVersion');
        $id              = I('id', '');
        $where           = array('id' => array('IN', $id));

        // 获取应用编号
        $app_id = $AppVersionModel->where($where)->getField('app_id');

        $res = $AppVersionModel->where($where)->delete();
        if ($res === false) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '批量删除应用版本', 'remark' => '批量删除应用版本失败,版本编号:' . $id, 'status' => 0);
            recordActionLog($logData);

            $this->error('应用版本删除失败!');
        }

        // 获取允许下载的版本个数
        $where = array('app_id' => $app_id, 'status' => 1);
        $cnt   = $AppVersionModel->getCount($where);

        // 更新允许下载的版本个数
        $AppReleaseModel = D('AppRelease');
        $where           = array('app_id' => $app_id);
        $data            = array(
            'valid_cnt'   => $cnt,
            'update_time' => time(), //更新应用发布
        );
        $res = $AppReleaseModel->where($where)->save($data);
        // $res2 = $AppReleaseModel->where($where)->field('id')->select();
        //       $res3 = array();
        //       for ($i=0; $i < count($res2); $i++) {
        //           $res3[$i] = $res2[$i]['id'];
        //       }
        // $sphinx = new Sphinx();
        // $sphinx->setUpdated('app_releases',$res3);

        // 记录日志
        $logData = array('module' => '应用市场', 'action' => '批量删除应用版本', 'remark' => '版本编号:' . $id, 'status' => 1);
        recordActionLog($logData);

        $this->success('应用版本删除成功!');
    }

    /**
     * @desc 下载应用
     */
    public function download()
    {
        set_time_limit(0);

        $sn      = I('sn', '', 'trim');
        $package = I('package', '', 'trim');
        $version = I('version', '', 'trim');

        $AppsModel       = D('Apps');
        $AppVersionModel = D('AppVersion');
        $app_info        = null;
        $ver_info        = null;
        //是否有sn号获取渠道应用
        if ($sn) {
            $deviceInfoModel = D('DeviceInfo');
            $device_info     = $deviceInfoModel->getDataBySn($sn);
            $deviceModel     = D('Device');
            $device          = $deviceModel->getData($device_info['dev_id']);
            $channel_id      = $device['channel_id'];
           
        $vendor_id       = $device['vendor_id'];
           //
            //获取应用信息和版本信息
            $app_info = $AppsModel->where(array('package' => $package,'version' => $version,'mem_id' => array('in', array($channel_id, $vendor_id, 1))))->find();
            $ver_info = $AppVersionModel->where(array('app_id' => $app_info['id'],'version' => $version))->find();
       // dump($ver_info);
            if (!$ver_info) {
                die('版本信息不存在');
            }

            if ($ver_info && $ver_info['status'] == 0) {
                die('无可下载的应用');
            }

            // 添加下载记录
            $AppDownloadModel = D('AppDownload');
            $data             = array(
                'sn'            => $sn,
                'app_id'        => $app_info['id'],
                'app_name'      => $app_info['name'],
                'app_developer' => $app_info['developer'],
                'app_package'   => $app_info['package'],
                'app_category'  => $app_info['app_category_info']['name'],
                'type'          => 'down',
                'app_ver'       => $version,
                'down_time'     => time(),
                'complete_time' => time(),
                'status'        => 1,
            );
            $res = $AppDownloadModel->insert($data);

            /***************************插入下载历史表的实时状态start***********************/
            $AppHistoryModel = M('AppHistory');
            $historyData     = array(
                'info_id'     => $res,
                'status'      => '1', //开始下载
                'create_time' => time(),
            );
            $AppHistoryModel->add($historyData);
            /********************************插入下载历史表的实时状态end*************************/
        } else {
            $app_info = $AppsModel->getDataByPackage($package);
            $ver_info = $AppVersionModel->getInfo($package, $version);
        }

        // 更新下载数: +1
        $data = array('download_cnt' => intval($app_info['download_cnt']) + 1);
        $res  = $AppsModel->update($app_info['id'], $data);

        $data = array('download_cnt' => intval($ver_info['download_cnt']) + 1);
        $res  = $AppVersionModel->update($ver_info['id'], $data);

        // 下载
        // 文件路径
        $file_path = '.' . $ver_info['apk_path'];
        $pathinfo  = pathinfo($file_path);

        // 文件名
        $file_name = $pathinfo['basename'];
        //if (file_exists($file_path)) {
            $cdn_host = C('CDN_HOST');
            if ($cdn_host) {
                $url = rtrim($cdn_host, '/') . trim($ver_info['apk_path'], '.');
                header("Location:" . $url);
            } else {
                // $fp = fopen($file_path, 'r');

                // // 文件大小
                // $file_size = filesize($file_path);

                // //下载文件需要用到的头
                // header('Content-Type: application/force-download;');
                // header('Content-Transfer-Encoding: binary');
                // Header('Accept-Length:' . $file_size);
                // Header('Content-Length:' . $file_size);
                // header('Accept-Ranges:Bytes');
                // Header('Content-Disposition: attachment; filename="' . $file_name . '"');

                // $buffer     = 1024;
                // $file_count = 0;
                // //向浏览器返回数据
                // while (!feof($fp) && $file_count < $file_size) {
                //     $file_con = fread($fp, $buffer);
                //     $file_count += $buffer;
                //     echo $file_con;
                // }
                // fclose($fp);
                $downloadUrl = C('COS_HOST') . $ver_info['apk_path'];
                header("Location: $downloadUrl");
            }
        //}
    }

    /**
     * 应用广告列表
     * @return [type] [description]
     */
    public function ads()
    {
        $AppAdsModel = D('AppAds');
        $adss        = $AppAdsModel->order('sort_order')->select();

        $adsSizeModel = D('AdsSize');
        for ($i = 0; $i < count($adss); $i++) {
            $with               = $adsSizeModel->where(array('id' => $adss[$i]['size']))->field('with')->find();
            $height             = $adsSizeModel->where(array('id' => $adss[$i]['size']))->field('height')->find();
            $adss[$i]['with']   = $with['with'] ? $with['with'] : 0;
            $adss[$i]['height'] = $height['height'] ? $height['height'] : 0;
        }
//dump($adss);exit;
        $this->assign('adss', $adss);
        $this->display('ads_list');
    }

    /**
     * @desc 添加广告
     */
    public function addAds()
    {
        $adsSizeModel = D('AdsSize');
        $sizes        = $adsSizeModel->select();

        $this->assign('sizes', $sizes);
        $this->display('Apps/pieces/add_ads_page');
    }

    /**
     * @desc 编辑广告
     */
    public function editAds()
    {
        $id = I('id', '0', 'intval');
        $this->assign('id', $id);

        $size = I('size', '0', 'intval');
        $this->assign('size', $size);

        $status = I('status', '0', 'intval');
        $this->assign('status', $status);

        $sort = I('sort', '0', 'intval');
        $this->assign('sort', $sort);

        $name = I('name', '0', 'trim');
        $this->assign('name', $name);

        $remark = I('remark', '', 'trim');
        $this->assign('remark', $remark);

        //获取广告尺寸
        $adsSizeModel = D('AdsSize');
        $sizes        = $adsSizeModel->select();
        $this->assign('sizes', $sizes);

        $this->display('Apps/pieces/edit_ads_page');
    }

    /**
     * @desc 添加/编辑广告 操作
     */
    public function addAdsProc()
    {
        $id         = I('post.id', 0, 'intval');
        $name       = I('post.name', '', 'trim');
        $sort_order = I('post.sort_order', 0, 'intval');
        $status     = I('post.status', 1, 'intval');
        $size       = I('post.size', 0, 'intval'); //广告图尺寸
        $remark     = I('post.remark', '', 'trim'); //广告描述

        if (!$name) {
            $this->error('请输入广告名称');
        }
        if (mb_strlen($remark, 'utf-8') > 28) {
            $this->error('简单描述请不要超过28个字');
        }

        $AppAdsModel = D('AppAds');

        $data = array(
            'name'        => $name,
            'sort_order'  => $sort_order,
            'status'      => $status,
            'size'        => $size,
            'remark'      => $remark,
            'create_time' => time(),
        );

        if ($id) {
            $data['id'] = $id;
            $act        = '修改';

            if ($AppAdsModel->create($data)) {
                $res = $AppAdsModel->save();
            }
        } else {
            //添加需要验证是否有同名广告
            $has = $AppAdsModel->where(array('name' => $name))->find();
            if ($has) {
                $this->error('广告名称已经存在');
            }

            $act = '添加';
            if ($AppAdsModel->create($data)) {
                $res = $AppAdsModel->add();
                $id  = $res;
            }
        }

        if ($res === false) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => $act . '广告分类', 'remark' => $act . '应用广告失败', 'status' => 0);
            recordActionLog($logData);

            $this->error('广告' . $act . '失败');
        }

        // 记录日志
        $logData = array('module' => '应用市场', 'action' => $act . '应用广告', 'remark' => '广告编号:' . $id, 'status' => 1);
        recordActionLog($logData);

        $this->success('广告' . $act . '成功');
    }

    /**
     * @desc 删除广告
     */
    public function delAdsProc()
    {
        $id = I('post.id', 0, 'intval');

        if (!$id) {
            $this->error('缺少广告编号');
        }

        $AppAdsModel = D('AppAds');

        $res = $AppAdsModel->where(array('id' => $id))->delete();

        if ($res === false) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '删除应用广告', 'remark' => '删除应用广告失败,广告编号:' . $id, 'status' => 0);
            recordActionLog($logData);

            $this->error('广告删除失败');
        }

        // 记录日志
        $logData = array('module' => '应用市场', 'action' => '删除应用广告', 'remark' => '广告编号:' . $id, 'status' => 1);
        recordActionLog($logData);

        $this->success('广告删除成功');
    }

    /**
     * @desc AJAX上传广告图片
     */
    public function uploadAdsImage()
    {
        $error      = '';
        $msg        = '';
        $file_url   = '';
        $id         = I('id', '');
        $withSize   = I('withSize', '');
        $heightSize = I('heightSize', '');

        if (!$id) {
            $msg    = '缺少广告ID';
            $status = -1;
            $return = array('data' => '', 'info' => $msg, 'status' => $status);
            echo json_encode($return);
            die;
        }
        if ($withSize == 0 || $heightSize == 0) {
            $Original = 1; //原图
        }

        $fileElementName = 'image';
        if (!empty($_FILES[$fileElementName]['error'])) {
            switch ($_FILES[$fileElementName]['error']) {
                case '1':
                    $status = -1;
                    $error  = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                    break;
                case '2':
                    $status = -1;
                    $error  = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                    break;
                case '3':
                    $status = -1;
                    $error  = 'The uploaded file was only partially uploaded';
                    break;
                case '4':
                    $status = -1;
                    $error  = 'No file was uploaded.';
                    break;
                case '6':
                    $status = -1;
                    $error  = 'Missing a temporary folder';
                    break;
                case '7':
                    $status = -1;
                    $error  = 'Failed to write file to disk';
                    break;
                case '8':
                    $status = -1;
                    $error  = 'File upload stopped by extension';
                    break;
                case '999':
                default:
                    $status = -1;
                    $error  = 'No error code avaiable';
            }
        } else if (empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none') {
            $status = -1;
            $error  = 'No file was uploaded..';
        } else {

            if ($Original) {
                $result = uploadOne('image', 'Ads'); //原图
            } else {
                $result = uploadOne('image', 'Ads', 1, $withSize, $heightSize); //缩略图
            }
            //dump($result);exit;
            if ($result['ok']) {
                if ($Original) {
                    $file_name = $result['images'][0]; //原图
                } else {
                    $file_name = $result['images'][1]; //缩略图
                }
                $file_path = C('IMG_URL');
                $file_url  = $file_path . $file_name;

                $schema   = isSsl() ? 'https' : 'http';
                $full_url = $schema . '://' . $_SERVER['HTTP_HOST'] . $file_url;

                $AppAdsModel = D('AppAds');

                //更新数据库地址目录
                $AppAdsModel->where(array('id' => $id))->save(array('image' => $full_url));

                $msg    = '上传成功';
                $status = 1;
            } else {
                $error  = '上传失败';
                $status = -1;
            }
        }
        $data   = array('image' => $full_url);
        $info   = $status == 1 ? $msg : $error;
        $return = array('data' => $data, 'info' => $info, 'status' => $status);
        echo json_encode($return);
    }

    /**
     * 应用购买记录
     * @return [type] [description]
     */
    public function appBuyHistory()
    {
        $kwd   = I('kwd', '');
        $field = I('field', '');

        $where = array();
        if ($kwd) {
            if ($field == 'app_name') {
                $where['app_name'] = array('LIKE', '%' . $kwd . '%');
            } elseif ($field == 'member') {
                $where['member'] = array('LIKE', '%' . $kwd . '%');
            }
        }

        $appBuyHistoryViewModel = D('AppBuyHistoryView');
        $info                   = $appBuyHistoryViewModel->getList($where);
        $total                  = $appBuyHistoryViewModel->getCount($where);
        $p                      = new Page($total, $this->listRows);
        $paging                 = $p->show();

// dump($info);exit;
        $this->assign('kwd', $kwd);
        $this->assign('field', $field);
        $this->assign('info', $info);
        $this->assign('paging', $paging);
        $this->display('app_buy_history');
    }

    /**
     * @desc 删除应用购买记录
     */
    public function delAppBuyHistory()
    {
        $id = I('post.id', '');
        if (!$id) {
            $this->error('请选择要删除的记录');
        }

        $AppBuyHistoryModel = D('AppBuyHistory');
        $where              = array('id' => array('IN', $id));
        $res                = $AppBuyHistoryModel->where($where)->delete();

        if ($res === false) {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '删除应用购买记录', 'remark' => '删除应用购买记录失败,记录编号:' . $id, 'status' => 0);
            recordActionLog($logData);

            $this->error('删除失败:' . $AppReleaseModel->getError());
        } else {
            // 记录日志
            $logData = array('module' => '应用市场', 'action' => '删除应用购买记录', 'remark' => '记录编号:' . $id, 'status' => 1);
            recordActionLog($logData);

            $this->success('删除成功', U('/Main/Apps/appBuyHistory'));
        }
    }

    /**
     * 判断该应用是否属于该用户
     * @author 缪志鹏 <Jepeng 993218181@qq.com>
     * @param app_id,需要验证的应用id,$version为验证的版本号,默认为空
     */
    public function is_have_this_app($app_id, $version = null)
    {
        $is_channel = ($this->role_info['role_id'] == RoleInfo::Channel);
        $is_vendor  = ($this->role_info['role_id'] == RoleInfo::Vendor);

        if ($is_channel || $is_vendor) {
            $mem_id = $this->mem_id;
        } else {
            $mem_id = 0;
        }
        if ($is_channel) {
            $ChannelModel = D('Channel');
            $vendor_id    = $ChannelModel->getOneField($mem_id, 'vendor_id');
        }

        $ViewAppOwnerModel = D('ViewAppOwner');
        $apps_info         = $ViewAppOwnerModel->get_data_by_app_id($app_id);

        if ($apps_info['mem_id'] == $mem_id || $apps_info['mem_id'] == 0 || $apps_info['mem_id'] == $vendor_id) {
            return ture;
        } else {
            $AppsMembersModel = D('AppsMembers');
            $data['mem_id']   = array('in', array($mem_id, $vendor_id, 0));
            $data['app_id']   = $app_id;
            $result           = $AppsMembersModel->getDataResult($data);
            if ($result) {
                return $result;
            } else {
                return false;
            }
        }
    }

    /**
     * 应用权限控制
     */
    // public function appAccess()
    // {
    //     //获取应用信息
    //     $app_id    = I('id','');
    //     $appVersionModel = D('AppVersion');
    //     $app_access = $appVersionModel->getData($app_id);
    //     $access_channel = $app_access['access_channel'];
    //     $access = explode(',',$access_channel);
    //     $appModel  = D('Apps');
    //     $appInfo   = $appModel->getData($app_id);

    //     $page      = I('page', 1, 'intval');
    //     if ($page < 1) $page = 1;

    //     $province  = I('province', '');
    //     $city      = I('city', '');
    //     $kwd       = I('kwd', '');
    //     $field     = I('field','');
    //     $vendor_id = I('vendor_id','');//厂家

    //     // 搜索条件
    //     $where = array();

    //     if ($this->is_super || $this->role == 'system') {
    //         // 获取厂家
    //         $VendorModel = D('Vendor');
    //         $vendors = $VendorModel->getAll();
    //         if ($vendor_id) {
    //             $where['Channel.vendor_id'] = $vendor_id;
    //         }
    //     } else if ($this->role == 'vendor') {
    //         // 获取厂家ID
    //         $vendor_id = getVendorId($this->mem_id, $this->role);
    //         $where['Channel.vendor_id'] = $vendor_id;
    //     }

    //     if ($province) {
    //         $where['Channel.province'] = $province;
    //     }
    //     if ($city) {
    //         $where['Channel.city'] = $city;
    //     }

    //     //渠道名和会员帐号搜索
    //     if($kwd){
    //         switch ($field) {
    //             case 'name':
    //                 $where['Channel.name'] = array('LIKE', '%'.$kwd.'%');
    //                 break;
    //             case 'member':
    //                 $where['username'] = array('LIKE', '%'.$kwd.'%');
    //                 break;
    //             case 'remark':
    //                 $where['Channel.remark'] = array('LIKE', '%'.$kwd.'%');
    //                 break;
    //         }
    //     }
    //     $_where = my_serialize($where);//搜索条件序列化,导出用

    //     // 获取列表
    //     $ChannelModel = D('Channel');
    //     $channel = $ChannelModel->getList($where, $page, $this->listRows);

    //     //渠道列表添加应用权限元素
    //     foreach($channel as &$key){

    //         if(in_array($key['mem_id'], $access)) {
    //             $key['access'] = '无';
    //         }else{
    //             $key['access'] = '有';
    //         }

    //     }
    //     $total = $ChannelModel->getCount($where, $this->listRows);

    //     $p = new Page($total);
    //     $paging = $p->show();

    //     $this->assign('app_id',$app_id);
    //     $this->assign('province', $province);
    //     $this->assign('city', $city);
    //     $this->assign('kwd', $kwd);
    //     $this->assign('field', $field);
    //     $this->assign('paging', $paging);
    //     $this->assign('channel', $channel);
    //     $this->assign('vendors', $vendors);
    //     $this->assign('vendor_id', $vendor_id);
    //     $this->assign('_where', $_where);//搜索条件序列化,导出用
    //     $this->assign('access',$access);
    //     // $this->display('channel_list');
    //     $this->roleDisplay('app_access');
    // }

    // public function changeAccessProc()
    // {

    //     $app_id = I('get.app_id','');
    //     $channel_ids = I('post.id');//渠道商id
    //     $status = I('post.status', 0, 'intval');
    //     //取出表中被禁用的渠道id
    //     $appVersionModel = D('AppVersion');
    //     $data = $appVersionModel->getData($app_id);
    //     $ids = $data['access_channel'];

    //     if ($status == 1) {
    //         $action = '启用';
    //     } else {
    //         $action = '禁用';
    //     }
    //     if($status == 1) {
    //         //生成启用渠道后禁止渠道的数组
    //         $ids1 = explode(',',$ids);
    //         $ids2 = explode(',',$channel_ids);
    //         $arr = array_diff($ids1,$ids2);
    //         //把数组写入表中
    //         $access_channel = implode(',',$arr);
    //         $data = array('access_channel' => $access_channel);
    //         $where = array('app_id' => $app_id);
    //         $res = $appVersionModel->update2($where,$data);
    //         if($res){
    //             $this -> success($action.'渠道成功',U('Main/Apps'));
    //         }else{
    //             $this -> error('操作失败');
    //         }
    //     }else{
    //         //生成禁用渠道后禁止渠道的数组
    //         $ids1 = explode(',',$ids);
    //         $ids2 = explode(',',$channel_ids);
    //         $arr1 = array_intersect($ids1,$ids2);
    //         $arr2 = array_diff($ids1,$ids2);
    //         $arr3 = array_diff($ids2,$ids1);
    //         $arr = array_merge($arr1,$arr2,$arr3);
    //         //把数组写入表中
    //         $access_channel = implode(',',$arr);
    //         $data = array('access_channel' => $access_channel);
    //         $where = array('app_id' => $app_id);
    //         $res = $appVersionModel->update2($where,$data);
    //         if($res){
    //             $this -> success($action.'渠道成功',U('Main/Apps'));
    //         }else{
    //             $this -> error('操作失败');
    //         }
    //     }

    // }
}

说明:

php
ignore_user_abort(true); //关闭浏览器也可以执行,只有断开httpd连接方可终止了,重启apache或者断开网络
set_time_limit(0);    //可以让程序无限制的执行下去

nginx apache 可能返回504或者等待返回超时了,但只要httpd连接未段,发出的请求后台仍然不会中断执行,只有断开httpd连接方可终止了,重启apache或者断开网络。

 

PHP主动断开与浏览器的连接

参见文档:

https://www.php.cn/php-notebook-92280.html

<!--?php

 

   /**

    * 自动断开与浏览器的连接

    * jiaofuyou

    */

 

    echo '1234567890';  //向浏览器输出的内容

 

    {//断开连接的代码  

        $size=ob_get_length();  

        header("Content-Length: $size");  //告诉浏览器数据长度,浏览器接收到此长度数据后就不再接收数据

        header("Connection: Close");      //告诉浏览器关闭当前连接,即为短连接

        ob_flush();  

        flush();  

    }  

     

    error_log(date("[Y-m-d H:i:s]")." --> "."start" ."\n", 3 , "/usr/local/apache2219/logs/php_log");

     

    //断开连接后的执行长时间操作      

    sleep(5);  

     

    echo 'test213';//浏览器接收不到了  

     

    error_log(date("[Y-m-d H:i:s]")." > "."end"   ."\n", 3 , "/usr/local/apache2219/logs/php_log");

    //可以查看错误日志是否延迟5秒后执行. 

 

?>

 

PHP主动断开与浏览器的连接

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!