AppframeController.class.php 13.4 KB
<?php
namespace Common\Controller;
use Think\Controller;

class AppframeController extends Controller {

    function _initialize() {
        $this->assign("waitSecond", 3);
        $time=time();
        $this->assign("js_debug",APP_DEBUG?"?v=$time":"");
    }

    // 民族列表
    public function nation() {
        $nation = M('Nation')
            ->select();
        $this->assign('nation', $nation);
    }

    // 地区列表
    public function region() {
        $region = M('Region')
            ->select();
        $this->assign('region', $region);
        $region_mobile = array();
        foreach($region as $k=>$v) {
            $region_mobile[$k]['value'] = $v['id'];
            $region_mobile[$k]['label'] = $v['name'];
        }
        $this->assign('region_mobile', json_encode($region_mobile));
    }

    // 一级分类列表
    public function product() {
        $where['parent'] = 0;
        $product = M('Product')
            ->where($where)
            ->select();
        $this->assign('product', $product);
    }

    // 二级分类列表
    public function product_son($id) {
        $where['parent'] = $id;
        $product_son = M('Product')
            ->where($where)
            ->select();
        $this->assign('product_son', $product_son);
    }

    /**
     * 时间格式化
     */
    public function formateData($time){
        $now_time = date("Y-m-d H:i:s");
        $now_time = strtotime($now_time);
        $dur = $now_time - $time;
        if($dur < 60){
            return $dur.'秒前';
        }else{
            if($dur < 3600){
                return floor($dur/60).'分钟前';
            }else{
                if($dur < 86400){
                    return floor($dur/3600).'小时前';
                }else{
                    return floor($dur/86400).'天前';
                }
            }
        }
    }

    /*
     * TP上传操作
     * @author ShiO
     * @date 2015年9月21日 14:14:09
     * 20M = 20971520B
     * 5M  = 5242880B
     */
    protected function upload($savePath, $maxSize = 20971520, $exts = array('jpg', 'gif', 'png', 'jpeg', 'mp4'), $saveName = array()) {
        if (!$saveName) {
            $saveName = time() . mt_rand(1000, 9999);
        } elseif ($saveName === true) {
            $saveName = array('uniqid', '');
        }
        $upload = new \Think\Upload();
        // 实例化上传类
        $upload->maxSize = $maxSize;
        // 设置附件上传大小
        $upload->exts = $exts;
        // 设置附件上传类型
        $upload->savePath = $savePath . '/';
        // 设置附件上传(子)目录
        $upload->autoSub = true;
        // 开启子目录保存
        $upload->subName = array('date', 'Ymd');
        // 自动子目录命名规则
        $upload->saveName = $saveName;
        // 文件命名规则
        $upload->rootPath = './'.C("UPLOADPATH");
        // 文件上传根目录

        // 上传文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            return array(false, $upload->getError());
        } else {// 上传成功
            return array(true, $info);
        }
    }

    /*
     * TP上传操作(生成图片缩略图)
     * @author lz
     * @date 2017年12月23日
     */
    protected function image($imagePath) {
        $image = new \Think\Image();
        $path = explode(".", $imagePath);
        $filename = $path[0]."_thumb";
        $image->open('.'.C('UPLOADS_PATH').$imagePath);
        // 生成一个居中裁剪为150*150的缩略图并保存为_thumb.jpg
        if($image->thumb(C('THUMB_WIDTH'), C('THUMB_HEIGHT'),\Think\Image::IMAGE_THUMB_CENTER)->save('.'.C('UPLOADS_PATH').$filename.".".$path[1])){
            return $filename.".".$path[1];
        }
    }

    /*
     * TP上传操作(并验证是否有重复文件,如果有则不再上传)
     * @author lz
     * 增加防止重复的文件上传方式,后缀名判断
     */
    protected function uploadCommon($uploadType = 'file', $maxSize = 20971520, $uploadModule = '', $returnJson = true) {
        // 判断文件是否重复
        $this->attachmentModel = D('Common/Attachment');
        list($fileInfo, $attachmentId) = $this->_uploadCheckExists();

        if ($fileInfo) {
            if (!$returnJson) {
                return array(true, $fileInfo, C('UPLOADS_PATH') . $fileInfo, $attachmentId);
            }
            $this->ajaxReturn(array('code' => 0, 'msg' => '上传成功', 'data' => array('path' => $fileInfo, 'link' => C('UPLOADS_PATH') . $fileInfo, 'attachment_id' => $attachmentId)));
        }

        if ($uploadType == 'file') {
            $allFileType = array();
            $allFileType = array_merge($allFileType, C('UPLOAD_IMAGE_EXT'));
            $allFileType = array_merge($allFileType, C('UPLOAD_AUDIO_EXT'));
            $allFileType = array_merge($allFileType, C('UPLOAD_VIDEO_EXT'));
            $allFileType = array_merge($allFileType, C('UPLOAD_FILE_EXT'));
            list($status, $info) = $this->upload($uploadModule, $maxSize, $allFileType);
        } else {
            list($status, $info) = $this->upload($uploadModule, $maxSize, C('UPLOAD_' . strtoupper($uploadType) . '_EXT'));
        }

        if (!$status) {
            if (!$returnJson) {
                return array(false, $info, '', '');
            }
            $this->ajaxReturn(array('code' => 9, 'msg' => $info));
        }

        $info = current($info);

        //判断是否有图
        $savePath = $info['savepath'] . $info['savename'];
        $originName = $info['name'];
        $saveName = $info['savename'];
        $fileType = $info['type'];
        $ext = $info['ext'];
        $size = $info['size'];
        $md5 = $info['md5'];
        $sha1 = $info['sha1'];

        $attachmentData = array('origin_name' => $originName, 'save_name' => $saveName, 'save_path' => $savePath, 'upload_module' => $uploadModule, 'type' => $fileType, 'ext' => $ext, 'size' => $size, 'md5' => $md5, 'sha1' => $sha1);
        $attachmentId = $this->attachmentModel->addFileUpload($attachmentData);

        if (!$returnJson) {
            return array(true, $savePath, C('UPLOADS_PATH') . $savePath, $attachmentId);exit;
        }
        //返回文件地址和名给JS作回调用
        $this->ajaxReturn(array('code' => 0, 'msg' => '上传成功', 'data' => array('path' => $savePath, 'link' => C('UPLOADS_PATH') . $savePath, 'attachment_id' => $attachmentId), 'info'=>$info));

    }

    // 节省空间利器,检测文件是否已经上传,如果已经上传则不再新增了
    private function _uploadCheckExists() {
        $file = current($_FILES);
        $fileHash = md5_file($file['tmp_name']);
        if (!$fileHash) {
            return false;
        }
        list($fileInfo, $attachmentId) = $this->attachmentModel->getFileUploadInfoByHash($fileHash);
        return array($fileInfo, $attachmentId);
    }

    /**
     * Ajax方式返回数据到客户端
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type AJAX返回数据格式
     * @return void
     */
    protected function ajaxReturn($data, $type = '',$json_option=0) {

        $data['referer'] = $data['url'] ? $data['url'] : "";
        $data['state']   = !empty($data['status']) ? "success" : "fail";

        if(empty($type)) $type  =   C('DEFAULT_AJAX_RETURN');
        switch (strtoupper($type)){
            case 'JSON' :
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                exit(json_encode($data,$json_option));
            case 'XML'  :
                // 返回xml格式数据
                header('Content-Type:text/xml; charset=utf-8');
                exit(xml_encode($data));
            case 'JSONP':
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                $handler  =   isset($_GET[C('VAR_JSONP_HANDLER')]) ? $_GET[C('VAR_JSONP_HANDLER')] : C('DEFAULT_JSONP_HANDLER');
                exit($handler.'('.json_encode($data,$json_option).');');
            case 'EVAL' :
                // 返回可执行的js脚本
                header('Content-Type:text/html; charset=utf-8');
                exit($data);
            case 'AJAX_UPLOAD':
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:text/html; charset=utf-8');
                exit(json_encode($data,$json_option));
            default :
                // 用于扩展其他返回格式数据
                Hook::listen('ajax_return',$data);
        }

    }

    /**
     *
     * @param number $totalSize 总数
     * @param number $pageSize  总页数
     * @param number $currentPage 当前页
     * @param number $listRows 每页显示条数
     * @param string $pageParam 分页参数
     * @param string $pageLink 分页链接
     * @param string $static 是否为静态链接
     */
    protected function page($totalSize = 1, $pageSize = 0, $currentPage = 1, $listRows = 6, $pageParam = '', $pageLink = '', $static = FALSE) {
        if ($pageSize == 0) {
            $pageSize = C("PAGE_LISTROWS");
        }
        if (empty($pageParam)) {
            $pageParam = C("VAR_PAGE");
        }

        $page = new \Page($totalSize, $pageSize, $currentPage, $listRows, $pageParam, $pageLink, $static);

        $page->setLinkWraper("li");
        if(sp_is_mobile()){
            $page->SetPager('default', '{prev}&nbsp;{list}&nbsp;{next}', array("listlong" => "4", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => ""));
        }else{
            $page->SetPager('default', '{first}{prev}&nbsp;{liststart}{list}{listend}&nbsp;{next}{last}', array("listlong" => "4", "first" => "首页", "last" => "尾页", "prev" => "上一页", "next" => "下一页", "list" => "*", "disabledclass" => ""));
        }

        return $page;
    }

    /**
     *
     * @param number $totalSize 总数
     * @param number $pageSize  总页数
     * @param number $currentPage 当前页
     * @param number $listRows 每页显示条数
     * @param string $pageParam 分页参数
     * @param string $pageLink 分页链接
     * @param string $static 是否为静态链接
     */
    protected function pages($totalSize = 1, $pageSize = 0, $currentPage = 1, $listRows = 6, $pageParam = '', $pageLink = '', $static = FALSE) {
        if ($pageSize == 0) {
            $pageSize = C("PAGE_LISTROWS");
        }
        if (empty($pageParam)) {
            $pageParam = C("VAR_PAGE");
        }

        $page = new \Page($totalSize, $pageSize, $currentPage, $listRows, $pageParam, $pageLink, $static);

        $page->setLinkWraper("");
        if(sp_is_mobile()){
            $page->SetPager('new', '{prev}&nbsp;{list}&nbsp;{next}', array("listlong" => "4", "prev" => "<", "next" => ">", "list" => "*", "disabledclass" => ""));
        }else{
            $page->SetPager('new', '{prev}&nbsp;{liststart}{list}{listend}&nbsp;{next}', array("listlong" => "10", "prev" => "<", "next" => ">", "list" => "*", "disabledclass" => ""));
        }

        return $page;
    }

    /**
     *
     * @param number $totalSize 总数
     * @param number $pageSize  总页数
     * @param number $currentPage 当前页
     * @param number $listRows 每页显示条数
     * @param string $pageParam 分页参数
     * @param string $pageLink 分页链接
     * @param string $static 是否为静态链接
     */
    protected function page_goods($totalSize = 1, $pageSize = 0, $currentPage = 1, $listRows = 6, $pageParam = '', $pageLink = '', $static = FALSE) {
        if ($pageSize == 0) {
            $pageSize = C("PAGE_LISTROWS");
        }
        if (empty($pageParam)) {
            $pageParam = C("VAR_PAGE");
        }

        $page = new \Page($totalSize, $pageSize, $currentPage, $listRows, $pageParam, $pageLink, $static);

        $page->setLinkWraper("li");
        if(sp_is_mobile()){
            $page->SetPager('goods', '{prev}&nbsp;{list}&nbsp;{next}', array("listlong" => "4", "prev" => "<", "next" => ">", "list" => "*", "disabledclass" => ""));
        }else{
            $page->SetPager('goods', '{first}{prev}&nbsp;{liststart}{list}{listend}&nbsp;{next}{last}', array("listlong" => "10", "first" => "<<", "last" => ">>", "prev" => "<", "next" => ">", "list" => "*", "disabledclass" => ""));
        }

        return $page;
    }

    //空操作
    public function _empty() {
        $this->error('该页面不存在!');
    }

    /**
     * 检查操作频率
     * @param int $duration 距离最后一次操作的时长
     */
    protected function check_last_action($duration){

        $action=MODULE_NAME."-".CONTROLLER_NAME."-".ACTION_NAME;
        $time=time();

        $session_last_action=session('last_action');
        if(!empty($session_last_action['action']) && $action==$session_last_action['action']){
            $mduration=$time-$session_last_action['time'];
            if($duration>$mduration){
                $this->error("您的操作太过频繁,请稍后再试~~~");
            }else{
                session('last_action.time',$time);
            }
        }else{
            session('last_action.action',$action);
            session('last_action.time',$time);
        }
    }

    /**
     * 模板主题设置
     * @access protected
     * @param string $theme 模版主题
     * @return Action
     */
    public function theme($theme){
        $this->theme=$theme;
        return $this;
    }

}