BaseController.php 10.3 KB
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace cmf\controller;

use cmf\lib\Upload;
use think\Controller;
use think\Request;
use think\View;
use think\Config;
use think\Db;

class BaseController extends Controller
{
    /**
     * 构造函数
     * @param Request $request Request对象
     * @access public
     */
    public function __construct(Request $request = null)
    {
        if (!cmf_is_installed() && $request->module() != 'install') {
            header('Location: ' . cmf_get_root() . '/?s=install');
            exit;
        }

        if (is_null($request)) {
            $request = Request::instance();
        }

        $this->request = $request;

        $this->_initializeView();
        $this->view = View::instance(Config::get('template'), Config::get('view_replace_str'));


        // 控制器初始化
        $this->_initialize();

        // 前置操作方法
        if ($this->beforeActionList) {
            foreach ($this->beforeActionList as $method => $options) {
                is_numeric($method) ?
                    $this->beforeAction($options) :
                    $this->beforeAction($method, $options);
            }
        }
    }


    // 初始化视图配置
    protected function _initializeView()
    {
    }

    /**
     *  排序 排序字段为list_orders数组 POST 排序字段为:list_order
     */
    protected function listOrders($model)
    {
        if (!is_object($model)) {
            return false;
        }

        $pk  = $model->getPk(); //获取主键名称
        $ids = $this->request->post("list_orders/a");

        if (!empty($ids)) {
            foreach ($ids as $key => $r) {
                $data['list_order'] = $r;
                $model->where([$pk => $key])->update($data);
            }

        }

        return true;
    }

    /**
     * 生成6位随机数
     * @param   string
     * @return  boolean
     */
    protected function generate_code($length = 6) {
        $min = pow(10 , ($length - 1));
        $max = pow(10, $length) - 1;
        return rand($min, $max);
    }

    /**
     *  百荣科技短信接口
     */
    protected function sendSMS($mobile,$content){
        date_default_timezone_set('PRC');//设置时区
        $url 		= "http://www.ztsms.cn/sendNSms.do";//提交地址
        $username 	= config('cmf_sms_user');//用户名
        $password 	= config('cmf_sms_password');//原密码
        $data = array(
            'content' 	=> '【天津巧虎】短信验证码:'.$content.'。10分钟内有效,请尽快登录。详询400-110-7575。',//短信内容
            'mobile' 	=> $mobile,//手机号码
            'productid' => '676767',//产品id
            'xh'		=> ''//小号
        );
        $isTranscoding = false;
        $timeout = 30;
        $data['content'] = $isTranscoding === true ? mb_convert_encoding($data['content'], "UTF-8") : $data['content'];
        $data['username']=$username;
        $data['tkey'] 	= date('YmdHis');
        $data['password'] = md5(md5($password) . $data['tkey']);
        $curl = curl_init();// 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        if(isset($_SERVER['HTTP_USER_AGENT'])) {
            curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        }
        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS,  http_build_query($data)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, false); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        $result = curl_exec($curl); // 执行操作
        if (curl_errno($curl)){
            echo 'Error POST'.curl_error($curl);
        }
        return $result;
    }

    /**
     *  百荣科技短信通知接口
     */
    protected function sendSMSS($mobile, $content){
        date_default_timezone_set('PRC');//设置时区
        $url 		= "http://www.ztsms.cn/sendNSms.do";//提交地址
        $username 	= config('cmf_sms_user');//用户名
        $password 	= config('cmf_sms_password');//原密码
        $data = array(
            'content' 	=> "【天津巧虎】" . $content,//短信内容
            'mobile' 	=> $mobile,//手机号码
            'productid' => '887361',//产品id
            'xh'		=> ''//小号
        );
        $isTranscoding = false;
        $timeout = 30;
        $data['content'] = $isTranscoding === true ? mb_convert_encoding($data['content'], "UTF-8") : $data['content'];
        $data['username']=$username;
        $data['tkey'] 	= date('YmdHis');
        $data['password'] = md5(md5($password) . $data['tkey']);
        $curl = curl_init();// 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS,  http_build_query($data)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, false); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        $result = curl_exec($curl); // 执行操作
        if (curl_errno($curl)){
            echo 'Error POST'.curl_error($curl);
        }
        return $result;
    }

    /**
     * 上传素材
     * @param name:file type:varchar require:1 default: other: desc:素材内容
     * @param name:filetype type:varchar require:1 default: other: desc:素材类型
     * @param name:app type:varchar require:1 default: other: desc:素材存储路径
     *
     */
    protected function upload() {
        if ($this->request->isPost()) {
            $uploader = new Upload();
//            return ["code"=>40004, "msg"=>$this->request->param(), "data"=>[$this->request->file()]];

            $result = $uploader->upload();

            if ($result === false) {
                return [0, $uploader->getError(),''];
            } else {
                return [1, "上传成功!", $result];
            }
        }
    }

    // curl方法
    protected function curl($url, $post = null) {
        // 初始化
        $curl = curl_init();
        // 设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        // 设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_NOBODY, 0);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        // 设置获取的信息以文件流的形式返回,而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        if($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            //把POST的变量加上
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
        }
        // 执行命令
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            $data = curl_error($curl);
        }
        return $data;
    }

    /**
     * 生成二维码
     * @param $url 地址(含域名)
     * @param $errorLevel 容错级别
     * @param $size 生成图片大小
     */
    protected function createQRcode($url,$errorLevel,$size,$floder = 'qrcode') {
        require VENDOR_PATH.'phpqrcode/phpqrcode.php';
        $QRcode = new \QRcode();
        $errorCorrectionLevel = $errorLevel;    //容错级别
        $matrixPointSize = $size;           //生成图片大小
        //生成二维码图片
        $data = './upload/';
        $flodername =  $floder.'/' . date("Ymd", time());
        $png = uniqid() . '.png';
        $filename = $data.$flodername . '/' . $png;
        if (!file_exists($data.$flodername)) {
            mkdir($data.$flodername, 0777, true);
        }
        $QRcode->png($url, $filename, $errorCorrectionLevel, $matrixPointSize);
        return $flodername . '/' . $png;
    }

    /**
     * 单表数据查询(此为通用方法:如有特殊要求,需在控制器单独编写)
     * @param string $table 表名
     * @param array $where 查询的where条件
     * @param int $list 是否为查询多条数据(值不为为0时为多条查询,值为1时为查询所有数据,其他为分页查询)
     * @param array $order 排序条件
     * @param int $listRow 查询分页条数($list为1时使用)
     * @return array 返回的列表数据
     */
    protected function singleData($table, $where = [], $list = 0, $order = [], $listRow = 0) {
//        $exist = Db::query('show tables like ' . Config::get('database.prefix') . $table);
//        return $exist;
        $table_model = Db::name($table)->where($where);
        if(!empty($order)) {
            $table_model = $table_model->order($order);
        }
        if(empty($list)) {
            $data = $table_model->find();
        } elseif($list == 1) {
            $data = $table_model->select()->toArray();
        } else {
            if(empty($listRow)) {
                $listRow = Config::get('paginate.list_rows');
            }
            $data = $table_model->paginate($listRow);
        }
        return $data;
    }

}